testing: allow to select tests
[org-mode/org-tableheadings.git] / lisp / org.el
blobbb478083bcba98e9a8b86fc6cd9dad911c9222ea
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 orgtbl-mode "org-table" (&optional arg))
128 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
129 (declare-function org-beamer-mode "ox-beamer" ())
130 (declare-function org-table-blank-field "org-table" ())
131 (declare-function org-table-edit-field "org-table" (arg))
132 (declare-function org-table-insert-row "org-table" (&optional arg))
133 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
134 (declare-function org-table-set-constants "org-table" ())
135 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
136 (declare-function org-id-get-create "org-id" (&optional force))
137 (declare-function org-add-archive-files "org-archive" (files))
138 (declare-function org-id-find-id-file "org-id" (id))
139 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
140 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
141 (declare-function org-agenda-redo "org-agenda" (&optional all))
142 (declare-function org-table-align "org-table" ())
143 (declare-function org-table-begin "org-table" (&optional table-type))
144 (declare-function org-table-end "org-table" (&optional table-type))
145 (declare-function org-table-paste-rectangle "org-table" ())
146 (declare-function org-table-maybe-eval-formula "org-table" ())
147 (declare-function org-table-maybe-recalculate-line "org-table" ())
149 (declare-function org-element--parse-objects "org-element"
150 (beg end acc restriction))
151 (declare-function org-element-at-point "org-element" (&optional keep-trail))
152 (declare-function org-element-cache-reset "org-element" (&optional all))
153 (declare-function org-element-contents "org-element" (element))
154 (declare-function org-element-context "org-element" (&optional element))
155 (declare-function org-element-interpret-data "org-element"
156 (data &optional parent))
157 (declare-function org-element-map "org-element"
158 (data types fun &optional info first-match no-recursion))
159 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
160 (declare-function org-element-parse-buffer "org-element"
161 (&optional granularity visible-only))
162 (declare-function org-element-property "org-element" (property element))
163 (declare-function org-element-put-property "org-element"
164 (element property value))
165 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
166 (declare-function org-element--parse-objects "org-element"
167 (beg end acc restriction))
168 (declare-function org-element-parse-buffer "org-element"
169 (&optional granularity visible-only))
170 (declare-function org-element-restriction "org-element" (element))
171 (declare-function org-element-type "org-element" (element))
173 (defsubst org-uniquify (list)
174 "Non-destructively remove duplicate elements from LIST."
175 (let ((res (copy-sequence list))) (delete-dups res)))
177 ;; load languages based on value of `org-babel-load-languages'
178 (defvar org-babel-load-languages)
180 ;;;###autoload
181 (defun org-babel-do-load-languages (sym value)
182 "Load the languages defined in `org-babel-load-languages'."
183 (set-default sym value)
184 (mapc (lambda (pair)
185 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
186 (if active
187 (progn
188 (require (intern (concat "ob-" lang))))
189 (progn
190 (funcall 'fmakunbound
191 (intern (concat "org-babel-execute:" lang)))
192 (funcall 'fmakunbound
193 (intern (concat "org-babel-expand-body:" lang)))))))
194 org-babel-load-languages))
196 ;;;###autoload
197 (defun org-babel-load-file (file &optional compile)
198 "Load Emacs Lisp source code blocks in the Org-mode FILE.
199 This function exports the source code using `org-babel-tangle'
200 and then loads the resulting file using `load-file'. With prefix
201 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
202 file to byte-code before it is loaded."
203 (interactive "fFile to load: \nP")
204 (require 'ob-core)
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))
5516 ;; Make sure that file local variables are set.
5517 (report-errors "File local-variables error: %s"
5518 (hack-local-variables)))
5520 ;; Update `customize-package-emacs-version-alist'
5521 (add-to-list 'customize-package-emacs-version-alist
5522 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5523 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5524 ("8.0" . "24.4")))
5526 (defvar org-mode-transpose-word-syntax-table
5527 (let ((st (make-syntax-table)))
5528 (mapc (lambda(c) (modify-syntax-entry
5529 (string-to-char (car c)) "w p" st))
5530 org-emphasis-alist)
5531 st))
5533 (when (fboundp 'abbrev-table-put)
5534 (abbrev-table-put org-mode-abbrev-table
5535 :parents (list text-mode-abbrev-table)))
5537 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5539 (defsubst org-fix-ellipsis-at-bol ()
5540 (save-excursion (goto-char (window-start)) (recenter 0)))
5542 (defun org-find-invisible-foreground ()
5543 (let ((candidates (remove
5544 "unspecified-bg"
5545 (nconc
5546 (list (face-background 'default)
5547 (face-background 'org-default))
5548 (mapcar
5549 (lambda (alist)
5550 (when (boundp alist)
5551 (cdr (assoc 'background-color (symbol-value alist)))))
5552 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5553 (list (face-foreground 'org-hide))))))
5554 (car (remove nil candidates))))
5556 (defun org-current-time (&optional rounding-minutes past)
5557 "Current time, possibly rounded to ROUNDING-MINUTES.
5558 When ROUNDING-MINUTES is not an integer, fall back on the car of
5559 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5560 the rounding returns a past time."
5561 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5562 (car org-time-stamp-rounding-minutes)))
5563 (time (decode-time)) res)
5564 (if (< r 1)
5565 (current-time)
5566 (setq res
5567 (apply 'encode-time
5568 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5569 (nthcdr 2 time))))
5570 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5571 (seconds-to-time (- (org-float-time res) (* r 60)))
5572 res))))
5574 (defun org-today ()
5575 "Return today date, considering `org-extend-today-until'."
5576 (time-to-days
5577 (time-subtract (current-time)
5578 (list 0 (* 3600 org-extend-today-until) 0))))
5580 ;;;; Font-Lock stuff, including the activators
5582 (defvar org-mouse-map (make-sparse-keymap))
5583 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5584 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5585 (when org-mouse-1-follows-link
5586 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5587 (when org-tab-follows-link
5588 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5589 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5591 (require 'font-lock)
5593 (defconst org-non-link-chars "]\t\n\r<>")
5594 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5595 "shell" "elisp" "doi" "message"))
5596 (defvar org-link-types-re nil
5597 "Matches a link that has a url-like prefix like \"http:\"")
5598 (defvar org-link-re-with-space nil
5599 "Matches a link with spaces, optional angular brackets around it.")
5600 (defvar org-link-re-with-space2 nil
5601 "Matches a link with spaces, optional angular brackets around it.")
5602 (defvar org-link-re-with-space3 nil
5603 "Matches a link with spaces, only for internal part in bracket links.")
5604 (defvar org-angle-link-re nil
5605 "Matches link with angular brackets, spaces are allowed.")
5606 (defvar org-plain-link-re nil
5607 "Matches plain link, without spaces.")
5608 (defvar org-bracket-link-regexp nil
5609 "Matches a link in double brackets.")
5610 (defvar org-bracket-link-analytic-regexp nil
5611 "Regular expression used to analyze links.
5612 Here is what the match groups contain after a match:
5613 1: http:
5614 2: http
5615 3: path
5616 4: [desc]
5617 5: desc")
5618 (defvar org-bracket-link-analytic-regexp++ nil
5619 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5620 (defvar org-any-link-re nil
5621 "Regular expression matching any link.")
5623 (defconst org-match-sexp-depth 3
5624 "Number of stacked braces for sub/superscript matching.")
5626 (defun org-create-multibrace-regexp (left right n)
5627 "Create a regular expression which will match a balanced sexp.
5628 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5629 as single character strings.
5630 The regexp returned will match the entire expression including the
5631 delimiters. It will also define a single group which contains the
5632 match except for the outermost delimiters. The maximum depth of
5633 stacked delimiters is N. Escaping delimiters is not possible."
5634 (let* ((nothing (concat "[^" left right "]*?"))
5635 (or "\\|")
5636 (re nothing)
5637 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5638 (while (> n 1)
5639 (setq n (1- n)
5640 re (concat re or next)
5641 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5642 (concat left "\\(" re "\\)" right)))
5644 (defvar org-match-substring-regexp
5645 (concat
5646 "\\(\\S-\\)\\([_^]\\)\\("
5647 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5648 "\\|"
5649 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5650 "\\|"
5651 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5652 "The regular expression matching a sub- or superscript.")
5654 (defvar org-match-substring-with-braces-regexp
5655 (concat
5656 "\\(\\S-\\)\\([_^]\\)\\("
5657 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5658 "\\)")
5659 "The regular expression matching a sub- or superscript, forcing braces.")
5661 (defun org-make-link-regexps ()
5662 "Update the link regular expressions.
5663 This should be called after the variable `org-link-types' has changed."
5664 (setq org-link-types-re
5665 (concat
5666 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5667 org-link-re-with-space
5668 (concat
5669 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5670 "\\([^" org-non-link-chars " ]"
5671 "[^" org-non-link-chars "]*"
5672 "[^" org-non-link-chars " ]\\)>?")
5673 org-link-re-with-space2
5674 (concat
5675 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5676 "\\([^" org-non-link-chars " ]"
5677 "[^\t\n\r]*"
5678 "[^" org-non-link-chars " ]\\)>?")
5679 org-link-re-with-space3
5680 (concat
5681 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5682 "\\([^" org-non-link-chars " ]"
5683 "[^\t\n\r]*\\)")
5684 org-angle-link-re
5685 (concat
5686 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5687 "\\([^" org-non-link-chars " ]"
5688 "[^" org-non-link-chars "]*"
5689 "\\)>")
5690 org-plain-link-re
5691 (concat
5692 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5693 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5694 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5695 org-bracket-link-regexp
5696 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5697 org-bracket-link-analytic-regexp
5698 (concat
5699 "\\[\\["
5700 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5701 "\\([^]]+\\)"
5702 "\\]"
5703 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5704 "\\]")
5705 org-bracket-link-analytic-regexp++
5706 (concat
5707 "\\[\\["
5708 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5709 "\\([^]]+\\)"
5710 "\\]"
5711 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5712 "\\]")
5713 org-any-link-re
5714 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5715 org-angle-link-re "\\)\\|\\("
5716 org-plain-link-re "\\)")))
5718 (org-make-link-regexps)
5720 (defvar org-emph-face nil)
5722 (defun org-do-emphasis-faces (limit)
5723 "Run through the buffer and add overlays to emphasized strings."
5724 (let (rtn a)
5725 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5726 (if (not (= (char-after (match-beginning 3))
5727 (char-after (match-beginning 4))))
5728 (progn
5729 (setq rtn t)
5730 (setq a (assoc (match-string 3) org-emphasis-alist))
5731 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5732 'face
5733 (nth 1 a))
5734 (and (nth 2 a)
5735 (org-remove-flyspell-overlays-in
5736 (match-beginning 0) (match-end 0)))
5737 (add-text-properties (match-beginning 2) (match-end 2)
5738 '(font-lock-multiline t org-emphasis t))
5739 (when org-hide-emphasis-markers
5740 (add-text-properties (match-end 4) (match-beginning 5)
5741 '(invisible org-link))
5742 (add-text-properties (match-beginning 3) (match-end 3)
5743 '(invisible org-link)))))
5744 (backward-char 1))
5745 rtn))
5747 (defun org-emphasize (&optional char)
5748 "Insert or change an emphasis, i.e. a font like bold or italic.
5749 If there is an active region, change that region to a new emphasis.
5750 If there is no region, just insert the marker characters and position
5751 the cursor between them.
5752 CHAR should be the marker character. If it is a space, it means to
5753 remove the emphasis of the selected region.
5754 If CHAR is not given (for example in an interactive call) it will be
5755 prompted for."
5756 (interactive)
5757 (let ((erc org-emphasis-regexp-components)
5758 (prompt "")
5759 (string "") beg end move c s)
5760 (if (org-region-active-p)
5761 (setq beg (region-beginning) end (region-end)
5762 string (buffer-substring beg end))
5763 (setq move t))
5765 (unless char
5766 (message "Emphasis marker or tag: [%s]"
5767 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5768 (setq char (read-char-exclusive)))
5769 (if (equal char ?\ )
5770 (setq s "" move nil)
5771 (unless (assoc (char-to-string char) org-emphasis-alist)
5772 (user-error "No such emphasis marker: \"%c\"" char))
5773 (setq s (char-to-string char)))
5774 (while (and (> (length string) 1)
5775 (equal (substring string 0 1) (substring string -1))
5776 (assoc (substring string 0 1) org-emphasis-alist))
5777 (setq string (substring string 1 -1)))
5778 (setq string (concat s string s))
5779 (if beg (delete-region beg end))
5780 (unless (or (bolp)
5781 (string-match (concat "[" (nth 0 erc) "\n]")
5782 (char-to-string (char-before (point)))))
5783 (insert " "))
5784 (unless (or (eobp)
5785 (string-match (concat "[" (nth 1 erc) "\n]")
5786 (char-to-string (char-after (point)))))
5787 (insert " ") (backward-char 1))
5788 (insert string)
5789 (and move (backward-char 1))))
5791 (defconst org-nonsticky-props
5792 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5794 (defsubst org-rear-nonsticky-at (pos)
5795 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5797 (defun org-activate-plain-links (limit)
5798 "Run through the buffer and add overlays to links."
5799 (let (f hl)
5800 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5801 (not (org-in-src-block-p)))
5802 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5803 (setq f (get-text-property (match-beginning 0) 'face))
5804 (setq hl (org-match-string-no-properties 0))
5805 (if (or (eq f 'org-tag)
5806 (and (listp f) (memq 'org-tag f)))
5808 (add-text-properties (match-beginning 0) (match-end 0)
5809 (list 'mouse-face 'highlight
5810 'face 'org-link
5811 'htmlize-link `(:uri ,hl)
5812 'keymap org-mouse-map))
5813 (org-rear-nonsticky-at (match-end 0)))
5814 t)))
5816 (defun org-activate-code (limit)
5817 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5818 (progn
5819 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5820 (remove-text-properties (match-beginning 0) (match-end 0)
5821 '(display t invisible t intangible t))
5822 t)))
5824 (defcustom org-src-fontify-natively nil
5825 "When non-nil, fontify code in code blocks."
5826 :type 'boolean
5827 :version "24.1"
5828 :group 'org-appearance
5829 :group 'org-babel)
5831 (defcustom org-allow-promoting-top-level-subtree nil
5832 "When non-nil, allow promoting a top level subtree.
5833 The leading star of the top level headline will be replaced
5834 by a #."
5835 :type 'boolean
5836 :version "24.1"
5837 :group 'org-appearance)
5839 (defun org-fontify-meta-lines-and-blocks (limit)
5840 (condition-case nil
5841 (org-fontify-meta-lines-and-blocks-1 limit)
5842 (error (message "org-mode fontification error"))))
5844 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5845 "Fontify #+ lines and blocks."
5846 (let ((case-fold-search t))
5847 (if (re-search-forward
5848 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5849 limit t)
5850 (let ((beg (match-beginning 0))
5851 (block-start (match-end 0))
5852 (block-end nil)
5853 (lang (match-string 7))
5854 (beg1 (line-beginning-position 2))
5855 (dc1 (downcase (match-string 2)))
5856 (dc3 (downcase (match-string 3)))
5857 end end1 quoting block-type ovl)
5858 (cond
5859 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5860 ;; a single line of backend-specific content
5861 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5862 (remove-text-properties (match-beginning 0) (match-end 0)
5863 '(display t invisible t intangible t))
5864 (add-text-properties (match-beginning 1) (match-end 3)
5865 '(font-lock-fontified t face org-meta-line))
5866 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5867 '(font-lock-fontified t face org-block))
5868 ; for backend-specific code
5870 ((and (match-end 4) (equal dc3 "+begin"))
5871 ;; Truly a block
5872 (setq block-type (downcase (match-string 5))
5873 quoting (member block-type org-protecting-blocks))
5874 (when (re-search-forward
5875 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5876 nil t) ;; on purpose, we look further than LIMIT
5877 (setq end (min (point-max) (match-end 0))
5878 end1 (min (point-max) (1- (match-beginning 0))))
5879 (setq block-end (match-beginning 0))
5880 (when quoting
5881 (remove-text-properties beg end
5882 '(display t invisible t intangible t)))
5883 (add-text-properties
5884 beg end
5885 '(font-lock-fontified t font-lock-multiline t))
5886 (add-text-properties beg beg1 '(face org-meta-line))
5887 (add-text-properties end1 (min (point-max) (1+ end))
5888 '(face org-meta-line)) ; for end_src
5889 (cond
5890 ((and lang (not (string= lang "")) org-src-fontify-natively)
5891 (org-src-font-lock-fontify-block lang block-start block-end)
5892 ;; remove old background overlays
5893 (mapc (lambda (ov)
5894 (if (eq (overlay-get ov 'face) 'org-block-background)
5895 (delete-overlay ov)))
5896 (overlays-at (/ (+ beg1 block-end) 2)))
5897 ;; add a background overlay
5898 (setq ovl (make-overlay beg1 block-end))
5899 (overlay-put ovl 'face 'org-block-background)
5900 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5901 (quoting
5902 (add-text-properties beg1 (min (point-max) (1+ end1))
5903 '(face org-block))) ; end of source block
5904 ((not org-fontify-quote-and-verse-blocks))
5905 ((string= block-type "quote")
5906 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5907 ((string= block-type "verse")
5908 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5909 (add-text-properties beg beg1 '(face org-block-begin-line))
5910 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5911 '(face org-block-end-line))
5913 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
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 (add-text-properties
5930 beg (match-end 0)
5931 '(font-lock-fontified t face org-meta-line))
5933 ((member dc3 '(" " ""))
5934 (add-text-properties
5935 beg (match-end 0)
5936 '(font-lock-fontified t face font-lock-comment-face)))
5937 ((not (member (char-after beg) '(?\ ?\t)))
5938 ;; just any other in-buffer setting, but not indented
5939 (add-text-properties
5940 beg (match-end 0)
5941 '(font-lock-fontified t face org-meta-line))
5943 (t nil))))))
5945 (defun org-activate-angle-links (limit)
5946 "Run through the buffer and add overlays to links."
5947 (if (and (re-search-forward org-angle-link-re limit t)
5948 (not (org-in-src-block-p)))
5949 (progn
5950 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5951 (add-text-properties (match-beginning 0) (match-end 0)
5952 (list 'mouse-face 'highlight
5953 'keymap org-mouse-map))
5954 (org-rear-nonsticky-at (match-end 0))
5955 t)))
5957 (defun org-activate-footnote-links (limit)
5958 "Run through the buffer and add overlays to footnotes."
5959 (let ((fn (org-footnote-next-reference-or-definition limit)))
5960 (when fn
5961 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5962 (org-remove-flyspell-overlays-in beg end)
5963 (add-text-properties beg end
5964 (list 'mouse-face 'highlight
5965 'keymap org-mouse-map
5966 'help-echo
5967 (if (= (point-at-bol) beg)
5968 "Footnote definition"
5969 "Footnote reference")
5970 'font-lock-fontified t
5971 'font-lock-multiline t
5972 'face 'org-footnote))))))
5974 (defun org-activate-bracket-links (limit)
5975 "Run through the buffer and add overlays to bracketed links."
5976 (if (and (re-search-forward org-bracket-link-regexp limit t)
5977 (not (org-in-src-block-p)))
5978 (let* ((hl (org-match-string-no-properties 1))
5979 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
5980 (ip (org-maybe-intangible
5981 (list 'invisible 'org-link
5982 'keymap org-mouse-map 'mouse-face 'highlight
5983 'font-lock-multiline t 'help-echo help
5984 'htmlize-link `(:uri ,hl))))
5985 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5986 'font-lock-multiline t 'help-echo help
5987 'htmlize-link `(:uri ,hl))))
5988 ;; We need to remove the invisible property here. Table narrowing
5989 ;; may have made some of this invisible.
5990 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5991 (remove-text-properties (match-beginning 0) (match-end 0)
5992 '(invisible nil))
5993 (if (match-end 3)
5994 (progn
5995 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5996 (org-rear-nonsticky-at (match-beginning 3))
5997 (add-text-properties (match-beginning 3) (match-end 3) vp)
5998 (org-rear-nonsticky-at (match-end 3))
5999 (add-text-properties (match-end 3) (match-end 0) ip)
6000 (org-rear-nonsticky-at (match-end 0)))
6001 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
6002 (org-rear-nonsticky-at (match-beginning 1))
6003 (add-text-properties (match-beginning 1) (match-end 1) vp)
6004 (org-rear-nonsticky-at (match-end 1))
6005 (add-text-properties (match-end 1) (match-end 0) ip)
6006 (org-rear-nonsticky-at (match-end 0)))
6007 t)))
6009 (defun org-activate-dates (limit)
6010 "Run through the buffer and add overlays to dates."
6011 (if (and (re-search-forward org-tsr-regexp-both limit t)
6012 (not (equal (char-before (match-beginning 0)) 91)))
6013 (progn
6014 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6015 (add-text-properties (match-beginning 0) (match-end 0)
6016 (list 'mouse-face 'highlight
6017 'keymap org-mouse-map))
6018 (org-rear-nonsticky-at (match-end 0))
6019 (when org-display-custom-times
6020 (if (match-end 3)
6021 (org-display-custom-time (match-beginning 3) (match-end 3)))
6022 (org-display-custom-time (match-beginning 1) (match-end 1)))
6023 t)))
6025 (defvar org-target-link-regexp nil
6026 "Regular expression matching radio targets in plain text.")
6027 (make-variable-buffer-local 'org-target-link-regexp)
6028 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
6029 "Regular expression matching a link target.")
6030 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
6031 "Regular expression matching a radio target.")
6032 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
6033 "Regular expression matching any target.")
6035 (defun org-activate-target-links (limit)
6036 "Run through the buffer and add overlays to target matches."
6037 (when org-target-link-regexp
6038 (let ((case-fold-search t))
6039 (if (re-search-forward org-target-link-regexp limit t)
6040 (progn
6041 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6042 (add-text-properties (match-beginning 0) (match-end 0)
6043 (list 'mouse-face 'highlight
6044 'keymap org-mouse-map
6045 'help-echo "Radio target link"
6046 'org-linked-text t))
6047 (org-rear-nonsticky-at (match-end 0))
6048 t)))))
6050 (defun org-update-radio-target-regexp ()
6051 "Find all radio targets in this file and update the regular expression."
6052 (interactive)
6053 (when (memq 'radio org-activate-links)
6054 (setq org-target-link-regexp
6055 (org-make-target-link-regexp (org-all-targets 'radio)))
6056 (org-restart-font-lock)))
6058 (defun org-hide-wide-columns (limit)
6059 (let (s e)
6060 (setq s (text-property-any (point) (or limit (point-max))
6061 'org-cwidth t))
6062 (when s
6063 (setq e (next-single-property-change s 'org-cwidth))
6064 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6065 (goto-char e)
6066 t)))
6068 (defvar org-latex-and-related-regexp nil
6069 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6070 (defvar org-match-substring-regexp)
6071 (defvar org-match-substring-with-braces-regexp)
6073 (defun org-compute-latex-and-related-regexp ()
6074 "Compute regular expression for LaTeX, entities and sub/superscript.
6075 Result depends on variable `org-highlight-latex-and-related'."
6076 (org-set-local
6077 'org-latex-and-related-regexp
6078 (let* ((re-sub
6079 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6080 ((eq org-use-sub-superscripts '{})
6081 (list org-match-substring-with-braces-regexp))
6082 (org-use-sub-superscripts (list org-match-substring-regexp))))
6083 (re-latex
6084 (when (memq 'latex org-highlight-latex-and-related)
6085 (let ((matchers (plist-get org-format-latex-options :matchers)))
6086 (delq nil
6087 (mapcar (lambda (x)
6088 (and (member (car x) matchers) (nth 1 x)))
6089 org-latex-regexps)))))
6090 (re-entities
6091 (when (memq 'entities org-highlight-latex-and-related)
6092 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6093 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6095 (defun org-do-latex-and-related (limit)
6096 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6097 LIMIT bounds the search for syntax to highlight. Stop at first
6098 highlighted object, if any. Return t if some highlighting was
6099 done, nil otherwise."
6100 (when (org-string-nw-p org-latex-and-related-regexp)
6101 (catch 'found
6102 (while (re-search-forward org-latex-and-related-regexp limit t)
6103 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6104 'face))
6105 '(org-code org-verbatim underline))
6106 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6107 '(?_ ?^))
6109 0)))
6110 (font-lock-prepend-text-property
6111 (+ offset (match-beginning 0)) (match-end 0)
6112 'face 'org-latex-and-related)
6113 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6114 '(font-lock-multiline t)))
6115 (throw 'found t)))
6116 nil)))
6118 (defun org-restart-font-lock ()
6119 "Restart `font-lock-mode', to force refontification."
6120 (when (and (boundp 'font-lock-mode) font-lock-mode)
6121 (font-lock-mode -1)
6122 (font-lock-mode 1)))
6124 (defun org-all-targets (&optional radio)
6125 "Return a list of all targets in this file.
6126 When optional argument RADIO is non-nil, only find radio
6127 targets."
6128 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
6129 (save-excursion
6130 (goto-char (point-min))
6131 (while (re-search-forward re nil t)
6132 ;; Make sure point is really within the object.
6133 (backward-char)
6134 (let ((obj (org-element-context)))
6135 (when (memq (org-element-type obj) '(radio-target target))
6136 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
6137 rtn)))
6139 (defun org-make-target-link-regexp (targets)
6140 "Make regular expression matching all strings in TARGETS.
6141 The regular expression finds the targets also if there is a line break
6142 between words."
6143 (and targets
6144 (concat
6145 "\\<\\("
6146 (mapconcat
6147 (lambda (x)
6148 (setq x (regexp-quote x))
6149 (while (string-match " +" x)
6150 (setq x (replace-match "\\s-+" t t x)))
6152 targets
6153 "\\|")
6154 "\\)\\>")))
6156 (defun org-activate-tags (limit)
6157 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6158 (progn
6159 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6160 (add-text-properties (match-beginning 1) (match-end 1)
6161 (list 'mouse-face 'highlight
6162 'keymap org-mouse-map))
6163 (org-rear-nonsticky-at (match-end 1))
6164 t)))
6166 (defun org-outline-level ()
6167 "Compute the outline level of the heading at point.
6168 If this is called at a normal headline, the level is the number of stars.
6169 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6170 (save-excursion
6171 (if (not (condition-case nil
6172 (org-back-to-heading t)
6173 (error nil)))
6175 (looking-at org-outline-regexp)
6176 (1- (- (match-end 0) (match-beginning 0))))))
6178 (defvar org-font-lock-keywords nil)
6180 (defsubst org-re-property (property &optional literal)
6181 "Return a regexp matching a PROPERTY line.
6182 Match group 3 will be set to the value if it exists."
6183 (concat "^\\(?4:[ \t]*\\)\\(?1::\\(?2:"
6184 (if literal property (regexp-quote property))
6185 "\\):\\)[ \t]+\\(?3:[^ \t\r\n].*?\\)\\(?5:[ \t]*\\)$"))
6187 (defconst org-property-re
6188 (org-re-property ".*?" 'literal)
6189 "Regular expression matching a property line.
6190 There are four matching groups:
6191 1: :PROPKEY: including the leading and trailing colon,
6192 2: PROPKEY without the leading and trailing colon,
6193 3: PROPVAL without leading or trailing spaces,
6194 4: the indentation of the current line,
6195 5: trailing whitespace.")
6197 (defvar org-font-lock-hook nil
6198 "Functions to be called for special font lock stuff.")
6200 (defvar org-font-lock-set-keywords-hook nil
6201 "Functions that can manipulate `org-font-lock-extra-keywords'.
6202 This is called after `org-font-lock-extra-keywords' is defined, but before
6203 it is installed to be used by font lock. This can be useful if something
6204 needs to be inserted at a specific position in the font-lock sequence.")
6206 (defun org-font-lock-hook (limit)
6207 "Run `org-font-lock-hook' within LIMIT."
6208 (run-hook-with-args 'org-font-lock-hook limit))
6210 (defun org-set-font-lock-defaults ()
6211 "Set font lock defaults for the current buffer."
6212 (let* ((em org-fontify-emphasized-text)
6213 (lk org-activate-links)
6214 (org-font-lock-extra-keywords
6215 (list
6216 ;; Call the hook
6217 '(org-font-lock-hook)
6218 ;; Headlines
6219 `(,(if org-fontify-whole-heading-line
6220 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6221 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6222 (1 (org-get-level-face 1))
6223 (2 (org-get-level-face 2))
6224 (3 (org-get-level-face 3)))
6225 ;; Table lines
6226 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6227 (1 'org-table t))
6228 ;; Table internals
6229 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6230 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6231 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6232 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6233 ;; Drawers
6234 (list org-drawer-regexp '(0 'org-special-keyword t))
6235 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
6236 ;; Properties
6237 (list org-property-re
6238 '(1 'org-special-keyword t)
6239 '(3 'org-property-value t))
6240 ;; Links
6241 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6242 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6243 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6244 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6245 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6246 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6247 (if (memq 'footnote lk) '(org-activate-footnote-links))
6248 ;; Targets.
6249 (list org-any-target-regexp '(0 'org-target t))
6250 ;; Diary sexps.
6251 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6252 ;; Macro
6253 '("{{{.+}}}" (0 'org-macro t))
6254 '(org-hide-wide-columns (0 nil append))
6255 ;; TODO keyword
6256 (list (format org-heading-keyword-regexp-format
6257 org-todo-regexp)
6258 '(2 (org-get-todo-face 2) t))
6259 ;; DONE
6260 (if org-fontify-done-headline
6261 (list (format org-heading-keyword-regexp-format
6262 (concat
6263 "\\(?:"
6264 (mapconcat 'regexp-quote org-done-keywords "\\|")
6265 "\\)"))
6266 '(2 'org-headline-done t))
6267 nil)
6268 ;; Priorities
6269 '(org-font-lock-add-priority-faces)
6270 ;; Tags
6271 '(org-font-lock-add-tag-faces)
6272 ;; Tags groups
6273 (if (and org-group-tags org-tag-groups-alist)
6274 (list (concat org-outline-regexp-bol ".+\\(:"
6275 (regexp-opt (mapcar 'car org-tag-groups-alist))
6276 ":\\).*$")
6277 '(1 'org-tag-group prepend)))
6278 ;; Special keywords
6279 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6280 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6281 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6282 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6283 ;; Emphasis
6284 (if em
6285 (if (featurep 'xemacs)
6286 '(org-do-emphasis-faces (0 nil append))
6287 '(org-do-emphasis-faces)))
6288 ;; Checkboxes
6289 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6290 1 'org-checkbox prepend)
6291 (if (cdr (assq 'checkbox org-list-automatic-rules))
6292 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6293 (0 (org-get-checkbox-statistics-face) t)))
6294 ;; Description list items
6295 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6296 1 'org-list-dt prepend)
6297 ;; ARCHIVEd headings
6298 (list (concat
6299 org-outline-regexp-bol
6300 "\\(.*:" org-archive-tag ":.*\\)")
6301 '(1 'org-archived prepend))
6302 ;; Specials
6303 '(org-do-latex-and-related)
6304 '(org-fontify-entities)
6305 '(org-raise-scripts)
6306 ;; Code
6307 '(org-activate-code (1 'org-code t))
6308 ;; COMMENT
6309 (list (format org-heading-keyword-regexp-format
6310 (concat "\\("
6311 org-comment-string "\\|" org-quote-string
6312 "\\)"))
6313 '(2 'org-special-keyword t))
6314 ;; Blocks and meta lines
6315 '(org-fontify-meta-lines-and-blocks))))
6316 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6317 (run-hooks 'org-font-lock-set-keywords-hook)
6318 ;; Now set the full font-lock-keywords
6319 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6320 (org-set-local 'font-lock-defaults
6321 '(org-font-lock-keywords t nil nil backward-paragraph))
6322 (kill-local-variable 'font-lock-keywords) nil))
6324 (defun org-toggle-pretty-entities ()
6325 "Toggle the composition display of entities as UTF8 characters."
6326 (interactive)
6327 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6328 (org-restart-font-lock)
6329 (if org-pretty-entities
6330 (message "Entities are now displayed as UTF8 characters")
6331 (save-restriction
6332 (widen)
6333 (org-decompose-region (point-min) (point-max))
6334 (message "Entities are now displayed as plain text"))))
6336 (defvar org-custom-properties-overlays nil
6337 "List of overlays used for custom properties.")
6338 (make-variable-buffer-local 'org-custom-properties-overlays)
6340 (defun org-toggle-custom-properties-visibility ()
6341 "Display or hide properties in `org-custom-properties'."
6342 (interactive)
6343 (if org-custom-properties-overlays
6344 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6345 (setq org-custom-properties-overlays nil))
6346 (unless (not org-custom-properties)
6347 (save-excursion
6348 (save-restriction
6349 (widen)
6350 (goto-char (point-min))
6351 (while (re-search-forward org-property-re nil t)
6352 (mapc (lambda(p)
6353 (when (equal p (substring (match-string 1) 1 -1))
6354 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6355 (overlay-put o 'invisible t)
6356 (overlay-put o 'org-custom-property t)
6357 (push o org-custom-properties-overlays))))
6358 org-custom-properties)))))))
6360 (defun org-fontify-entities (limit)
6361 "Find an entity to fontify."
6362 (let (ee)
6363 (when org-pretty-entities
6364 (catch 'match
6365 (while (re-search-forward
6366 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6367 limit t)
6368 (if (and (not (org-in-indented-comment-line))
6369 (setq ee (org-entity-get (match-string 1)))
6370 (= (length (nth 6 ee)) 1))
6371 (let*
6372 ((end (if (equal (match-string 2) "{}")
6373 (match-end 2)
6374 (match-end 1))))
6375 (add-text-properties
6376 (match-beginning 0) end
6377 (list 'font-lock-fontified t))
6378 (compose-region (match-beginning 0) end
6379 (nth 6 ee) nil)
6380 (backward-char 1)
6381 (throw 'match t))))
6382 nil))))
6384 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6385 "Fontify string S like in Org-mode."
6386 (with-temp-buffer
6387 (insert s)
6388 (let ((org-odd-levels-only odd-levels))
6389 (org-mode)
6390 (font-lock-fontify-buffer)
6391 (buffer-string))))
6393 (defvar org-m nil)
6394 (defvar org-l nil)
6395 (defvar org-f nil)
6396 (defun org-get-level-face (n)
6397 "Get the right face for match N in font-lock matching of headlines."
6398 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6399 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6400 (if org-cycle-level-faces
6401 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6402 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6403 (cond
6404 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6405 ((eq n 2) org-f)
6406 (t (if org-level-color-stars-only nil org-f))))
6409 (defun org-get-todo-face (kwd)
6410 "Get the right face for a TODO keyword KWD.
6411 If KWD is a number, get the corresponding match group."
6412 (if (numberp kwd) (setq kwd (match-string kwd)))
6413 (or (org-face-from-face-or-color
6414 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6415 (and (member kwd org-done-keywords) 'org-done)
6416 'org-todo))
6418 (defun org-face-from-face-or-color (context inherit face-or-color)
6419 "Create a face list that inherits INHERIT, but sets the foreground color.
6420 When FACE-OR-COLOR is not a string, just return it."
6421 (if (stringp face-or-color)
6422 (list :inherit inherit
6423 (cdr (assoc context org-faces-easy-properties))
6424 face-or-color)
6425 face-or-color))
6427 (defun org-font-lock-add-tag-faces (limit)
6428 "Add the special tag faces."
6429 (when (and org-tag-faces org-tags-special-faces-re)
6430 (while (re-search-forward org-tags-special-faces-re limit t)
6431 (add-text-properties (match-beginning 1) (match-end 1)
6432 (list 'face (org-get-tag-face 1)
6433 'font-lock-fontified t))
6434 (backward-char 1))))
6436 (defun org-font-lock-add-priority-faces (limit)
6437 "Add the special priority faces."
6438 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6439 (when (save-match-data (org-at-heading-p))
6440 (add-text-properties
6441 (match-beginning 0) (match-end 0)
6442 (list 'face (or (org-face-from-face-or-color
6443 'priority 'org-priority
6444 (cdr (assoc (char-after (match-beginning 1))
6445 org-priority-faces)))
6446 'org-priority)
6447 'font-lock-fontified t)))))
6449 (defun org-get-tag-face (kwd)
6450 "Get the right face for a TODO keyword KWD.
6451 If KWD is a number, get the corresponding match group."
6452 (if (numberp kwd) (setq kwd (match-string kwd)))
6453 (or (org-face-from-face-or-color
6454 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6455 'org-tag))
6457 (defun org-unfontify-region (beg end &optional maybe_loudly)
6458 "Remove fontification and activation overlays from links."
6459 (font-lock-default-unfontify-region beg end)
6460 (let* ((buffer-undo-list t)
6461 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6462 (inhibit-modification-hooks t)
6463 deactivate-mark buffer-file-name buffer-file-truename)
6464 (org-decompose-region beg end)
6465 (remove-text-properties beg end
6466 '(mouse-face t keymap t org-linked-text t
6467 invisible t intangible t
6468 org-no-flyspell t org-emphasis t))
6469 (org-remove-font-lock-display-properties beg end)))
6471 (defconst org-script-display '(((raise -0.3) (height 0.7))
6472 ((raise 0.3) (height 0.7))
6473 ((raise -0.5))
6474 ((raise 0.5)))
6475 "Display properties for showing superscripts and subscripts.")
6477 (defun org-remove-font-lock-display-properties (beg end)
6478 "Remove specific display properties that have been added by font lock.
6479 The will remove the raise properties that are used to show superscripts
6480 and subscripts."
6481 (let (next prop)
6482 (while (< beg end)
6483 (setq next (next-single-property-change beg 'display nil end)
6484 prop (get-text-property beg 'display))
6485 (if (member prop org-script-display)
6486 (put-text-property beg next 'display nil))
6487 (setq beg next))))
6489 (defun org-raise-scripts (limit)
6490 "Add raise properties to sub/superscripts."
6491 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6492 (if (re-search-forward
6493 (if (eq org-use-sub-superscripts t)
6494 org-match-substring-regexp
6495 org-match-substring-with-braces-regexp)
6496 limit t)
6497 (let* ((pos (point)) table-p comment-p
6498 (mpos (match-beginning 3))
6499 (emph-p (get-text-property mpos 'org-emphasis))
6500 (link-p (get-text-property mpos 'mouse-face))
6501 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6502 (goto-char (point-at-bol))
6503 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6504 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6505 (goto-char pos)
6506 ;; Handle a_b^c
6507 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6508 (if (or comment-p emph-p link-p keyw-p)
6510 (put-text-property (match-beginning 3) (match-end 0)
6511 'display
6512 (if (equal (char-after (match-beginning 2)) ?^)
6513 (nth (if table-p 3 1) org-script-display)
6514 (nth (if table-p 2 0) org-script-display)))
6515 (add-text-properties (match-beginning 2) (match-end 2)
6516 (list 'invisible t
6517 'org-dwidth t 'org-dwidth-n 1))
6518 (if (and (eq (char-after (match-beginning 3)) ?{)
6519 (eq (char-before (match-end 3)) ?}))
6520 (progn
6521 (add-text-properties
6522 (match-beginning 3) (1+ (match-beginning 3))
6523 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6524 (add-text-properties
6525 (1- (match-end 3)) (match-end 3)
6526 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6527 t)))))
6529 ;;;; Visibility cycling, including org-goto and indirect buffer
6531 ;;; Cycling
6533 (defvar org-cycle-global-status nil)
6534 (make-variable-buffer-local 'org-cycle-global-status)
6535 (put 'org-cycle-global-status 'org-state t)
6536 (defvar org-cycle-subtree-status nil)
6537 (make-variable-buffer-local 'org-cycle-subtree-status)
6538 (put 'org-cycle-subtree-status 'org-state t)
6540 (defvar org-inlinetask-min-level)
6542 (defun org-unlogged-message (&rest args)
6543 "Display a message, but avoid logging it in the *Messages* buffer."
6544 (let ((message-log-max nil))
6545 (apply 'message args)))
6547 ;;;###autoload
6548 (defun org-cycle (&optional arg)
6549 "TAB-action and visibility cycling for Org-mode.
6551 This is the command invoked in Org-mode by the TAB key. Its main purpose
6552 is outline visibility cycling, but it also invokes other actions
6553 in special contexts.
6555 - When this function is called with a prefix argument, rotate the entire
6556 buffer through 3 states (global cycling)
6557 1. OVERVIEW: Show only top-level headlines.
6558 2. CONTENTS: Show all headlines of all levels, but no body text.
6559 3. SHOW ALL: Show everything.
6560 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6561 determined by the variable `org-startup-folded', and by any VISIBILITY
6562 properties in the buffer.
6563 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6564 including any drawers.
6566 - When inside a table, re-align the table and move to the next field.
6568 - When point is at the beginning of a headline, rotate the subtree started
6569 by this line through 3 different states (local cycling)
6570 1. FOLDED: Only the main headline is shown.
6571 2. CHILDREN: The main headline and the direct children are shown.
6572 From this state, you can move to one of the children
6573 and zoom in further.
6574 3. SUBTREE: Show the entire subtree, including body text.
6575 If there is no subtree, switch directly from CHILDREN to FOLDED.
6577 - When point is at the beginning of an empty headline and the variable
6578 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6579 of the headline by demoting and promoting it to likely levels. This
6580 speeds up creation document structure by pressing TAB once or several
6581 times right after creating a new headline.
6583 - When there is a numeric prefix, go up to a heading with level ARG, do
6584 a `show-subtree' and return to the previous cursor position. If ARG
6585 is negative, go up that many levels.
6587 - When point is not at the beginning of a headline, execute the global
6588 binding for TAB, which is re-indenting the line. See the option
6589 `org-cycle-emulate-tab' for details.
6591 - Special case: if point is at the beginning of the buffer and there is
6592 no headline in line 1, this function will act as if called with prefix arg
6593 (C-u TAB, same as S-TAB) also when called without prefix arg.
6594 But only if also the variable `org-cycle-global-at-bob' is t."
6595 (interactive "P")
6596 (org-load-modules-maybe)
6597 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6598 (and org-cycle-level-after-item/entry-creation
6599 (or (org-cycle-level)
6600 (org-cycle-item-indentation))))
6601 (let* ((limit-level
6602 (or org-cycle-max-level
6603 (and (boundp 'org-inlinetask-min-level)
6604 org-inlinetask-min-level
6605 (1- org-inlinetask-min-level))))
6606 (nstars (and limit-level
6607 (if org-odd-levels-only
6608 (and limit-level (1- (* limit-level 2)))
6609 limit-level)))
6610 (org-outline-regexp
6611 (if (not (derived-mode-p 'org-mode))
6612 outline-regexp
6613 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6614 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6615 (not (looking-at org-outline-regexp))))
6616 (org-cycle-hook
6617 (if bob-special
6618 (delq 'org-optimize-window-after-visibility-change
6619 (copy-sequence org-cycle-hook))
6620 org-cycle-hook))
6621 (pos (point)))
6623 (if (or bob-special (equal arg '(4)))
6624 ;; special case: use global cycling
6625 (setq arg t))
6627 (cond
6629 ((equal arg '(16))
6630 (setq last-command 'dummy)
6631 (org-set-startup-visibility)
6632 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6634 ((equal arg '(64))
6635 (show-all)
6636 (org-unlogged-message "Entire buffer visible, including drawers"))
6638 ;; Table: enter it or move to the next field.
6639 ((org-at-table-p 'any)
6640 (if (org-at-table.el-p)
6641 (message "Use C-c ' to edit table.el tables")
6642 (if arg (org-table-edit-field t)
6643 (org-table-justify-field-maybe)
6644 (call-interactively 'org-table-next-field))))
6646 ((run-hook-with-args-until-success
6647 'org-tab-after-check-for-table-hook))
6649 ;; Global cycling: delegate to `org-cycle-internal-global'.
6650 ((eq arg t) (org-cycle-internal-global))
6652 ;; Drawers: delegate to `org-flag-drawer'.
6653 ((save-excursion
6654 (beginning-of-line 1)
6655 (looking-at org-drawer-regexp))
6656 (org-flag-drawer ; toggle block visibility
6657 (not (get-char-property (match-end 0) 'invisible))))
6659 ;; Show-subtree, ARG levels up from here.
6660 ((integerp arg)
6661 (save-excursion
6662 (org-back-to-heading)
6663 (outline-up-heading (if (< arg 0) (- arg)
6664 (- (funcall outline-level) arg)))
6665 (org-show-subtree)))
6667 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6668 ((and (featurep 'org-inlinetask)
6669 (org-inlinetask-at-task-p)
6670 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6671 (org-inlinetask-toggle-visibility))
6673 ((org-try-cdlatex-tab))
6675 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6676 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6677 (save-excursion (beginning-of-line 1)
6678 (looking-at org-outline-regexp)))
6679 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6680 (org-cycle-internal-local))
6682 ;; From there: TAB emulation and template completion.
6683 (buffer-read-only (org-back-to-heading))
6685 ((run-hook-with-args-until-success
6686 'org-tab-after-check-for-cycling-hook))
6688 ((org-try-structure-completion))
6690 ((run-hook-with-args-until-success
6691 'org-tab-before-tab-emulation-hook))
6693 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6694 (or (not (bolp))
6695 (not (looking-at org-outline-regexp))))
6696 (call-interactively (global-key-binding "\t")))
6698 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6699 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6700 (or (and (eq org-cycle-emulate-tab 'white)
6701 (= (match-end 0) (point-at-eol)))
6702 (and (eq org-cycle-emulate-tab 'whitestart)
6703 (>= (match-end 0) pos))))
6705 (eq org-cycle-emulate-tab t))
6706 (call-interactively (global-key-binding "\t")))
6708 (t (save-excursion
6709 (org-back-to-heading)
6710 (org-cycle)))))))
6712 (defun org-cycle-internal-global ()
6713 "Do the global cycling action."
6714 ;; Hack to avoid display of messages for .org attachments in Gnus
6715 (let ((ga (string-match "\\*fontification" (buffer-name))))
6716 (cond
6717 ((and (eq last-command this-command)
6718 (eq org-cycle-global-status 'overview))
6719 ;; We just created the overview - now do table of contents
6720 ;; This can be slow in very large buffers, so indicate action
6721 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6722 (unless ga (org-unlogged-message "CONTENTS..."))
6723 (org-content)
6724 (unless ga (org-unlogged-message "CONTENTS...done"))
6725 (setq org-cycle-global-status 'contents)
6726 (run-hook-with-args 'org-cycle-hook 'contents))
6728 ((and (eq last-command this-command)
6729 (eq org-cycle-global-status 'contents))
6730 ;; We just showed the table of contents - now show everything
6731 (run-hook-with-args 'org-pre-cycle-hook 'all)
6732 (show-all)
6733 (unless ga (org-unlogged-message "SHOW ALL"))
6734 (setq org-cycle-global-status 'all)
6735 (run-hook-with-args 'org-cycle-hook 'all))
6738 ;; Default action: go to overview
6739 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6740 (org-overview)
6741 (unless ga (org-unlogged-message "OVERVIEW"))
6742 (setq org-cycle-global-status 'overview)
6743 (run-hook-with-args 'org-cycle-hook 'overview)))))
6745 (defvar org-called-with-limited-levels);Dyn-bound in ̀org-with-limited-levels'.
6747 (defun org-cycle-internal-local ()
6748 "Do the local cycling action."
6749 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6750 ;; First, determine end of headline (EOH), end of subtree or item
6751 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6752 (save-excursion
6753 (if (org-at-item-p)
6754 (progn
6755 (beginning-of-line)
6756 (setq struct (org-list-struct))
6757 (setq eoh (point-at-eol))
6758 (setq eos (org-list-get-item-end-before-blank (point) struct))
6759 (setq has-children (org-list-has-child-p (point) struct)))
6760 (org-back-to-heading)
6761 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6762 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6763 (setq has-children
6764 (or (save-excursion
6765 (let ((level (funcall outline-level)))
6766 (outline-next-heading)
6767 (and (org-at-heading-p t)
6768 (> (funcall outline-level) level))))
6769 (save-excursion
6770 (org-list-search-forward (org-item-beginning-re) eos t)))))
6771 ;; Determine end invisible part of buffer (EOL)
6772 (beginning-of-line 2)
6773 ;; XEmacs doesn't have `next-single-char-property-change'
6774 (if (featurep 'xemacs)
6775 (while (and (not (eobp)) ;; this is like `next-line'
6776 (get-char-property (1- (point)) 'invisible))
6777 (beginning-of-line 2))
6778 (while (and (not (eobp)) ;; this is like `next-line'
6779 (get-char-property (1- (point)) 'invisible))
6780 (goto-char (next-single-char-property-change (point) 'invisible))
6781 (and (eolp) (beginning-of-line 2))))
6782 (setq eol (point)))
6783 ;; Find out what to do next and set `this-command'
6784 (cond
6785 ((= eos eoh)
6786 ;; Nothing is hidden behind this heading
6787 (unless (org-before-first-heading-p)
6788 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6789 (org-unlogged-message "EMPTY ENTRY")
6790 (setq org-cycle-subtree-status nil)
6791 (save-excursion
6792 (goto-char eos)
6793 (outline-next-heading)
6794 (if (outline-invisible-p) (org-flag-heading nil))))
6795 ((and (or (>= eol eos)
6796 (not (string-match "\\S-" (buffer-substring eol eos))))
6797 (or has-children
6798 (not (setq children-skipped
6799 org-cycle-skip-children-state-if-no-children))))
6800 ;; Entire subtree is hidden in one line: children view
6801 (unless (org-before-first-heading-p)
6802 (run-hook-with-args 'org-pre-cycle-hook 'children))
6803 (if (org-at-item-p)
6804 (org-list-set-item-visibility (point-at-bol) struct 'children)
6805 (org-show-entry)
6806 (org-with-limited-levels (show-children))
6807 ;; FIXME: This slows down the func way too much.
6808 ;; How keep drawers hidden in subtree anyway?
6809 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6810 ;; (org-cycle-hide-drawers 'subtree))
6812 ;; Fold every list in subtree to top-level items.
6813 (when (eq org-cycle-include-plain-lists 'integrate)
6814 (save-excursion
6815 (org-back-to-heading)
6816 (while (org-list-search-forward (org-item-beginning-re) eos t)
6817 (beginning-of-line 1)
6818 (let* ((struct (org-list-struct))
6819 (prevs (org-list-prevs-alist struct))
6820 (end (org-list-get-bottom-point struct)))
6821 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6822 (org-list-get-all-items (point) struct prevs))
6823 (goto-char (if (< end eos) end eos)))))))
6824 (org-unlogged-message "CHILDREN")
6825 (save-excursion
6826 (goto-char eos)
6827 (outline-next-heading)
6828 (if (outline-invisible-p) (org-flag-heading nil)))
6829 (setq org-cycle-subtree-status 'children)
6830 (unless (org-before-first-heading-p)
6831 (run-hook-with-args 'org-cycle-hook 'children)))
6832 ((or children-skipped
6833 (and (eq last-command this-command)
6834 (eq org-cycle-subtree-status 'children)))
6835 ;; We just showed the children, or no children are there,
6836 ;; now show everything.
6837 (unless (org-before-first-heading-p)
6838 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6839 (outline-flag-region eoh eos nil)
6840 (org-unlogged-message
6841 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6842 (setq org-cycle-subtree-status 'subtree)
6843 (unless (org-before-first-heading-p)
6844 (run-hook-with-args 'org-cycle-hook 'subtree)))
6846 ;; Default action: hide the subtree.
6847 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6848 (outline-flag-region eoh eos t)
6849 (org-unlogged-message "FOLDED")
6850 (setq org-cycle-subtree-status 'folded)
6851 (unless (org-before-first-heading-p)
6852 (run-hook-with-args 'org-cycle-hook 'folded))))))
6854 ;;;###autoload
6855 (defun org-global-cycle (&optional arg)
6856 "Cycle the global visibility. For details see `org-cycle'.
6857 With \\[universal-argument] prefix arg, switch to startup visibility.
6858 With a numeric prefix, show all headlines up to that level."
6859 (interactive "P")
6860 (let ((org-cycle-include-plain-lists
6861 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6862 (cond
6863 ((integerp arg)
6864 (show-all)
6865 (hide-sublevels arg)
6866 (setq org-cycle-global-status 'contents))
6867 ((equal arg '(4))
6868 (org-set-startup-visibility)
6869 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6871 (org-cycle '(4))))))
6873 (defun org-set-startup-visibility ()
6874 "Set the visibility required by startup options and properties."
6875 (cond
6876 ((eq org-startup-folded t)
6877 (org-cycle '(4)))
6878 ((eq org-startup-folded 'content)
6879 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6880 (org-cycle '(4)) (org-cycle '(4)))))
6881 (unless (eq org-startup-folded 'showeverything)
6882 (if org-hide-block-startup (org-hide-block-all))
6883 (org-set-visibility-according-to-property 'no-cleanup)
6884 (org-cycle-hide-archived-subtrees 'all)
6885 (org-cycle-hide-drawers 'all)
6886 (org-cycle-show-empty-lines t)))
6888 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6889 "Switch subtree visibilities according to :VISIBILITY: property."
6890 (interactive)
6891 (let (org-show-entry-below state)
6892 (save-excursion
6893 (goto-char (point-min))
6894 (while (re-search-forward
6895 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6896 nil t)
6897 (setq state (match-string 1))
6898 (save-excursion
6899 (org-back-to-heading t)
6900 (hide-subtree)
6901 (org-reveal)
6902 (cond
6903 ((equal state '("fold" "folded"))
6904 (hide-subtree))
6905 ((equal state "children")
6906 (org-show-hidden-entry)
6907 (show-children))
6908 ((equal state "content")
6909 (save-excursion
6910 (save-restriction
6911 (org-narrow-to-subtree)
6912 (org-content))))
6913 ((member state '("all" "showall"))
6914 (show-subtree)))))
6915 (unless no-cleanup
6916 (org-cycle-hide-archived-subtrees 'all)
6917 (org-cycle-hide-drawers 'all)
6918 (org-cycle-show-empty-lines 'all)))))
6920 ;; This function uses outline-regexp instead of the more fundamental
6921 ;; org-outline-regexp so that org-cycle-global works outside of Org
6922 ;; buffers, where outline-regexp is needed.
6923 (defun org-overview ()
6924 "Switch to overview mode, showing only top-level headlines.
6925 Really, this shows all headlines with level equal or greater than the level
6926 of the first headline in the buffer. This is important, because if the
6927 first headline is not level one, then (hide-sublevels 1) gives confusing
6928 results."
6929 (interactive)
6930 (let ((pos (point))
6931 (level (save-excursion
6932 (goto-char (point-min))
6933 (if (re-search-forward (concat "^" outline-regexp) nil t)
6934 (progn
6935 (goto-char (match-beginning 0))
6936 (funcall outline-level))))))
6937 (and level (hide-sublevels level))
6938 (recenter '(4))
6939 (goto-char pos)))
6941 (defun org-content (&optional arg)
6942 "Show all headlines in the buffer, like a table of contents.
6943 With numerical argument N, show content up to level N."
6944 (interactive "P")
6945 (save-excursion
6946 ;; Visit all headings and show their offspring
6947 (and (integerp arg) (org-overview))
6948 (goto-char (point-max))
6949 (catch 'exit
6950 (while (and (progn (condition-case nil
6951 (outline-previous-visible-heading 1)
6952 (error (goto-char (point-min))))
6954 (looking-at org-outline-regexp))
6955 (if (integerp arg)
6956 (show-children (1- arg))
6957 (show-branches))
6958 (if (bobp) (throw 'exit nil))))))
6961 (defun org-optimize-window-after-visibility-change (state)
6962 "Adjust the window after a change in outline visibility.
6963 This function is the default value of the hook `org-cycle-hook'."
6964 (when (get-buffer-window (current-buffer))
6965 (cond
6966 ((eq state 'content) nil)
6967 ((eq state 'all) nil)
6968 ((eq state 'folded) nil)
6969 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6970 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6972 (defun org-remove-empty-overlays-at (pos)
6973 "Remove outline overlays that do not contain non-white stuff."
6974 (mapc
6975 (lambda (o)
6976 (and (eq 'outline (overlay-get o 'invisible))
6977 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6978 (overlay-end o))))
6979 (delete-overlay o)))
6980 (overlays-at pos)))
6982 (defun org-clean-visibility-after-subtree-move ()
6983 "Fix visibility issues after moving a subtree."
6984 ;; First, find a reasonable region to look at:
6985 ;; Start two siblings above, end three below
6986 (let* ((beg (save-excursion
6987 (and (org-get-last-sibling)
6988 (org-get-last-sibling))
6989 (point)))
6990 (end (save-excursion
6991 (and (org-get-next-sibling)
6992 (org-get-next-sibling)
6993 (org-get-next-sibling))
6994 (if (org-at-heading-p)
6995 (point-at-eol)
6996 (point))))
6997 (level (looking-at "\\*+"))
6998 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6999 (save-excursion
7000 (save-restriction
7001 (narrow-to-region beg end)
7002 (when re
7003 ;; Properly fold already folded siblings
7004 (goto-char (point-min))
7005 (while (re-search-forward re nil t)
7006 (if (and (not (outline-invisible-p))
7007 (save-excursion
7008 (goto-char (point-at-eol)) (outline-invisible-p)))
7009 (hide-entry))))
7010 (org-cycle-show-empty-lines 'overview)
7011 (org-cycle-hide-drawers 'overview)))))
7013 (defun org-cycle-show-empty-lines (state)
7014 "Show empty lines above all visible headlines.
7015 The region to be covered depends on STATE when called through
7016 `org-cycle-hook'. Lisp program can use t for STATE to get the
7017 entire buffer covered. Note that an empty line is only shown if there
7018 are at least `org-cycle-separator-lines' empty lines before the headline."
7019 (when (not (= org-cycle-separator-lines 0))
7020 (save-excursion
7021 (let* ((n (abs org-cycle-separator-lines))
7022 (re (cond
7023 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7024 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7025 (t (let ((ns (number-to-string (- n 2))))
7026 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7027 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7028 beg end b e)
7029 (cond
7030 ((memq state '(overview contents t))
7031 (setq beg (point-min) end (point-max)))
7032 ((memq state '(children folded))
7033 (setq beg (point) end (progn (org-end-of-subtree t t)
7034 (beginning-of-line 2)
7035 (point)))))
7036 (when beg
7037 (goto-char beg)
7038 (while (re-search-forward re end t)
7039 (unless (get-char-property (match-end 1) 'invisible)
7040 (setq e (match-end 1))
7041 (if (< org-cycle-separator-lines 0)
7042 (setq b (save-excursion
7043 (goto-char (match-beginning 0))
7044 (org-back-over-empty-lines)
7045 (if (save-excursion
7046 (goto-char (max (point-min) (1- (point))))
7047 (org-at-heading-p))
7048 (1- (point))
7049 (point))))
7050 (setq b (match-beginning 1)))
7051 (outline-flag-region b e nil)))))))
7052 ;; Never hide empty lines at the end of the file.
7053 (save-excursion
7054 (goto-char (point-max))
7055 (outline-previous-heading)
7056 (outline-end-of-heading)
7057 (if (and (looking-at "[ \t\n]+")
7058 (= (match-end 0) (point-max)))
7059 (outline-flag-region (point) (match-end 0) nil))))
7061 (defun org-show-empty-lines-in-parent ()
7062 "Move to the parent and re-show empty lines before visible headlines."
7063 (save-excursion
7064 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7065 (org-cycle-show-empty-lines context))))
7067 (defun org-files-list ()
7068 "Return `org-agenda-files' list, plus all open org-mode files.
7069 This is useful for operations that need to scan all of a user's
7070 open and agenda-wise Org files."
7071 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7072 (dolist (buf (buffer-list))
7073 (with-current-buffer buf
7074 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7075 (let ((file (expand-file-name (buffer-file-name))))
7076 (unless (member file files)
7077 (push file files))))))
7078 files))
7080 (defsubst org-entry-beginning-position ()
7081 "Return the beginning position of the current entry."
7082 (save-excursion (outline-back-to-heading t) (point)))
7084 (defsubst org-entry-end-position ()
7085 "Return the end position of the current entry."
7086 (save-excursion (outline-next-heading) (point)))
7088 (defun org-cycle-hide-drawers (state &optional exceptions)
7089 "Re-hide all drawers after a visibility state change.
7090 When non-nil, optional argument EXCEPTIONS is a list of strings
7091 specifying which drawers should not be hidden."
7092 (when (and (derived-mode-p 'org-mode)
7093 (not (memq state '(overview folded contents))))
7094 (save-excursion
7095 (let* ((globalp (memq state '(contents all)))
7096 (beg (if globalp (point-min) (point)))
7097 (end (if globalp (point-max)
7098 (if (eq state 'children)
7099 (save-excursion (outline-next-heading) (point))
7100 (org-end-of-subtree t)))))
7101 (goto-char beg)
7102 (while (re-search-forward org-drawer-regexp end t)
7103 (unless (member-ignore-case (match-string 1) exceptions)
7104 (let ((drawer (org-element-at-point)))
7105 (when (memq (org-element-type drawer) '(drawer property-drawer))
7106 (org-flag-drawer t drawer)
7107 ;; Make sure to skip drawer entirely or we might flag
7108 ;; it another time when matching its ending line with
7109 ;; `org-drawer-regexp'.
7110 (goto-char (org-element-property :end drawer))))))))))
7112 (defun org-cycle-hide-inline-tasks (state)
7113 "Re-hide inline tasks when switching to 'contents or 'children
7114 visibility state."
7115 (case state
7116 (contents
7117 (when (org-bound-and-true-p org-inlinetask-min-level)
7118 (hide-sublevels (1- org-inlinetask-min-level))))
7119 (children
7120 (when (featurep 'org-inlinetask)
7121 (save-excursion
7122 (while (and (outline-next-heading)
7123 (org-inlinetask-at-task-p))
7124 (org-inlinetask-toggle-visibility)
7125 (org-inlinetask-goto-end)))))))
7127 (defun org-flag-drawer (flag &optional element)
7128 "When FLAG is non-nil, hide the drawer we are at.
7129 Otherwise make it visible. When optional argument ELEMENT is
7130 a parsed drawer, as returned by `org-element-at-point', hide or
7131 show that drawer instead."
7132 (let ((drawer (or element (org-element-at-point))))
7133 (when (memq (org-element-type drawer) '(drawer property-drawer))
7134 (save-excursion
7135 (goto-char (org-element-property :post-affiliated drawer))
7136 (outline-flag-region
7137 (line-end-position)
7138 (progn (goto-char (org-element-property :end drawer))
7139 (skip-chars-backward " \r\t\n")
7140 (line-end-position))
7141 flag)))))
7143 (defun org-subtree-end-visible-p ()
7144 "Is the end of the current subtree visible?"
7145 (pos-visible-in-window-p
7146 (save-excursion (org-end-of-subtree t) (point))))
7148 (defun org-first-headline-recenter (&optional N)
7149 "Move cursor to the first headline and recenter the headline.
7150 Optional argument N means put the headline into the Nth line of the window."
7151 (goto-char (point-min))
7152 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7153 (beginning-of-line)
7154 (recenter (prefix-numeric-value N))))
7156 ;;; Saving and restoring visibility
7158 (defun org-outline-overlay-data (&optional use-markers)
7159 "Return a list of the locations of all outline overlays.
7160 These are overlays with the `invisible' property value `outline'.
7161 The return value is a list of cons cells, with start and stop
7162 positions for each overlay.
7163 If USE-MARKERS is set, return the positions as markers."
7164 (let (beg end)
7165 (save-excursion
7166 (save-restriction
7167 (widen)
7168 (delq nil
7169 (mapcar (lambda (o)
7170 (when (eq (overlay-get o 'invisible) 'outline)
7171 (setq beg (overlay-start o)
7172 end (overlay-end o))
7173 (and beg end (> end beg)
7174 (if use-markers
7175 (cons (move-marker (make-marker) beg)
7176 (move-marker (make-marker) end))
7177 (cons beg end)))))
7178 (overlays-in (point-min) (point-max))))))))
7180 (defun org-set-outline-overlay-data (data)
7181 "Create visibility overlays for all positions in DATA.
7182 DATA should have been made by `org-outline-overlay-data'."
7183 (let (o)
7184 (save-excursion
7185 (save-restriction
7186 (widen)
7187 (show-all)
7188 (mapc (lambda (c)
7189 (outline-flag-region (car c) (cdr c) t))
7190 data)))))
7192 ;;; Folding of blocks
7194 (defvar org-hide-block-overlays nil
7195 "Overlays hiding blocks.")
7196 (make-variable-buffer-local 'org-hide-block-overlays)
7198 (defun org-block-map (function &optional start end)
7199 "Call FUNCTION at the head of all source blocks in the current buffer.
7200 Optional arguments START and END can be used to limit the range."
7201 (let ((start (or start (point-min)))
7202 (end (or end (point-max))))
7203 (save-excursion
7204 (goto-char start)
7205 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7206 (save-excursion
7207 (save-match-data
7208 (goto-char (match-beginning 0))
7209 (funcall function)))))))
7211 (defun org-hide-block-toggle-all ()
7212 "Toggle the visibility of all blocks in the current buffer."
7213 (org-block-map #'org-hide-block-toggle))
7215 (defun org-hide-block-all ()
7216 "Fold all blocks in the current buffer."
7217 (interactive)
7218 (org-show-block-all)
7219 (org-block-map #'org-hide-block-toggle-maybe))
7221 (defun org-show-block-all ()
7222 "Unfold all blocks in the current buffer."
7223 (interactive)
7224 (mapc 'delete-overlay org-hide-block-overlays)
7225 (setq org-hide-block-overlays nil))
7227 (defun org-hide-block-toggle-maybe ()
7228 "Toggle visibility of block at point."
7229 (interactive)
7230 (let ((case-fold-search t))
7231 (if (save-excursion
7232 (beginning-of-line 1)
7233 (looking-at org-block-regexp))
7234 (progn (org-hide-block-toggle)
7235 t) ;; to signal that we took action
7236 nil))) ;; to signal that we did not
7238 (defun org-hide-block-toggle (&optional force)
7239 "Toggle the visibility of the current block."
7240 (interactive)
7241 (save-excursion
7242 (beginning-of-line)
7243 (if (re-search-forward org-block-regexp nil t)
7244 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7245 (end (match-end 0)) ;; end of entire body
7247 (if (memq t (mapcar (lambda (overlay)
7248 (eq (overlay-get overlay 'invisible)
7249 'org-hide-block))
7250 (overlays-at start)))
7251 (if (or (not force) (eq force 'off))
7252 (mapc (lambda (ov)
7253 (when (member ov org-hide-block-overlays)
7254 (setq org-hide-block-overlays
7255 (delq ov org-hide-block-overlays)))
7256 (when (eq (overlay-get ov 'invisible)
7257 'org-hide-block)
7258 (delete-overlay ov)))
7259 (overlays-at start)))
7260 (setq ov (make-overlay start end))
7261 (overlay-put ov 'invisible 'org-hide-block)
7262 ;; make the block accessible to isearch
7263 (overlay-put
7264 ov 'isearch-open-invisible
7265 (lambda (ov)
7266 (when (member ov org-hide-block-overlays)
7267 (setq org-hide-block-overlays
7268 (delq ov org-hide-block-overlays)))
7269 (when (eq (overlay-get ov 'invisible)
7270 'org-hide-block)
7271 (delete-overlay ov))))
7272 (push ov org-hide-block-overlays)))
7273 (user-error "Not looking at a source block"))))
7275 ;; org-tab-after-check-for-cycling-hook
7276 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7277 ;; Remove overlays when changing major mode
7278 (add-hook 'org-mode-hook
7279 (lambda () (org-add-hook 'change-major-mode-hook
7280 'org-show-block-all 'append 'local)))
7282 ;;; Org-goto
7284 (defvar org-goto-window-configuration nil)
7285 (defvar org-goto-marker nil)
7286 (defvar org-goto-map)
7287 (defun org-goto-map ()
7288 "Set the keymap `org-goto'."
7289 (setq org-goto-map
7290 (let ((map (make-sparse-keymap)))
7291 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7292 mouse-drag-region universal-argument org-occur))
7293 cmd)
7294 (while (setq cmd (pop cmds))
7295 (substitute-key-definition cmd cmd map global-map)))
7296 (suppress-keymap map)
7297 (org-defkey map "\C-m" 'org-goto-ret)
7298 (org-defkey map [(return)] 'org-goto-ret)
7299 (org-defkey map [(left)] 'org-goto-left)
7300 (org-defkey map [(right)] 'org-goto-right)
7301 (org-defkey map [(control ?g)] 'org-goto-quit)
7302 (org-defkey map "\C-i" 'org-cycle)
7303 (org-defkey map [(tab)] 'org-cycle)
7304 (org-defkey map [(down)] 'outline-next-visible-heading)
7305 (org-defkey map [(up)] 'outline-previous-visible-heading)
7306 (if org-goto-auto-isearch
7307 (if (fboundp 'define-key-after)
7308 (define-key-after map [t] 'org-goto-local-auto-isearch)
7309 nil)
7310 (org-defkey map "q" 'org-goto-quit)
7311 (org-defkey map "n" 'outline-next-visible-heading)
7312 (org-defkey map "p" 'outline-previous-visible-heading)
7313 (org-defkey map "f" 'outline-forward-same-level)
7314 (org-defkey map "b" 'outline-backward-same-level)
7315 (org-defkey map "u" 'outline-up-heading))
7316 (org-defkey map "/" 'org-occur)
7317 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7318 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7319 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7320 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7321 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7322 map)))
7324 (defconst org-goto-help
7325 "Browse buffer copy, to find location or copy text.%s
7326 RET=jump to location C-g=quit and return to previous location
7327 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7329 (defvar org-goto-start-pos) ; dynamically scoped parameter
7331 (defun org-goto (&optional alternative-interface)
7332 "Look up a different location in the current file, keeping current visibility.
7334 When you want look-up or go to a different location in a
7335 document, the fastest way is often to fold the entire buffer and
7336 then dive into the tree. This method has the disadvantage, that
7337 the previous location will be folded, which may not be what you
7338 want.
7340 This command works around this by showing a copy of the current
7341 buffer in an indirect buffer, in overview mode. You can dive
7342 into the tree in that copy, use org-occur and incremental search
7343 to find a location. When pressing RET or `Q', the command
7344 returns to the original buffer in which the visibility is still
7345 unchanged. After RET it will also jump to the location selected
7346 in the indirect buffer and expose the headline hierarchy above.
7348 With a prefix argument, use the alternative interface: e.g. if
7349 `org-goto-interface' is 'outline use 'outline-path-completion."
7350 (interactive "P")
7351 (org-goto-map)
7352 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7353 (org-refile-use-outline-path t)
7354 (org-refile-target-verify-function nil)
7355 (interface
7356 (if (not alternative-interface)
7357 org-goto-interface
7358 (if (eq org-goto-interface 'outline)
7359 'outline-path-completion
7360 'outline)))
7361 (org-goto-start-pos (point))
7362 (selected-point
7363 (if (eq interface 'outline)
7364 (car (org-get-location (current-buffer) org-goto-help))
7365 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7366 (org-refile-check-position pa)
7367 (nth 3 pa)))))
7368 (if selected-point
7369 (progn
7370 (org-mark-ring-push org-goto-start-pos)
7371 (goto-char selected-point)
7372 (if (or (outline-invisible-p) (org-invisible-p2))
7373 (org-show-context 'org-goto)))
7374 (message "Quit"))))
7376 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7377 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7378 (defvar org-goto-local-auto-isearch-map) ; defined below
7380 (defun org-get-location (buf help)
7381 "Let the user select a location in the Org-mode buffer BUF.
7382 This function uses a recursive edit. It returns the selected position
7383 or nil."
7384 (org-no-popups
7385 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7386 (isearch-hide-immediately nil)
7387 (isearch-search-fun-function
7388 (lambda () 'org-goto-local-search-headings))
7389 (org-goto-selected-point org-goto-exit-command))
7390 (save-excursion
7391 (save-window-excursion
7392 (delete-other-windows)
7393 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7394 (org-pop-to-buffer-same-window
7395 (condition-case nil
7396 (make-indirect-buffer (current-buffer) "*org-goto*")
7397 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7398 (with-output-to-temp-buffer "*Org Help*"
7399 (princ (format help (if org-goto-auto-isearch
7400 " Just type for auto-isearch."
7401 " n/p/f/b/u to navigate, q to quit."))))
7402 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7403 (setq buffer-read-only nil)
7404 (let ((org-startup-truncated t)
7405 (org-startup-folded nil)
7406 (org-startup-align-all-tables nil))
7407 (org-mode)
7408 (org-overview))
7409 (setq buffer-read-only t)
7410 (if (and (boundp 'org-goto-start-pos)
7411 (integer-or-marker-p org-goto-start-pos))
7412 (let ((org-show-hierarchy-above t)
7413 (org-show-siblings t)
7414 (org-show-following-heading t))
7415 (goto-char org-goto-start-pos)
7416 (and (outline-invisible-p) (org-show-context)))
7417 (goto-char (point-min)))
7418 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7419 (message "Select location and press RET")
7420 (use-local-map org-goto-map)
7421 (recursive-edit)))
7422 (kill-buffer "*org-goto*")
7423 (cons org-goto-selected-point org-goto-exit-command))))
7425 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7426 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7427 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7428 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7430 (defun org-goto-local-search-headings (string bound noerror)
7431 "Search and make sure that any matches are in headlines."
7432 (catch 'return
7433 (while (if isearch-forward
7434 (search-forward string bound noerror)
7435 (search-backward string bound noerror))
7436 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7437 (and (member :headline context)
7438 (not (member :tags context))))
7439 (throw 'return (point))))))
7441 (defun org-goto-local-auto-isearch ()
7442 "Start isearch."
7443 (interactive)
7444 (goto-char (point-min))
7445 (let ((keys (this-command-keys)))
7446 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7447 (isearch-mode t)
7448 (isearch-process-search-char (string-to-char keys)))))
7450 (defun org-goto-ret (&optional arg)
7451 "Finish `org-goto' by going to the new location."
7452 (interactive "P")
7453 (setq org-goto-selected-point (point)
7454 org-goto-exit-command 'return)
7455 (throw 'exit nil))
7457 (defun org-goto-left ()
7458 "Finish `org-goto' by going to the new location."
7459 (interactive)
7460 (if (org-at-heading-p)
7461 (progn
7462 (beginning-of-line 1)
7463 (setq org-goto-selected-point (point)
7464 org-goto-exit-command 'left)
7465 (throw 'exit nil))
7466 (user-error "Not on a heading")))
7468 (defun org-goto-right ()
7469 "Finish `org-goto' by going to the new location."
7470 (interactive)
7471 (if (org-at-heading-p)
7472 (progn
7473 (setq org-goto-selected-point (point)
7474 org-goto-exit-command 'right)
7475 (throw 'exit nil))
7476 (user-error "Not on a heading")))
7478 (defun org-goto-quit ()
7479 "Finish `org-goto' without cursor motion."
7480 (interactive)
7481 (setq org-goto-selected-point nil)
7482 (setq org-goto-exit-command 'quit)
7483 (throw 'exit nil))
7485 ;;; Indirect buffer display of subtrees
7487 (defvar org-indirect-dedicated-frame nil
7488 "This is the frame being used for indirect tree display.")
7489 (defvar org-last-indirect-buffer nil)
7491 (defun org-tree-to-indirect-buffer (&optional arg)
7492 "Create indirect buffer and narrow it to current subtree.
7493 With a numerical prefix ARG, go up to this level and then take that tree.
7494 If ARG is negative, go up that many levels.
7496 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7497 indirect buffer previously made with this command, to avoid proliferation of
7498 indirect buffers. However, when you call the command with a \
7499 \\[universal-argument] prefix, or
7500 when `org-indirect-buffer-display' is `new-frame', the last buffer
7501 is kept so that you can work with several indirect buffers at the same time.
7502 If `org-indirect-buffer-display' is `dedicated-frame', the \
7503 \\[universal-argument] prefix also
7504 requests that a new frame be made for the new buffer, so that the dedicated
7505 frame is not changed."
7506 (interactive "P")
7507 (let ((cbuf (current-buffer))
7508 (cwin (selected-window))
7509 (pos (point))
7510 beg end level heading ibuf)
7511 (save-excursion
7512 (org-back-to-heading t)
7513 (when (numberp arg)
7514 (setq level (org-outline-level))
7515 (if (< arg 0) (setq arg (+ level arg)))
7516 (while (> (setq level (org-outline-level)) arg)
7517 (org-up-heading-safe)))
7518 (setq beg (point)
7519 heading (org-get-heading))
7520 (org-end-of-subtree t t)
7521 (if (org-at-heading-p) (backward-char 1))
7522 (setq end (point)))
7523 (if (and (buffer-live-p org-last-indirect-buffer)
7524 (not (eq org-indirect-buffer-display 'new-frame))
7525 (not arg))
7526 (kill-buffer org-last-indirect-buffer))
7527 (setq ibuf (org-get-indirect-buffer cbuf heading)
7528 org-last-indirect-buffer ibuf)
7529 (cond
7530 ((or (eq org-indirect-buffer-display 'new-frame)
7531 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7532 (select-frame (make-frame))
7533 (delete-other-windows)
7534 (org-pop-to-buffer-same-window ibuf)
7535 (org-set-frame-title heading))
7536 ((eq org-indirect-buffer-display 'dedicated-frame)
7537 (raise-frame
7538 (select-frame (or (and org-indirect-dedicated-frame
7539 (frame-live-p org-indirect-dedicated-frame)
7540 org-indirect-dedicated-frame)
7541 (setq org-indirect-dedicated-frame (make-frame)))))
7542 (delete-other-windows)
7543 (org-pop-to-buffer-same-window ibuf)
7544 (org-set-frame-title (concat "Indirect: " heading)))
7545 ((eq org-indirect-buffer-display 'current-window)
7546 (org-pop-to-buffer-same-window ibuf))
7547 ((eq org-indirect-buffer-display 'other-window)
7548 (pop-to-buffer ibuf))
7549 (t (error "Invalid value")))
7550 (if (featurep 'xemacs)
7551 (save-excursion (org-mode) (turn-on-font-lock)))
7552 (narrow-to-region beg end)
7553 (show-all)
7554 (goto-char pos)
7555 (run-hook-with-args 'org-cycle-hook 'all)
7556 (and (window-live-p cwin) (select-window cwin))))
7558 (defun org-get-indirect-buffer (&optional buffer heading)
7559 (setq buffer (or buffer (current-buffer)))
7560 (let ((n 1) (base (buffer-name buffer)) bname)
7561 (while (buffer-live-p
7562 (get-buffer
7563 (setq bname
7564 (concat base "-"
7565 (if heading (concat heading "-" (number-to-string n))
7566 (number-to-string n))))))
7567 (setq n (1+ n)))
7568 (condition-case nil
7569 (make-indirect-buffer buffer bname 'clone)
7570 (error (make-indirect-buffer buffer bname)))))
7572 (defun org-set-frame-title (title)
7573 "Set the title of the current frame to the string TITLE."
7574 ;; FIXME: how to name a single frame in XEmacs???
7575 (unless (featurep 'xemacs)
7576 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7578 ;;;; Structure editing
7580 ;;; Inserting headlines
7582 (defun org-previous-line-empty-p (&optional next)
7583 "Is the previous line a blank line?
7584 When NEXT is non-nil, check the next line instead."
7585 (save-excursion
7586 (and (not (bobp))
7587 (or (beginning-of-line (if next 2 0)) t)
7588 (save-match-data
7589 (looking-at "[ \t]*$")))))
7591 (defun org-insert-heading (&optional arg invisible-ok)
7592 "Insert a new heading or item with same depth at point.
7593 If point is in a plain list and ARG is nil, create a new list item.
7594 With one universal prefix argument, insert a heading even in lists.
7595 With two universal prefix arguments, insert the heading at the end
7596 of the parent subtree.
7598 If point is at the beginning of a headline, insert a sibling before
7599 the current headline. If point is not at the beginning, split the line
7600 and create a new headline with the text in the current line after point
7601 \(see `org-M-RET-may-split-line' on how to modify this behavior).
7603 If point is at the beginning of a normal line, turn this line into
7604 a heading.
7606 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7607 This is important for non-interactive uses of the command."
7608 (interactive "P")
7609 (if (org-called-interactively-p 'any) (org-reveal))
7610 (let ((itemp (org-in-item-p))
7611 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7612 (respect-content (or org-insert-heading-respect-content
7613 (equal arg '(16))))
7614 (initial-content "")
7615 (adjust-empty-lines t))
7617 (cond
7619 ((or (= (buffer-size) 0)
7620 (and (not (save-excursion
7621 (and (ignore-errors (org-back-to-heading invisible-ok))
7622 (org-at-heading-p))))
7623 (or arg (not itemp))))
7624 ;; At beginning of buffer or so high up that only a heading
7625 ;; makes sense.
7626 (insert
7627 (if (or (bobp) (org-previous-line-empty-p)) "" "\n")
7628 (if (org-in-src-block-p) ",* " "* "))
7629 (run-hooks 'org-insert-heading-hook))
7631 ((and itemp (not (equal arg '(4))))
7632 ;; Insert an item
7633 (org-insert-item))
7636 ;; Insert a heading
7637 (save-restriction
7638 (widen)
7639 (let* ((level nil)
7640 (on-heading (org-at-heading-p))
7641 (empty-line-p (if on-heading
7642 (org-previous-line-empty-p)
7643 ;; We will decide later
7644 nil))
7645 ;; Get a level string to fall back on
7646 (fix-level
7647 (save-excursion
7648 (org-back-to-heading t)
7649 (if (org-previous-line-empty-p) (setq empty-line-p t))
7650 (looking-at org-outline-regexp)
7651 (make-string (1- (length (match-string 0))) ?*)))
7652 (stars
7653 (save-excursion
7654 (condition-case nil
7655 (progn
7656 (org-back-to-heading invisible-ok)
7657 (when (and (not on-heading)
7658 (featurep 'org-inlinetask)
7659 (integerp org-inlinetask-min-level)
7660 (>= (length (match-string 0))
7661 org-inlinetask-min-level))
7662 ;; Find a heading level before the inline task
7663 (while (and (setq level (org-up-heading-safe))
7664 (>= level org-inlinetask-min-level)))
7665 (if (org-at-heading-p)
7666 (org-back-to-heading invisible-ok)
7667 (error "This should not happen")))
7668 (unless (and (save-excursion
7669 (save-match-data
7670 (org-backward-heading-same-level
7671 1 invisible-ok))
7672 (= (point) (match-beginning 0)))
7673 (not (org-previous-line-empty-p t)))
7674 (setq empty-line-p (or empty-line-p
7675 (org-previous-line-empty-p))))
7676 (match-string 0))
7677 (error (or fix-level "* ")))))
7678 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7679 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7680 pos hide-previous previous-pos)
7682 ;; If we insert after content, move there and clean up whitespace
7683 (when respect-content
7684 (org-end-of-subtree nil t)
7685 (skip-chars-backward " \r\n")
7686 (and (looking-at "[ \t]+") (replace-match ""))
7687 (unless (eobp) (forward-char 1))
7688 (when (looking-at "^\\*")
7689 (unless (bobp) (backward-char 1))
7690 (insert "\n")))
7692 ;; If we are splitting, grab the text that should be moved to the new headline
7693 (when may-split
7694 (if (org-on-heading-p)
7695 ;; This is a heading, we split intelligently (keeping tags)
7696 (let ((pos (point)))
7697 (goto-char (point-at-bol))
7698 (unless (looking-at org-complex-heading-regexp)
7699 (error "This should not happen"))
7700 (when (and (match-beginning 4)
7701 (> pos (match-beginning 4))
7702 (< pos (match-end 4)))
7703 (setq initial-content (buffer-substring pos (match-end 4)))
7704 (goto-char pos)
7705 (delete-region (point) (match-end 4))
7706 (if (looking-at "[ \t]*$")
7707 (replace-match "")
7708 (insert (make-string (length initial-content) ?\ )))
7709 (setq initial-content (org-trim initial-content)))
7710 (goto-char pos))
7711 ;; a normal line
7712 (unless (bolp)
7713 (setq initial-content (buffer-substring (point) (point-at-eol)))
7714 (delete-region (point) (point-at-eol))
7715 (setq initial-content (org-trim initial-content)))))
7717 ;; If we are at the beginning of the line, insert before it. Else after
7718 (cond
7719 ((and (bolp) (looking-at "[ \t]*$")))
7720 ((and (bolp) (not (looking-at "[ \t]*$")))
7721 (open-line 1))
7723 (goto-char (point-at-eol))
7724 (insert "\n")))
7726 ;; Insert the new heading
7727 (insert stars)
7728 (just-one-space)
7729 (insert initial-content)
7730 (when adjust-empty-lines
7731 (if (or (not blank)
7732 (and blank (not (org-previous-line-empty-p))))
7733 (org-N-empty-lines-before-current (if blank 1 0))))
7734 (run-hooks 'org-insert-heading-hook)))))))
7736 (defun org-N-empty-lines-before-current (N)
7737 "Make the number of empty lines before current exactly N.
7738 So this will delete or add empty lines."
7739 (save-excursion
7740 (goto-char (point-at-bol))
7741 (if (looking-back "\\s-+" nil 'greedy)
7742 (replace-match ""))
7743 (or (bobp) (insert "\n"))
7744 (while (> N 0)
7745 (insert "\n")
7746 (setq N (1- N)))))
7748 (defun org-get-heading (&optional no-tags no-todo)
7749 "Return the heading of the current entry, without the stars.
7750 When NO-TAGS is non-nil, don't include tags.
7751 When NO-TODO is non-nil, don't include TODO keywords."
7752 (save-excursion
7753 (org-back-to-heading t)
7754 (cond
7755 ((and no-tags no-todo)
7756 (looking-at org-complex-heading-regexp)
7757 (match-string 4))
7758 (no-tags
7759 (looking-at (concat org-outline-regexp
7760 "\\(.*?\\)"
7761 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7762 (match-string 1))
7763 (no-todo
7764 (looking-at org-todo-line-regexp)
7765 (match-string 3))
7766 (t (looking-at org-heading-regexp)
7767 (match-string 2)))))
7769 (defvar orgstruct-mode) ; defined below
7771 (defun org-heading-components ()
7772 "Return the components of the current heading.
7773 This is a list with the following elements:
7774 - the level as an integer
7775 - the reduced level, different if `org-odd-levels-only' is set.
7776 - the TODO keyword, or nil
7777 - the priority character, like ?A, or nil if no priority is given
7778 - the headline text itself, or the tags string if no headline text
7779 - the tags string, or nil."
7780 (save-excursion
7781 (org-back-to-heading t)
7782 (if (let (case-fold-search)
7783 (looking-at
7784 (if orgstruct-mode
7785 org-heading-regexp
7786 org-complex-heading-regexp)))
7787 (if orgstruct-mode
7788 (list (length (match-string 1))
7789 (org-reduced-level (length (match-string 1)))
7792 (match-string 2)
7793 nil)
7794 (list (length (match-string 1))
7795 (org-reduced-level (length (match-string 1)))
7796 (org-match-string-no-properties 2)
7797 (and (match-end 3) (aref (match-string 3) 2))
7798 (org-match-string-no-properties 4)
7799 (org-match-string-no-properties 5))))))
7801 (defun org-get-entry ()
7802 "Get the entry text, after heading, entire subtree."
7803 (save-excursion
7804 (org-back-to-heading t)
7805 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7807 (defun org-insert-heading-after-current ()
7808 "Insert a new heading with same level as current, after current subtree."
7809 (interactive)
7810 (org-back-to-heading)
7811 (org-insert-heading)
7812 (org-move-subtree-down)
7813 (end-of-line 1))
7815 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7816 "Insert heading with `org-insert-heading-respect-content' set to t."
7817 (interactive "P")
7818 (let ((org-insert-heading-respect-content t))
7819 (org-insert-heading '(4) invisible-ok)))
7821 (defun org-insert-todo-heading-respect-content (&optional force-state)
7822 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7823 (interactive "P")
7824 (let ((org-insert-heading-respect-content t))
7825 (org-insert-todo-heading force-state '(4))))
7827 (defun org-insert-todo-heading (arg &optional force-heading)
7828 "Insert a new heading with the same level and TODO state as current heading.
7829 If the heading has no TODO state, or if the state is DONE, use the first
7830 state (TODO by default). Also one prefix arg, force first state. With two
7831 prefix args, force inserting at the end of the parent subtree."
7832 (interactive "P")
7833 (when (or force-heading (not (org-insert-item 'checkbox)))
7834 (org-insert-heading (or (and (equal arg '(16)) '(16))
7835 force-heading))
7836 (save-excursion
7837 (org-back-to-heading)
7838 (outline-previous-heading)
7839 (looking-at org-todo-line-regexp))
7840 (let*
7841 ((new-mark-x
7842 (if (or arg
7843 (not (match-beginning 2))
7844 (member (match-string 2) org-done-keywords))
7845 (car org-todo-keywords-1)
7846 (match-string 2)))
7847 (new-mark
7849 (run-hook-with-args-until-success
7850 'org-todo-get-default-hook new-mark-x nil)
7851 new-mark-x)))
7852 (beginning-of-line 1)
7853 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7854 (if org-treat-insert-todo-heading-as-state-change
7855 (org-todo new-mark)
7856 (insert new-mark " "))))
7857 (when org-provide-todo-statistics
7858 (org-update-parent-todo-statistics))))
7860 (defun org-insert-subheading (arg)
7861 "Insert a new subheading and demote it.
7862 Works for outline headings and for plain lists alike."
7863 (interactive "P")
7864 (org-insert-heading arg)
7865 (cond
7866 ((org-at-heading-p) (org-do-demote))
7867 ((org-at-item-p) (org-indent-item))))
7869 (defun org-insert-todo-subheading (arg)
7870 "Insert a new subheading with TODO keyword or checkbox and demote it.
7871 Works for outline headings and for plain lists alike."
7872 (interactive "P")
7873 (org-insert-todo-heading arg)
7874 (cond
7875 ((org-at-heading-p) (org-do-demote))
7876 ((org-at-item-p) (org-indent-item))))
7878 ;;; Promotion and Demotion
7880 (defvar org-after-demote-entry-hook nil
7881 "Hook run after an entry has been demoted.
7882 The cursor will be at the beginning of the entry.
7883 When a subtree is being demoted, the hook will be called for each node.")
7885 (defvar org-after-promote-entry-hook nil
7886 "Hook run after an entry has been promoted.
7887 The cursor will be at the beginning of the entry.
7888 When a subtree is being promoted, the hook will be called for each node.")
7890 (defun org-promote-subtree ()
7891 "Promote the entire subtree.
7892 See also `org-promote'."
7893 (interactive)
7894 (save-excursion
7895 (org-with-limited-levels (org-map-tree 'org-promote)))
7896 (org-fix-position-after-promote))
7898 (defun org-demote-subtree ()
7899 "Demote the entire subtree. See `org-demote'.
7900 See also `org-promote'."
7901 (interactive)
7902 (save-excursion
7903 (org-with-limited-levels (org-map-tree 'org-demote)))
7904 (org-fix-position-after-promote))
7907 (defun org-do-promote ()
7908 "Promote the current heading higher up the tree.
7909 If the region is active in `transient-mark-mode', promote all headings
7910 in the region."
7911 (interactive)
7912 (save-excursion
7913 (if (org-region-active-p)
7914 (org-map-region 'org-promote (region-beginning) (region-end))
7915 (org-promote)))
7916 (org-fix-position-after-promote))
7918 (defun org-do-demote ()
7919 "Demote the current heading lower down the tree.
7920 If the region is active in `transient-mark-mode', demote all headings
7921 in the region."
7922 (interactive)
7923 (save-excursion
7924 (if (org-region-active-p)
7925 (org-map-region 'org-demote (region-beginning) (region-end))
7926 (org-demote)))
7927 (org-fix-position-after-promote))
7929 (defun org-fix-position-after-promote ()
7930 "Make sure that after pro/demotion cursor position is right."
7931 (let ((pos (point)))
7932 (when (save-excursion
7933 (beginning-of-line 1)
7934 (looking-at org-todo-line-regexp)
7935 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7936 (cond ((eobp) (insert " "))
7937 ((eolp) (insert " "))
7938 ((equal (char-after) ?\ ) (forward-char 1))))))
7940 (defun org-current-level ()
7941 "Return the level of the current entry, or nil if before the first headline.
7942 The level is the number of stars at the beginning of the headline."
7943 (save-excursion
7944 (org-with-limited-levels
7945 (if (ignore-errors (org-back-to-heading t))
7946 (funcall outline-level)))))
7948 (defun org-get-previous-line-level ()
7949 "Return the outline depth of the last headline before the current line.
7950 Returns 0 for the first headline in the buffer, and nil if before the
7951 first headline."
7952 (let ((current-level (org-current-level))
7953 (prev-level (when (> (line-number-at-pos) 1)
7954 (save-excursion
7955 (beginning-of-line 0)
7956 (org-current-level)))))
7957 (cond ((null current-level) nil) ; Before first headline
7958 ((null prev-level) 0) ; At first headline
7959 (prev-level))))
7961 (defun org-reduced-level (l)
7962 "Compute the effective level of a heading.
7963 This takes into account the setting of `org-odd-levels-only'."
7964 (cond
7965 ((zerop l) 0)
7966 (org-odd-levels-only (1+ (floor (/ l 2))))
7967 (t l)))
7969 (defun org-level-increment ()
7970 "Return the number of stars that will be added or removed at a
7971 time to headlines when structure editing, based on the value of
7972 `org-odd-levels-only'."
7973 (if org-odd-levels-only 2 1))
7975 (defun org-get-valid-level (level &optional change)
7976 "Rectify a level change under the influence of `org-odd-levels-only'
7977 LEVEL is a current level, CHANGE is by how much the level should be
7978 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7979 even level numbers will become the next higher odd number."
7980 (if org-odd-levels-only
7981 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7982 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7983 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7984 (max 1 (+ level (or change 0)))))
7986 (if (boundp 'define-obsolete-function-alias)
7987 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7988 (define-obsolete-function-alias 'org-get-legal-level
7989 'org-get-valid-level)
7990 (define-obsolete-function-alias 'org-get-legal-level
7991 'org-get-valid-level "23.1")))
7993 (defun org-promote ()
7994 "Promote the current heading higher up the tree.
7995 If the region is active in `transient-mark-mode', promote all headings
7996 in the region."
7997 (org-back-to-heading t)
7998 (let* ((level (save-match-data (funcall outline-level)))
7999 (after-change-functions (remove 'flyspell-after-change-function
8000 after-change-functions))
8001 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8002 (diff (abs (- level (length up-head) -1))))
8003 (cond ((and (= level 1) org-called-with-limited-levels
8004 org-allow-promoting-top-level-subtree)
8005 (replace-match "# " nil t))
8006 ((= level 1)
8007 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8008 (t (replace-match up-head nil t)))
8009 ;; Fixup tag positioning
8010 (unless (= level 1)
8011 (and org-auto-align-tags (org-set-tags nil t))
8012 (if org-adapt-indentation (org-fixup-indentation (- diff))))
8013 (run-hooks 'org-after-promote-entry-hook)))
8015 (defun org-demote ()
8016 "Demote the current heading lower down the tree.
8017 If the region is active in `transient-mark-mode', demote all headings
8018 in the region."
8019 (org-back-to-heading t)
8020 (let* ((level (save-match-data (funcall outline-level)))
8021 (after-change-functions (remove 'flyspell-after-change-function
8022 after-change-functions))
8023 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8024 (diff (abs (- level (length down-head) -1))))
8025 (replace-match down-head nil t)
8026 ;; Fixup tag positioning
8027 (and org-auto-align-tags (org-set-tags nil t))
8028 (if org-adapt-indentation (org-fixup-indentation diff))
8029 (run-hooks 'org-after-demote-entry-hook)))
8031 (defun org-cycle-level ()
8032 "Cycle the level of an empty headline through possible states.
8033 This goes first to child, then to parent, level, then up the hierarchy.
8034 After top level, it switches back to sibling level."
8035 (interactive)
8036 (let ((org-adapt-indentation nil))
8037 (when (org-point-at-end-of-empty-headline)
8038 (setq this-command 'org-cycle-level) ; Only needed for caching
8039 (let ((cur-level (org-current-level))
8040 (prev-level (org-get-previous-line-level)))
8041 (cond
8042 ;; If first headline in file, promote to top-level.
8043 ((= prev-level 0)
8044 (loop repeat (/ (- cur-level 1) (org-level-increment))
8045 do (org-do-promote)))
8046 ;; If same level as prev, demote one.
8047 ((= prev-level cur-level)
8048 (org-do-demote))
8049 ;; If parent is top-level, promote to top level if not already.
8050 ((= prev-level 1)
8051 (loop repeat (/ (- cur-level 1) (org-level-increment))
8052 do (org-do-promote)))
8053 ;; If top-level, return to prev-level.
8054 ((= cur-level 1)
8055 (loop repeat (/ (- prev-level 1) (org-level-increment))
8056 do (org-do-demote)))
8057 ;; If less than prev-level, promote one.
8058 ((< cur-level prev-level)
8059 (org-do-promote))
8060 ;; If deeper than prev-level, promote until higher than
8061 ;; prev-level.
8062 ((> cur-level prev-level)
8063 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8064 do (org-do-promote))))
8065 t))))
8067 (defun org-map-tree (fun)
8068 "Call FUN for every heading underneath the current one."
8069 (org-back-to-heading)
8070 (let ((level (funcall outline-level)))
8071 (save-excursion
8072 (funcall fun)
8073 (while (and (progn
8074 (outline-next-heading)
8075 (> (funcall outline-level) level))
8076 (not (eobp)))
8077 (funcall fun)))))
8079 (defun org-map-region (fun beg end)
8080 "Call FUN for every heading between BEG and END."
8081 (let ((org-ignore-region t))
8082 (save-excursion
8083 (setq end (copy-marker end))
8084 (goto-char beg)
8085 (if (and (re-search-forward org-outline-regexp-bol nil t)
8086 (< (point) end))
8087 (funcall fun))
8088 (while (and (progn
8089 (outline-next-heading)
8090 (< (point) end))
8091 (not (eobp)))
8092 (funcall fun)))))
8094 (defvar org-property-end-re) ; silence byte-compiler
8095 (defun org-fixup-indentation (diff)
8096 "Change the indentation in the current entry by DIFF.
8097 However, if any line in the current entry has no indentation, or if it
8098 would end up with no indentation after the change, nothing at all is done."
8099 (save-excursion
8100 (let ((end (save-excursion (outline-next-heading)
8101 (point-marker)))
8102 (prohibit (if (> diff 0)
8103 "^\\S-"
8104 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8105 col)
8106 (unless (save-excursion (end-of-line 1)
8107 (re-search-forward prohibit end t))
8108 (while (and (< (point) end)
8109 (re-search-forward "^[ \t]+" end t))
8110 (goto-char (match-end 0))
8111 (setq col (current-column))
8112 (if (< diff 0) (replace-match ""))
8113 (org-indent-to-column (+ diff col))))
8114 (move-marker end nil))))
8116 (defun org-convert-to-odd-levels ()
8117 "Convert an org-mode file with all levels allowed to one with odd levels.
8118 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8119 level 5 etc."
8120 (interactive)
8121 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8122 (let ((outline-level 'org-outline-level)
8123 (org-odd-levels-only nil) n)
8124 (save-excursion
8125 (goto-char (point-min))
8126 (while (re-search-forward "^\\*\\*+ " nil t)
8127 (setq n (- (length (match-string 0)) 2))
8128 (while (>= (setq n (1- n)) 0)
8129 (org-demote))
8130 (end-of-line 1))))))
8132 (defun org-convert-to-oddeven-levels ()
8133 "Convert an org-mode file with only odd levels to one with odd/even levels.
8134 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8135 file contains a section with an even level, conversion would
8136 destroy the structure of the file. An error is signaled in this
8137 case."
8138 (interactive)
8139 (goto-char (point-min))
8140 ;; First check if there are no even levels
8141 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8142 (org-show-context t)
8143 (error "Not all levels are odd in this file. Conversion not possible"))
8144 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8145 (let ((outline-regexp org-outline-regexp)
8146 (outline-level 'org-outline-level)
8147 (org-odd-levels-only nil) n)
8148 (save-excursion
8149 (goto-char (point-min))
8150 (while (re-search-forward "^\\*\\*+ " nil t)
8151 (setq n (/ (1- (length (match-string 0))) 2))
8152 (while (>= (setq n (1- n)) 0)
8153 (org-promote))
8154 (end-of-line 1))))))
8156 (defun org-tr-level (n)
8157 "Make N odd if required."
8158 (if org-odd-levels-only (1+ (/ n 2)) n))
8160 ;;; Vertical tree motion, cutting and pasting of subtrees
8162 (defun org-move-subtree-up (&optional arg)
8163 "Move the current subtree up past ARG headlines of the same level."
8164 (interactive "p")
8165 (org-move-subtree-down (- (prefix-numeric-value arg))))
8167 (defun org-move-subtree-down (&optional arg)
8168 "Move the current subtree down past ARG headlines of the same level."
8169 (interactive "p")
8170 (setq arg (prefix-numeric-value arg))
8171 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8172 'org-get-last-sibling))
8173 (ins-point (make-marker))
8174 (cnt (abs arg))
8175 (col (current-column))
8176 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8177 ;; Select the tree
8178 (org-back-to-heading)
8179 (setq beg0 (point))
8180 (save-excursion
8181 (setq ne-beg (org-back-over-empty-lines))
8182 (setq beg (point)))
8183 (save-match-data
8184 (save-excursion (outline-end-of-heading)
8185 (setq folded (outline-invisible-p)))
8186 (outline-end-of-subtree))
8187 (outline-next-heading)
8188 (setq ne-end (org-back-over-empty-lines))
8189 (setq end (point))
8190 (goto-char beg0)
8191 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8192 ;; include less whitespace
8193 (save-excursion
8194 (goto-char beg)
8195 (forward-line (- ne-beg ne-end))
8196 (setq beg (point))))
8197 ;; Find insertion point, with error handling
8198 (while (> cnt 0)
8199 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8200 (progn (goto-char beg0)
8201 (user-error "Cannot move past superior level or buffer limit")))
8202 (setq cnt (1- cnt)))
8203 (if (> arg 0)
8204 ;; Moving forward - still need to move over subtree
8205 (progn (org-end-of-subtree t t)
8206 (save-excursion
8207 (org-back-over-empty-lines)
8208 (or (bolp) (newline)))))
8209 (setq ne-ins (org-back-over-empty-lines))
8210 (move-marker ins-point (point))
8211 (setq txt (buffer-substring beg end))
8212 (org-save-markers-in-region beg end)
8213 (delete-region beg end)
8214 (org-remove-empty-overlays-at beg)
8215 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8216 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8217 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8218 (let ((bbb (point)))
8219 (insert-before-markers txt)
8220 (org-reinstall-markers-in-region bbb)
8221 (move-marker ins-point bbb))
8222 (or (bolp) (insert "\n"))
8223 (setq ins-end (point))
8224 (goto-char ins-point)
8225 (org-skip-whitespace)
8226 (when (and (< arg 0)
8227 (org-first-sibling-p)
8228 (> ne-ins ne-beg))
8229 ;; Move whitespace back to beginning
8230 (save-excursion
8231 (goto-char ins-end)
8232 (let ((kill-whole-line t))
8233 (kill-line (- ne-ins ne-beg)) (point)))
8234 (insert (make-string (- ne-ins ne-beg) ?\n)))
8235 (move-marker ins-point nil)
8236 (if folded
8237 (hide-subtree)
8238 (org-show-entry)
8239 (show-children)
8240 (org-cycle-hide-drawers 'children))
8241 (org-clean-visibility-after-subtree-move)
8242 ;; move back to the initial column we were at
8243 (move-to-column col)))
8245 (defvar org-subtree-clip ""
8246 "Clipboard for cut and paste of subtrees.
8247 This is actually only a copy of the kill, because we use the normal kill
8248 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8250 (defvar org-subtree-clip-folded nil
8251 "Was the last copied subtree folded?
8252 This is used to fold the tree back after pasting.")
8254 (defun org-cut-subtree (&optional n)
8255 "Cut the current subtree into the clipboard.
8256 With prefix arg N, cut this many sequential subtrees.
8257 This is a short-hand for marking the subtree and then cutting it."
8258 (interactive "p")
8259 (org-copy-subtree n 'cut))
8261 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8262 "Copy the current subtree it in the clipboard.
8263 With prefix arg N, copy this many sequential subtrees.
8264 This is a short-hand for marking the subtree and then copying it.
8265 If CUT is non-nil, actually cut the subtree.
8266 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8267 of some markers in the region, even if CUT is non-nil. This is
8268 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8269 (interactive "p")
8270 (let (beg end folded (beg0 (point)))
8271 (if (org-called-interactively-p 'any)
8272 (org-back-to-heading nil) ; take what looks like a subtree
8273 (org-back-to-heading t)) ; take what is really there
8274 (setq beg (point))
8275 (skip-chars-forward " \t\r\n")
8276 (save-match-data
8277 (if nosubtrees
8278 (outline-next-heading)
8279 (save-excursion (outline-end-of-heading)
8280 (setq folded (outline-invisible-p)))
8281 (condition-case nil
8282 (org-forward-heading-same-level (1- n) t)
8283 (error nil))
8284 (org-end-of-subtree t t)))
8285 (setq end (point))
8286 (goto-char beg0)
8287 (when (> end beg)
8288 (setq org-subtree-clip-folded folded)
8289 (when (or cut force-store-markers)
8290 (org-save-markers-in-region beg end))
8291 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8292 (setq org-subtree-clip (current-kill 0))
8293 (message "%s: Subtree(s) with %d characters"
8294 (if cut "Cut" "Copied")
8295 (length org-subtree-clip)))))
8297 (defun org-paste-subtree (&optional level tree for-yank)
8298 "Paste the clipboard as a subtree, with modification of headline level.
8299 The entire subtree is promoted or demoted in order to match a new headline
8300 level.
8302 If the cursor is at the beginning of a headline, the same level as
8303 that headline is used to paste the tree.
8305 If not, the new level is derived from the *visible* headings
8306 before and after the insertion point, and taken to be the inferior headline
8307 level of the two. So if the previous visible heading is level 3 and the
8308 next is level 4 (or vice versa), level 4 will be used for insertion.
8309 This makes sure that the subtree remains an independent subtree and does
8310 not swallow low level entries.
8312 You can also force a different level, either by using a numeric prefix
8313 argument, or by inserting the heading marker by hand. For example, if the
8314 cursor is after \"*****\", then the tree will be shifted to level 5.
8316 If optional TREE is given, use this text instead of the kill ring.
8318 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8319 move back over whitespace before inserting, and move point to the end of
8320 the inserted text when done."
8321 (interactive "P")
8322 (setq tree (or tree (and kill-ring (current-kill 0))))
8323 (unless (org-kill-is-subtree-p tree)
8324 (user-error "%s"
8325 (substitute-command-keys
8326 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8327 (org-with-limited-levels
8328 (let* ((visp (not (outline-invisible-p)))
8329 (txt tree)
8330 (^re_ "\\(\\*+\\)[ \t]*")
8331 (old-level (if (string-match org-outline-regexp-bol txt)
8332 (- (match-end 0) (match-beginning 0) 1)
8333 -1))
8334 (force-level (cond (level (prefix-numeric-value level))
8335 ((and (looking-at "[ \t]*$")
8336 (string-match
8337 "^\\*+$" (buffer-substring
8338 (point-at-bol) (point))))
8339 (- (match-end 1) (match-beginning 1)))
8340 ((and (bolp)
8341 (looking-at org-outline-regexp))
8342 (- (match-end 0) (point) 1))))
8343 (previous-level (save-excursion
8344 (condition-case nil
8345 (progn
8346 (outline-previous-visible-heading 1)
8347 (if (looking-at ^re_)
8348 (- (match-end 0) (match-beginning 0) 1)
8350 (error 1))))
8351 (next-level (save-excursion
8352 (condition-case nil
8353 (progn
8354 (or (looking-at org-outline-regexp)
8355 (outline-next-visible-heading 1))
8356 (if (looking-at ^re_)
8357 (- (match-end 0) (match-beginning 0) 1)
8359 (error 1))))
8360 (new-level (or force-level (max previous-level next-level)))
8361 (shift (if (or (= old-level -1)
8362 (= new-level -1)
8363 (= old-level new-level))
8365 (- new-level old-level)))
8366 (delta (if (> shift 0) -1 1))
8367 (func (if (> shift 0) 'org-demote 'org-promote))
8368 (org-odd-levels-only nil)
8369 beg end newend)
8370 ;; Remove the forced level indicator
8371 (if force-level
8372 (delete-region (point-at-bol) (point)))
8373 ;; Paste
8374 (beginning-of-line (if (bolp) 1 2))
8375 (setq beg (point))
8376 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8377 (insert-before-markers txt)
8378 (unless (string-match "\n\\'" txt) (insert "\n"))
8379 (setq newend (point))
8380 (org-reinstall-markers-in-region beg)
8381 (setq end (point))
8382 (goto-char beg)
8383 (skip-chars-forward " \t\n\r")
8384 (setq beg (point))
8385 (if (and (outline-invisible-p) visp)
8386 (save-excursion (outline-show-heading)))
8387 ;; Shift if necessary
8388 (unless (= shift 0)
8389 (save-restriction
8390 (narrow-to-region beg end)
8391 (while (not (= shift 0))
8392 (org-map-region func (point-min) (point-max))
8393 (setq shift (+ delta shift)))
8394 (goto-char (point-min))
8395 (setq newend (point-max))))
8396 (when (or (org-called-interactively-p 'interactive) for-yank)
8397 (message "Clipboard pasted as level %d subtree" new-level))
8398 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8399 kill-ring
8400 (eq org-subtree-clip (current-kill 0))
8401 org-subtree-clip-folded)
8402 ;; The tree was folded before it was killed/copied
8403 (hide-subtree))
8404 (and for-yank (goto-char newend)))))
8406 (defun org-kill-is-subtree-p (&optional txt)
8407 "Check if the current kill is an outline subtree, or a set of trees.
8408 Returns nil if kill does not start with a headline, or if the first
8409 headline level is not the largest headline level in the tree.
8410 So this will actually accept several entries of equal levels as well,
8411 which is OK for `org-paste-subtree'.
8412 If optional TXT is given, check this string instead of the current kill."
8413 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8414 (re (org-get-limited-outline-regexp))
8415 (^re (concat "^" re))
8416 (start-level (and kill
8417 (string-match
8418 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8419 kill)
8420 (- (match-end 2) (match-beginning 2) 1)))
8421 (start (1+ (or (match-beginning 2) -1))))
8422 (if (not start-level)
8423 (progn
8424 nil) ;; does not even start with a heading
8425 (catch 'exit
8426 (while (setq start (string-match ^re kill (1+ start)))
8427 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8428 (throw 'exit nil)))
8429 t))))
8431 (defvar org-markers-to-move nil
8432 "Markers that should be moved with a cut-and-paste operation.
8433 Those markers are stored together with their positions relative to
8434 the start of the region.")
8436 (defun org-save-markers-in-region (beg end)
8437 "Check markers in region.
8438 If these markers are between BEG and END, record their position relative
8439 to BEG, so that after moving the block of text, we can put the markers back
8440 into place.
8441 This function gets called just before an entry or tree gets cut from the
8442 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8443 called immediately, to move the markers with the entries."
8444 (setq org-markers-to-move nil)
8445 (when (featurep 'org-clock)
8446 (org-clock-save-markers-for-cut-and-paste beg end))
8447 (when (featurep 'org-agenda)
8448 (org-agenda-save-markers-for-cut-and-paste beg end)))
8450 (defun org-check-and-save-marker (marker beg end)
8451 "Check if MARKER is between BEG and END.
8452 If yes, remember the marker and the distance to BEG."
8453 (when (and (marker-buffer marker)
8454 (equal (marker-buffer marker) (current-buffer)))
8455 (if (and (>= marker beg) (< marker end))
8456 (push (cons marker (- marker beg)) org-markers-to-move))))
8458 (defun org-reinstall-markers-in-region (beg)
8459 "Move all remembered markers to their position relative to BEG."
8460 (mapc (lambda (x)
8461 (move-marker (car x) (+ beg (cdr x))))
8462 org-markers-to-move)
8463 (setq org-markers-to-move nil))
8465 (defun org-narrow-to-subtree ()
8466 "Narrow buffer to the current subtree."
8467 (interactive)
8468 (save-excursion
8469 (save-match-data
8470 (org-with-limited-levels
8471 (narrow-to-region
8472 (progn (org-back-to-heading t) (point))
8473 (progn (org-end-of-subtree t t)
8474 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8475 (point)))))))
8477 (defun org-narrow-to-block ()
8478 "Narrow buffer to the current block."
8479 (interactive)
8480 (let* ((case-fold-search t)
8481 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8482 "^[ \t]*#\\+end_.*")))
8483 (if blockp
8484 (narrow-to-region (car blockp) (cdr blockp))
8485 (user-error "Not in a block"))))
8487 (eval-when-compile
8488 (defvar org-property-drawer-re))
8490 (defvar org-property-start-re) ;; defined below
8491 (defun org-clone-subtree-with-time-shift (n &optional shift)
8492 "Clone the task (subtree) at point N times.
8493 The clones will be inserted as siblings.
8495 In interactive use, the user will be prompted for the number of
8496 clones to be produced. If the entry has a timestamp, the user
8497 will also be prompted for a time shift, which may be a repeater
8498 as used in time stamps, for example `+3d'. To disable this,
8499 you can call the function with a universal prefix argument.
8501 When a valid repeater is given and the entry contains any time
8502 stamps, the clones will become a sequence in time, with time
8503 stamps in the subtree shifted for each clone produced. If SHIFT
8504 is nil or the empty string, time stamps will be left alone. The
8505 ID property of the original subtree is removed.
8507 If the original subtree did contain time stamps with a repeater,
8508 the following will happen:
8509 - the repeater will be removed in each clone
8510 - an additional clone will be produced, with the current, unshifted
8511 date(s) in the entry.
8512 - the original entry will be placed *after* all the clones, with
8513 repeater intact.
8514 - the start days in the repeater in the original entry will be shifted
8515 to past the last clone.
8516 In this way you can spell out a number of instances of a repeating task,
8517 and still retain the repeater to cover future instances of the task."
8518 (interactive "nNumber of clones to produce: ")
8519 (let ((shift
8520 (or shift
8521 (if (and (not (equal current-prefix-arg '(4)))
8522 (save-excursion
8523 (re-search-forward org-ts-regexp-both
8524 (save-excursion
8525 (org-end-of-subtree t)
8526 (point)) t)))
8527 (read-from-minibuffer
8528 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8529 ""))) ;; No time shift
8530 (n-no-remove -1)
8531 (drawer-re org-drawer-regexp)
8532 beg end template task idprop
8533 shift-n shift-what doshift nmin nmax)
8534 (if (not (and (integerp n) (> n 0)))
8535 (error "Invalid number of replications %s" n))
8536 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8537 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8538 shift)))
8539 (error "Invalid shift specification %s" shift))
8540 (when doshift
8541 (setq shift-n (string-to-number (match-string 1 shift))
8542 shift-what (cdr (assoc (match-string 2 shift)
8543 '(("d" . day) ("w" . week)
8544 ("m" . month) ("y" . year))))))
8545 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8546 (setq nmin 1 nmax n)
8547 (org-back-to-heading t)
8548 (setq beg (point))
8549 (setq idprop (org-entry-get nil "ID"))
8550 (org-end-of-subtree t t)
8551 (or (bolp) (insert "\n"))
8552 (setq end (point))
8553 (setq template (buffer-substring beg end))
8554 (when (and doshift
8555 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8556 (delete-region beg end)
8557 (setq end beg)
8558 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8559 (goto-char end)
8560 (loop for n from nmin to nmax do
8561 ;; prepare clone
8562 (with-temp-buffer
8563 (insert template)
8564 (org-mode)
8565 (goto-char (point-min))
8566 (org-show-subtree)
8567 (and idprop (if org-clone-delete-id
8568 (org-entry-delete nil "ID")
8569 (org-id-get-create t)))
8570 (unless (= n 0)
8571 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8572 (kill-whole-line))
8573 (goto-char (point-min))
8574 (while (re-search-forward drawer-re nil t)
8575 (org-remove-empty-drawer-at (point))))
8576 (goto-char (point-min))
8577 (when doshift
8578 (while (re-search-forward org-ts-regexp-both nil t)
8579 (org-timestamp-change (* n shift-n) shift-what))
8580 (unless (= n n-no-remove)
8581 (goto-char (point-min))
8582 (while (re-search-forward org-ts-regexp nil t)
8583 (save-excursion
8584 (goto-char (match-beginning 0))
8585 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8586 (delete-region (match-beginning 1) (match-end 1)))))))
8587 (setq task (buffer-string)))
8588 (insert task))
8589 (goto-char beg)))
8591 ;;; Outline Sorting
8593 (defun org-sort (with-case)
8594 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8595 Optional argument WITH-CASE means sort case-sensitively."
8596 (interactive "P")
8597 (cond
8598 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8599 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8601 (org-call-with-arg 'org-sort-entries with-case))))
8603 (defun org-sort-remove-invisible (s)
8604 "Remove invisible links from string S."
8605 (remove-text-properties 0 (length s) org-rm-props s)
8606 (while (string-match org-bracket-link-regexp s)
8607 (setq s (replace-match (if (match-end 2)
8608 (match-string 3 s)
8609 (match-string 1 s)) t t s)))
8610 (let ((st (format " %s " s)))
8611 (while (string-match org-emph-re st)
8612 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8613 (setq s (substring st 1 -1)))
8616 (defvar org-priority-regexp) ; defined later in the file
8618 (defvar org-after-sorting-entries-or-items-hook nil
8619 "Hook that is run after a bunch of entries or items have been sorted.
8620 When children are sorted, the cursor is in the parent line when this
8621 hook gets called. When a region or a plain list is sorted, the cursor
8622 will be in the first entry of the sorted region/list.")
8624 (defun org-sort-entries
8625 (&optional with-case sorting-type getkey-func compare-func property)
8626 "Sort entries on a certain level of an outline tree.
8627 If there is an active region, the entries in the region are sorted.
8628 Else, if the cursor is before the first entry, sort the top-level items.
8629 Else, the children of the entry at point are sorted.
8631 Sorting can be alphabetically, numerically, by date/time as given by
8632 a time stamp, by a property, by priority order, or by a custom function.
8634 The command prompts for the sorting type unless it has been given to the
8635 function through the SORTING-TYPE argument, which needs to be a character,
8636 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8637 precise meaning of each character:
8639 n Numerically, by converting the beginning of the entry/item to a number.
8640 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8641 o By order of TODO keywords.
8642 t By date/time, either the first active time stamp in the entry, or, if
8643 none exist, by the first inactive one.
8644 s By the scheduled date/time.
8645 d By deadline date/time.
8646 c By creation time, which is assumed to be the first inactive time stamp
8647 at the beginning of a line.
8648 p By priority according to the cookie.
8649 r By the value of a property.
8651 Capital letters will reverse the sort order.
8653 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8654 called with point at the beginning of the record. It must return either
8655 a string or a number that should serve as the sorting key for that record.
8657 Comparing entries ignores case by default. However, with an optional argument
8658 WITH-CASE, the sorting considers case as well.
8660 Sorting is done against the visible part of the headlines, it ignores hidden
8661 links.
8663 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
8664 (interactive "P")
8665 (let ((case-func (if with-case 'identity 'downcase))
8666 (cmstr
8667 ;; The clock marker is lost when using `sort-subr', let's
8668 ;; store the clocking string.
8669 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8670 (save-excursion
8671 (goto-char org-clock-marker)
8672 (looking-back "^.*") (match-string-no-properties 0))))
8673 start beg end stars re re2
8674 txt what tmp)
8675 ;; Find beginning and end of region to sort
8676 (cond
8677 ((org-region-active-p)
8678 ;; we will sort the region
8679 (setq end (region-end)
8680 what "region")
8681 (goto-char (region-beginning))
8682 (if (not (org-at-heading-p)) (outline-next-heading))
8683 (setq start (point)))
8684 ((or (org-at-heading-p)
8685 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8686 ;; we will sort the children of the current headline
8687 (org-back-to-heading)
8688 (setq start (point)
8689 end (progn (org-end-of-subtree t t)
8690 (or (bolp) (insert "\n"))
8691 (org-back-over-empty-lines)
8692 (point))
8693 what "children")
8694 (goto-char start)
8695 (show-subtree)
8696 (outline-next-heading))
8698 ;; we will sort the top-level entries in this file
8699 (goto-char (point-min))
8700 (or (org-at-heading-p) (outline-next-heading))
8701 (setq start (point))
8702 (goto-char (point-max))
8703 (beginning-of-line 1)
8704 (when (looking-at ".*?\\S-")
8705 ;; File ends in a non-white line
8706 (end-of-line 1)
8707 (insert "\n"))
8708 (setq end (point-max))
8709 (setq what "top-level")
8710 (goto-char start)
8711 (show-all)))
8713 (setq beg (point))
8714 (if (>= beg end) (user-error "Nothing to sort"))
8716 (looking-at "\\(\\*+\\)")
8717 (setq stars (match-string 1)
8718 re (concat "^" (regexp-quote stars) " +")
8719 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8720 txt (buffer-substring beg end))
8721 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8722 (if (and (not (equal stars "*")) (string-match re2 txt))
8723 (user-error "Region to sort contains a level above the first entry"))
8725 (unless sorting-type
8726 (message
8727 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8728 [t]ime [s]cheduled [d]eadline [c]reated
8729 A/N/P/R/O/F/T/S/D/C means reversed:"
8730 what)
8731 (setq sorting-type (read-char-exclusive))
8733 (unless getkey-func
8734 (and (= (downcase sorting-type) ?f)
8735 (setq getkey-func
8736 (org-icompleting-read "Sort using function: "
8737 obarray 'fboundp t nil nil))
8738 (setq getkey-func (intern getkey-func))))
8740 (and (= (downcase sorting-type) ?r)
8741 (not property)
8742 (setq property
8743 (org-icompleting-read "Property: "
8744 (mapcar 'list (org-buffer-property-keys t))
8745 nil t))))
8747 (message "Sorting entries...")
8749 (save-restriction
8750 (narrow-to-region start end)
8751 (let ((dcst (downcase sorting-type))
8752 (case-fold-search nil)
8753 (now (current-time)))
8754 (sort-subr
8755 (/= dcst sorting-type)
8756 ;; This function moves to the beginning character of the "record" to
8757 ;; be sorted.
8758 (lambda nil
8759 (if (re-search-forward re nil t)
8760 (goto-char (match-beginning 0))
8761 (goto-char (point-max))))
8762 ;; This function moves to the last character of the "record" being
8763 ;; sorted.
8764 (lambda nil
8765 (save-match-data
8766 (condition-case nil
8767 (outline-forward-same-level 1)
8768 (error
8769 (goto-char (point-max))))))
8770 ;; This function returns the value that gets sorted against.
8771 (lambda nil
8772 (cond
8773 ((= dcst ?n)
8774 (if (looking-at org-complex-heading-regexp)
8775 (string-to-number (org-sort-remove-invisible (match-string 4)))
8776 nil))
8777 ((= dcst ?a)
8778 (if (looking-at org-complex-heading-regexp)
8779 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8780 nil))
8781 ((= dcst ?t)
8782 (let ((end (save-excursion (outline-next-heading) (point))))
8783 (if (or (re-search-forward org-ts-regexp end t)
8784 (re-search-forward org-ts-regexp-both end t))
8785 (org-time-string-to-seconds (match-string 0))
8786 (org-float-time now))))
8787 ((= dcst ?c)
8788 (let ((end (save-excursion (outline-next-heading) (point))))
8789 (if (re-search-forward
8790 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8791 end t)
8792 (org-time-string-to-seconds (match-string 0))
8793 (org-float-time now))))
8794 ((= dcst ?s)
8795 (let ((end (save-excursion (outline-next-heading) (point))))
8796 (if (re-search-forward org-scheduled-time-regexp end t)
8797 (org-time-string-to-seconds (match-string 1))
8798 (org-float-time now))))
8799 ((= dcst ?d)
8800 (let ((end (save-excursion (outline-next-heading) (point))))
8801 (if (re-search-forward org-deadline-time-regexp end t)
8802 (org-time-string-to-seconds (match-string 1))
8803 (org-float-time now))))
8804 ((= dcst ?p)
8805 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8806 (string-to-char (match-string 2))
8807 org-default-priority))
8808 ((= dcst ?r)
8809 (or (org-entry-get nil property) ""))
8810 ((= dcst ?o)
8811 (if (looking-at org-complex-heading-regexp)
8812 (- 9999 (length (member (match-string 2)
8813 org-todo-keywords-1)))))
8814 ((= dcst ?f)
8815 (if getkey-func
8816 (progn
8817 (setq tmp (funcall getkey-func))
8818 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8819 tmp)
8820 (error "Invalid key function `%s'" getkey-func)))
8821 (t (error "Invalid sorting type `%c'" sorting-type))))
8823 (cond
8824 ((= dcst ?a) 'string<)
8825 ((= dcst ?f) compare-func)
8826 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8827 (run-hooks 'org-after-sorting-entries-or-items-hook)
8828 ;; Reset the clock marker if needed
8829 (when cmstr
8830 (save-excursion
8831 (goto-char start)
8832 (search-forward cmstr nil t)
8833 (move-marker org-clock-marker (point))))
8834 (message "Sorting entries...done")))
8836 (defun org-do-sort (table what &optional with-case sorting-type)
8837 "Sort TABLE of WHAT according to SORTING-TYPE.
8838 The user will be prompted for the SORTING-TYPE if the call to this
8839 function does not specify it. WHAT is only for the prompt, to indicate
8840 what is being sorted. The sorting key will be extracted from
8841 the car of the elements of the table.
8842 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8843 (unless sorting-type
8844 (message
8845 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8846 what)
8847 (setq sorting-type (read-char-exclusive)))
8848 (let ((dcst (downcase sorting-type))
8849 extractfun comparefun)
8850 ;; Define the appropriate functions
8851 (cond
8852 ((= dcst ?n)
8853 (setq extractfun 'string-to-number
8854 comparefun (if (= dcst sorting-type) '< '>)))
8855 ((= dcst ?a)
8856 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8857 (lambda(x) (downcase (org-sort-remove-invisible x))))
8858 comparefun (if (= dcst sorting-type)
8859 'string<
8860 (lambda (a b) (and (not (string< a b))
8861 (not (string= a b)))))))
8862 ((= dcst ?t)
8863 (setq extractfun
8864 (lambda (x)
8865 (if (or (string-match org-ts-regexp x)
8866 (string-match org-ts-regexp-both x))
8867 (org-float-time
8868 (org-time-string-to-time (match-string 0 x)))
8870 comparefun (if (= dcst sorting-type) '< '>)))
8871 (t (error "Invalid sorting type `%c'" sorting-type)))
8873 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8874 table)
8875 (lambda (a b) (funcall comparefun (car a) (car b))))))
8878 ;;; The orgstruct minor mode
8880 ;; Define a minor mode which can be used in other modes in order to
8881 ;; integrate the org-mode structure editing commands.
8883 ;; This is really a hack, because the org-mode structure commands use
8884 ;; keys which normally belong to the major mode. Here is how it
8885 ;; works: The minor mode defines all the keys necessary to operate the
8886 ;; structure commands, but wraps the commands into a function which
8887 ;; tests if the cursor is currently at a headline or a plain list
8888 ;; item. If that is the case, the structure command is used,
8889 ;; temporarily setting many Org-mode variables like regular
8890 ;; expressions for filling etc. However, when any of those keys is
8891 ;; used at a different location, function uses `key-binding' to look
8892 ;; up if the key has an associated command in another currently active
8893 ;; keymap (minor modes, major mode, global), and executes that
8894 ;; command. There might be problems if any of the keys is otherwise
8895 ;; used as a prefix key.
8897 (defcustom orgstruct-heading-prefix-regexp ""
8898 "Regexp that matches the custom prefix of Org headlines in
8899 orgstruct(++)-mode."
8900 :group 'org
8901 :version "24.4"
8902 :package-version '(Org . "8.3")
8903 :type 'regexp)
8904 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8906 (defcustom orgstruct-setup-hook nil
8907 "Hook run after orgstruct-mode-map is filled."
8908 :group 'org
8909 :version "24.4"
8910 :package-version '(Org . "8.0")
8911 :type 'hook)
8913 (defvar orgstruct-initialized nil)
8915 (defvar org-local-vars nil
8916 "List of local variables, for use by `orgstruct-mode'.")
8918 ;;;###autoload
8919 (define-minor-mode orgstruct-mode
8920 "Toggle the minor mode `orgstruct-mode'.
8921 This mode is for using Org-mode structure commands in other
8922 modes. The following keys behave as if Org-mode were active, if
8923 the cursor is on a headline, or on a plain list item (both as
8924 defined by Org-mode)."
8925 nil " OrgStruct" (make-sparse-keymap)
8926 (funcall (if orgstruct-mode
8927 'add-to-invisibility-spec
8928 'remove-from-invisibility-spec)
8929 '(outline . t))
8930 (when orgstruct-mode
8931 (org-load-modules-maybe)
8932 (unless orgstruct-initialized
8933 (orgstruct-setup)
8934 (setq orgstruct-initialized t))))
8936 ;;;###autoload
8937 (defun turn-on-orgstruct ()
8938 "Unconditionally turn on `orgstruct-mode'."
8939 (orgstruct-mode 1))
8941 (defvar org-fb-vars nil)
8942 (make-variable-buffer-local 'org-fb-vars)
8943 (defun orgstruct++-mode (&optional arg)
8944 "Toggle `orgstruct-mode', the enhanced version of it.
8945 In addition to setting orgstruct-mode, this also exports all
8946 indentation and autofilling variables from org-mode into the
8947 buffer. It will also recognize item context in multiline items."
8948 (interactive "P")
8949 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8950 (if (< arg 1)
8951 (progn (orgstruct-mode -1)
8952 (mapc (lambda(v)
8953 (org-set-local (car v)
8954 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8955 org-fb-vars))
8956 (orgstruct-mode 1)
8957 (setq org-fb-vars nil)
8958 (unless org-local-vars
8959 (setq org-local-vars (org-get-local-variables)))
8960 (let (var val)
8961 (mapc
8962 (lambda (x)
8963 (when (string-match
8964 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8965 (symbol-name (car x)))
8966 (setq var (car x) val (nth 1 x))
8967 (push (list var `(quote ,(eval var))) org-fb-vars)
8968 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8969 org-local-vars)
8970 (org-set-local 'orgstruct-is-++ t))))
8972 (defvar orgstruct-is-++ nil
8973 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8974 (make-variable-buffer-local 'orgstruct-is-++)
8976 ;;;###autoload
8977 (defun turn-on-orgstruct++ ()
8978 "Unconditionally turn on `orgstruct++-mode'."
8979 (orgstruct++-mode 1))
8981 (defun orgstruct-error ()
8982 "Error when there is no default binding for a structure key."
8983 (interactive)
8984 (funcall (if (fboundp 'user-error)
8985 'user-error
8986 'error)
8987 "This key has no function outside structure elements"))
8989 (defun orgstruct-setup ()
8990 "Setup orgstruct keymap."
8991 (dolist (cell '((org-demote . t)
8992 (org-metaleft . t)
8993 (org-metaright . t)
8994 (org-promote . t)
8995 (org-shiftmetaleft . t)
8996 (org-shiftmetaright . t)
8997 org-backward-element
8998 org-backward-heading-same-level
8999 org-ctrl-c-ret
9000 org-ctrl-c-minus
9001 org-ctrl-c-star
9002 org-cycle
9003 org-forward-heading-same-level
9004 org-insert-heading
9005 org-insert-heading-respect-content
9006 org-kill-note-or-show-branches
9007 org-mark-subtree
9008 org-meta-return
9009 org-metadown
9010 org-metaup
9011 org-narrow-to-subtree
9012 org-promote-subtree
9013 org-reveal
9014 org-shiftdown
9015 org-shiftleft
9016 org-shiftmetadown
9017 org-shiftmetaup
9018 org-shiftright
9019 org-shifttab
9020 org-shifttab
9021 org-shiftup
9022 org-show-subtree
9023 org-sort
9024 org-up-element
9025 outline-demote
9026 outline-next-visible-heading
9027 outline-previous-visible-heading
9028 outline-promote
9029 outline-up-heading
9030 show-children))
9031 (let ((f (or (car-safe cell) cell))
9032 (disable-when-heading-prefix (cdr-safe cell)))
9033 (when (fboundp f)
9034 (let ((new-bindings))
9035 (dolist (binding (nconc (where-is-internal f org-mode-map)
9036 (where-is-internal f outline-mode-map)))
9037 (push binding new-bindings)
9038 ;; TODO use local-function-key-map
9039 (dolist (rep '(("<tab>" . "TAB")
9040 ("<return>" . "RET")
9041 ("<escape>" . "ESC")
9042 ("<delete>" . "DEL")))
9043 (setq binding (read-kbd-macro
9044 (let ((case-fold-search))
9045 (replace-regexp-in-string
9046 (regexp-quote (cdr rep))
9047 (car rep)
9048 (key-description binding)))))
9049 (pushnew binding new-bindings :test 'equal)))
9050 (dolist (binding new-bindings)
9051 (let ((key (lookup-key orgstruct-mode-map binding)))
9052 (when (or (not key) (numberp key))
9053 (condition-case nil
9054 (org-defkey orgstruct-mode-map
9055 binding
9056 (orgstruct-make-binding f binding disable-when-heading-prefix))
9057 (error nil)))))))))
9058 (run-hooks 'orgstruct-setup-hook))
9060 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9061 "Create a function for binding in the structure minor mode.
9062 FUN is the command to call inside a table. KEY is the key that
9063 should be checked in for a command to execute outside of tables.
9064 Non-nil `disable-when-heading-prefix' means to disable the command
9065 if `orgstruct-heading-prefix-regexp' is not empty."
9066 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9067 (let ((nname name)
9068 (i 0))
9069 (while (fboundp (intern nname))
9070 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9071 (setq name (intern nname)))
9072 (eval
9073 (let ((bindings '((org-heading-regexp
9074 (concat "^"
9075 orgstruct-heading-prefix-regexp
9076 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9077 (org-outline-regexp
9078 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9079 (org-outline-regexp-bol
9080 (concat "^" org-outline-regexp))
9081 (outline-regexp org-outline-regexp)
9082 (outline-heading-end-regexp "\n")
9083 (outline-level 'org-outline-level)
9084 (outline-heading-alist))))
9085 `(defun ,name (arg)
9086 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9087 "Outside of structure, run the binding of `"
9088 (key-description key) "'."
9089 (when disable-when-heading-prefix
9090 (concat
9091 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9092 "back to the default binding due to limitations of Org's implementation of\n"
9093 "`" (symbol-name fun) "'.")))
9094 (interactive "p")
9095 (let* ((disable
9096 ,(and disable-when-heading-prefix
9097 '(not (string= orgstruct-heading-prefix-regexp ""))))
9098 (fallback
9099 (or disable
9100 (not
9101 (let* ,bindings
9102 (org-context-p 'headline 'item
9103 ,(when (memq fun
9104 '(org-insert-heading
9105 org-insert-heading-respect-content
9106 org-meta-return))
9107 '(when orgstruct-is-++
9108 'item-body))))))))
9109 (if fallback
9110 (let* ((orgstruct-mode)
9111 (binding
9112 (loop with key = ,key
9113 for rep in
9114 '(nil
9115 ("<\\([^>]*\\)tab>" . "\\1TAB")
9116 ("<\\([^>]*\\)return>" . "\\1RET")
9117 ("<\\([^>]*\\)escape>" . "\\1ESC")
9118 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9120 (when rep
9121 (setq key (read-kbd-macro
9122 (let ((case-fold-search))
9123 (replace-regexp-in-string
9124 (car rep)
9125 (cdr rep)
9126 (key-description key))))))
9127 thereis (key-binding key))))
9128 (if (keymapp binding)
9129 (set-temporary-overlay-map binding)
9130 (let ((func (or binding
9131 (unless disable
9132 'orgstruct-error))))
9133 (when func
9134 (call-interactively func)))))
9135 (org-run-like-in-org-mode
9136 (lambda ()
9137 (interactive)
9138 (let* ,bindings
9139 (call-interactively ',fun)))))))))
9140 name))
9142 (defun org-contextualize-keys (alist contexts)
9143 "Return valid elements in ALIST depending on CONTEXTS.
9145 `org-agenda-custom-commands' or `org-capture-templates' are the
9146 values used for ALIST, and `org-agenda-custom-commands-contexts'
9147 or `org-capture-templates-contexts' are the associated contexts
9148 definitions."
9149 (let ((contexts
9150 ;; normalize contexts
9151 (mapcar
9152 (lambda(c) (cond ((listp (cadr c))
9153 (list (car c) (car c) (cadr c)))
9154 ((string= "" (cadr c))
9155 (list (car c) (car c) (caddr c)))
9156 (t c))) contexts))
9157 (a alist) c r s)
9158 ;; loop over all commands or templates
9159 (while (setq c (pop a))
9160 (let (vrules repl)
9161 (cond
9162 ((not (assoc (car c) contexts))
9163 (push c r))
9164 ((and (assoc (car c) contexts)
9165 (setq vrules (org-contextualize-validate-key
9166 (car c) contexts)))
9167 (mapc (lambda (vr)
9168 (when (not (equal (car vr) (cadr vr)))
9169 (setq repl vr))) vrules)
9170 (if (not repl) (push c r)
9171 (push (cadr repl) s)
9172 (push
9173 (cons (car c)
9174 (cdr (or (assoc (cadr repl) alist)
9175 (error "Undefined key `%s' as contextual replacement for `%s'"
9176 (cadr repl) (car c)))))
9177 r))))))
9178 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9179 (delq
9181 (delete-dups
9182 (mapcar (lambda (x)
9183 (let ((tpl (car x)))
9184 (when (not (delq
9186 (mapcar (lambda(y)
9187 (equal y tpl)) s))) x)))
9188 (reverse r))))))
9190 (defun org-contextualize-validate-key (key contexts)
9191 "Check CONTEXTS for agenda or capture KEY."
9192 (let (r rr res)
9193 (while (setq r (pop contexts))
9194 (mapc
9195 (lambda (rr)
9196 (when
9197 (and (equal key (car r))
9198 (if (functionp rr) (funcall rr)
9199 (or (and (eq (car rr) 'in-file)
9200 (buffer-file-name)
9201 (string-match (cdr rr) (buffer-file-name)))
9202 (and (eq (car rr) 'in-mode)
9203 (string-match (cdr rr) (symbol-name major-mode)))
9204 (and (eq (car rr) 'in-buffer)
9205 (string-match (cdr rr) (buffer-name)))
9206 (when (and (eq (car rr) 'not-in-file)
9207 (buffer-file-name))
9208 (not (string-match (cdr rr) (buffer-file-name))))
9209 (when (eq (car rr) 'not-in-mode)
9210 (not (string-match (cdr rr) (symbol-name major-mode))))
9211 (when (eq (car rr) 'not-in-buffer)
9212 (not (string-match (cdr rr) (buffer-name)))))))
9213 (push r res)))
9214 (car (last r))))
9215 (delete-dups (delq nil res))))
9217 (defun org-context-p (&rest contexts)
9218 "Check if local context is any of CONTEXTS.
9219 Possible values in the list of contexts are `table', `headline', and `item'."
9220 (let ((pos (point)))
9221 (goto-char (point-at-bol))
9222 (prog1 (or (and (memq 'table contexts)
9223 (looking-at "[ \t]*|"))
9224 (and (memq 'headline contexts)
9225 (looking-at org-outline-regexp))
9226 (and (memq 'item contexts)
9227 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9228 (and (memq 'item-body contexts)
9229 (org-in-item-p)))
9230 (goto-char pos))))
9232 (defun org-get-local-variables ()
9233 "Return a list of all local variables in an Org mode buffer."
9234 (let (varlist)
9235 (with-current-buffer (get-buffer-create "*Org tmp*")
9236 (erase-buffer)
9237 (org-mode)
9238 (setq varlist (buffer-local-variables)))
9239 (kill-buffer "*Org tmp*")
9240 (delq nil
9241 (mapcar
9242 (lambda (x)
9243 (setq x
9244 (if (symbolp x)
9245 (list x)
9246 (list (car x) (cdr x))))
9247 (if (and (not (get (car x) 'org-state))
9248 (string-match
9249 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9250 (symbol-name (car x))))
9251 x nil))
9252 varlist))))
9254 (defun org-clone-local-variables (from-buffer &optional regexp)
9255 "Clone local variables from FROM-BUFFER.
9256 Optional argument REGEXP selects variables to clone."
9257 (mapc
9258 (lambda (pair)
9259 (and (symbolp (car pair))
9260 (or (null regexp)
9261 (string-match regexp (symbol-name (car pair))))
9262 (set (make-local-variable (car pair))
9263 (cdr pair))))
9264 (buffer-local-variables from-buffer)))
9266 ;;;###autoload
9267 (defun org-run-like-in-org-mode (cmd)
9268 "Run a command, pretending that the current buffer is in Org-mode.
9269 This will temporarily bind local variables that are typically bound in
9270 Org-mode to the values they have in Org-mode, and then interactively
9271 call CMD."
9272 (org-load-modules-maybe)
9273 (unless org-local-vars
9274 (setq org-local-vars (org-get-local-variables)))
9275 (let (binds)
9276 (dolist (var org-local-vars)
9277 (when (or (not (boundp (car var)))
9278 (eq (symbol-value (car var))
9279 (default-value (car var))))
9280 (push (list (car var) `(quote ,(cadr var))) binds)))
9281 (eval `(let ,binds
9282 (call-interactively (quote ,cmd))))))
9284 ;;;; Archiving
9286 (defun org-get-category (&optional pos force-refresh)
9287 "Get the category applying to position POS."
9288 (save-match-data
9289 (if force-refresh (org-refresh-category-properties))
9290 (let ((pos (or pos (point))))
9291 (or (get-text-property pos 'org-category)
9292 (progn (org-refresh-category-properties)
9293 (get-text-property pos 'org-category))))))
9295 (defun org-refresh-category-properties ()
9296 "Refresh category text properties in the buffer."
9297 (let ((case-fold-search t)
9298 (inhibit-read-only t)
9299 (def-cat (cond
9300 ((null org-category)
9301 (if buffer-file-name
9302 (file-name-sans-extension
9303 (file-name-nondirectory buffer-file-name))
9304 "???"))
9305 ((symbolp org-category) (symbol-name org-category))
9306 (t org-category)))
9307 beg end cat pos optionp)
9308 (org-with-silent-modifications
9309 (save-excursion
9310 (save-restriction
9311 (widen)
9312 (goto-char (point-min))
9313 (put-text-property (point) (point-max) 'org-category def-cat)
9314 (while (re-search-forward
9315 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9316 (setq pos (match-end 0)
9317 optionp (equal (char-after (match-beginning 0)) ?#)
9318 cat (org-trim (match-string 2)))
9319 (if optionp
9320 (setq beg (point-at-bol) end (point-max))
9321 (org-back-to-heading t)
9322 (setq beg (point) end (org-end-of-subtree t t)))
9323 (put-text-property beg end 'org-category cat)
9324 (put-text-property beg end 'org-category-position beg)
9325 (goto-char pos)))))))
9327 (defun org-refresh-properties (dprop tprop)
9328 "Refresh buffer text properties.
9329 DPROP is the drawer property and TPROP is the corresponding text
9330 property to set."
9331 (let ((case-fold-search t)
9332 (inhibit-read-only t) p)
9333 (org-with-silent-modifications
9334 (save-excursion
9335 (save-restriction
9336 (widen)
9337 (goto-char (point-min))
9338 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9339 (setq p (org-match-string-no-properties 1))
9340 (save-excursion
9341 (org-back-to-heading t)
9342 (put-text-property
9343 (point-at-bol) (org-end-of-subtree t t) tprop p))))))))
9346 ;;;; Link Stuff
9348 ;;; Link abbreviations
9350 (defun org-link-expand-abbrev (link)
9351 "Apply replacements as defined in `org-link-abbrev-alist'."
9352 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9353 (let* ((key (match-string 1 link))
9354 (as (or (assoc key org-link-abbrev-alist-local)
9355 (assoc key org-link-abbrev-alist)))
9356 (tag (and (match-end 2) (match-string 3 link)))
9357 rpl)
9358 (if (not as)
9359 link
9360 (setq rpl (cdr as))
9361 (cond
9362 ((symbolp rpl) (funcall rpl tag))
9363 ((string-match "%(\\([^)]+\\))" rpl)
9364 (replace-match
9365 (save-match-data
9366 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9367 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9368 ((string-match "%h" rpl)
9369 (replace-match (url-hexify-string (or tag "")) t t rpl))
9370 (t (concat rpl tag)))))
9371 link))
9373 ;;; Storing and inserting links
9375 (defvar org-insert-link-history nil
9376 "Minibuffer history for links inserted with `org-insert-link'.")
9378 (defvar org-stored-links nil
9379 "Contains the links stored with `org-store-link'.")
9381 (defvar org-store-link-plist nil
9382 "Plist with info about the most recently link created with `org-store-link'.")
9384 (defvar org-link-protocols nil
9385 "Link protocols added to Org-mode using `org-add-link-type'.")
9387 (defvar org-store-link-functions nil
9388 "List of functions that are called to create and store a link.
9389 Each function will be called in turn until one returns a non-nil
9390 value. Each function should check if it is responsible for creating
9391 this link (for example by looking at the major mode).
9392 If not, it must exit and return nil.
9393 If yes, it should return a non-nil value after a calling
9394 `org-store-link-props' with a list of properties and values.
9395 Special properties are:
9397 :type The link prefix, like \"http\". This must be given.
9398 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9399 This is obligatory as well.
9400 :description Optional default description for the second pair
9401 of brackets in an Org-mode link. The user can still change
9402 this when inserting this link into an Org-mode buffer.
9404 In addition to these, any additional properties can be specified
9405 and then used in capture templates.")
9407 (defun org-add-link-type (type &optional follow export)
9408 "Add TYPE to the list of `org-link-types'.
9409 Re-compute all regular expressions depending on `org-link-types'
9411 FOLLOW and EXPORT are two functions.
9413 FOLLOW should take the link path as the single argument and do whatever
9414 is necessary to follow the link, for example find a file or display
9415 a mail message.
9417 EXPORT should format the link path for export to one of the export formats.
9418 It should be a function accepting three arguments:
9420 path the path of the link, the text after the prefix (like \"http:\")
9421 desc the description of the link, if any, or a description added by
9422 org-export-normalize-links if there is none
9423 format the export format, a symbol like `html' or `latex' or `ascii'..
9425 The function may use the FORMAT information to return different values
9426 depending on the format. The return value will be put literally into
9427 the exported file. If the return value is nil, this means Org should
9428 do what it normally does with links which do not have EXPORT defined.
9430 Org-mode has a built-in default for exporting links. If you are happy with
9431 this default, there is no need to define an export function for the link
9432 type. For a simple example of an export function, see `org-bbdb.el'."
9433 (add-to-list 'org-link-types type t)
9434 (org-make-link-regexps)
9435 (if (assoc type org-link-protocols)
9436 (setcdr (assoc type org-link-protocols) (list follow export))
9437 (push (list type follow export) org-link-protocols)))
9439 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9440 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9442 ;;;###autoload
9443 (defun org-store-link (arg)
9444 "\\<org-mode-map>Store an org-link to the current location.
9445 This link is added to `org-stored-links' and can later be inserted
9446 into an org-buffer with \\[org-insert-link].
9448 For some link types, a prefix arg is interpreted.
9449 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9450 For file links, arg negates `org-context-in-file-links'.
9452 A double prefix arg force skipping storing functions that are not
9453 part of Org's core.
9455 A triple prefix arg force storing a link for each line in the
9456 active region."
9457 (interactive "P")
9458 (org-load-modules-maybe)
9459 (if (and (equal arg '(64)) (org-region-active-p))
9460 (save-excursion
9461 (let ((end (region-end)))
9462 (goto-char (region-beginning))
9463 (set-mark (point))
9464 (while (< (point-at-eol) end)
9465 (move-end-of-line 1) (activate-mark)
9466 (let (current-prefix-arg)
9467 (call-interactively 'org-store-link))
9468 (move-beginning-of-line 2)
9469 (set-mark (point)))))
9470 (org-with-limited-levels
9471 (setq org-store-link-plist nil)
9472 (let (link cpltxt desc description search
9473 txt custom-id agenda-link sfuns sfunsn)
9474 (cond
9476 ;; Store a link using an external link type
9477 ((and (not (equal arg '(16)))
9478 (setq sfuns
9479 (delq
9480 nil (mapcar (lambda (f)
9481 (let (fs) (if (funcall f) (push f fs))))
9482 org-store-link-functions))
9483 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9484 (or (and (cdr sfuns)
9485 (funcall (intern
9486 (completing-read
9487 "Which function for creating the link? "
9488 sfunsn t (car sfunsn)))))
9489 (funcall (caar sfuns)))
9490 (setq link (plist-get org-store-link-plist :link)
9491 desc (or (plist-get org-store-link-plist
9492 :description) link))))
9494 ;; Store a link from a source code buffer
9495 ((org-src-edit-buffer-p)
9496 (let (label gc)
9497 (while (or (not label)
9498 (save-excursion
9499 (save-restriction
9500 (widen)
9501 (goto-char (point-min))
9502 (re-search-forward
9503 (regexp-quote (format org-coderef-label-format label))
9504 nil t))))
9505 (when label (message "Label exists already") (sit-for 2))
9506 (setq label (read-string "Code line label: " label)))
9507 (end-of-line 1)
9508 (setq link (format org-coderef-label-format label))
9509 (setq gc (- 79 (length link)))
9510 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9511 (insert link)
9512 (setq link (concat "(" label ")") desc nil)))
9514 ;; We are in the agenda, link to referenced location
9515 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9516 (let ((m (or (get-text-property (point) 'org-hd-marker)
9517 (get-text-property (point) 'org-marker))))
9518 (when m
9519 (org-with-point-at m
9520 (setq agenda-link
9521 (if (org-called-interactively-p 'any)
9522 (call-interactively 'org-store-link)
9523 (org-store-link nil)))))))
9525 ((eq major-mode 'calendar-mode)
9526 (let ((cd (calendar-cursor-to-date)))
9527 (setq link
9528 (format-time-string
9529 (car org-time-stamp-formats)
9530 (apply 'encode-time
9531 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9532 nil nil nil))))
9533 (org-store-link-props :type "calendar" :date cd)))
9535 ((eq major-mode 'help-mode)
9536 (setq link (concat "help:" (save-excursion
9537 (goto-char (point-min))
9538 (looking-at "^[^ ]+")
9539 (match-string 0))))
9540 (org-store-link-props :type "help"))
9542 ((eq major-mode 'w3-mode)
9543 (setq cpltxt (if (and (buffer-name)
9544 (not (string-match "Untitled" (buffer-name))))
9545 (buffer-name)
9546 (url-view-url t))
9547 link (url-view-url t))
9548 (org-store-link-props :type "w3" :url (url-view-url t)))
9550 ((eq major-mode 'image-mode)
9551 (setq cpltxt (concat "file:"
9552 (abbreviate-file-name buffer-file-name))
9553 link cpltxt)
9554 (org-store-link-props :type "image" :file buffer-file-name))
9556 ;; In dired, store a link to the file of the current line
9557 ((eq major-mode 'dired-mode)
9558 (let ((file (dired-get-filename nil t)))
9559 (setq file (if file
9560 (abbreviate-file-name
9561 (expand-file-name (dired-get-filename nil t)))
9562 ;; otherwise, no file so use current directory.
9563 default-directory))
9564 (setq cpltxt (concat "file:" file)
9565 link cpltxt)))
9567 ((setq search (run-hook-with-args-until-success
9568 'org-create-file-search-functions))
9569 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9570 "::" search))
9571 (setq cpltxt (or description link)))
9573 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9574 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9575 (cond
9576 ;; Store a link using the target at point
9577 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9578 (setq cpltxt
9579 (concat "file:"
9580 (abbreviate-file-name
9581 (buffer-file-name (buffer-base-buffer)))
9582 "::" (match-string 1))
9583 link cpltxt))
9584 ((and (featurep 'org-id)
9585 (or (eq org-id-link-to-org-use-id t)
9586 (and (org-called-interactively-p 'any)
9587 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9588 (and (eq org-id-link-to-org-use-id
9589 'create-if-interactive-and-no-custom-id)
9590 (not custom-id))))
9591 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9592 ;; Store a link using the ID at point
9593 (setq link (condition-case nil
9594 (prog1 (org-id-store-link)
9595 (setq desc (plist-get org-store-link-plist
9596 :description)))
9597 (error
9598 ;; Probably before first headline, link only to file
9599 (concat "file:"
9600 (abbreviate-file-name
9601 (buffer-file-name (buffer-base-buffer))))))))
9603 ;; Just link to current headline
9604 (setq cpltxt (concat "file:"
9605 (abbreviate-file-name
9606 (buffer-file-name (buffer-base-buffer)))))
9607 ;; Add a context search string
9608 (when (org-xor org-context-in-file-links arg)
9609 (let* ((ee (org-element-at-point))
9610 (et (org-element-type ee))
9611 (ev (plist-get (cadr ee) :value))
9612 (ek (plist-get (cadr ee) :key))
9613 (eok (and (stringp ek) (string-match "name" ek))))
9614 (setq txt (cond
9615 ((org-at-heading-p) nil)
9616 ((and (eq et 'keyword) eok) ev)
9617 ((org-region-active-p)
9618 (buffer-substring (region-beginning) (region-end)))))
9619 (when (or (null txt) (string-match "\\S-" txt))
9620 (setq cpltxt
9621 (concat cpltxt "::"
9622 (condition-case nil
9623 (org-make-org-heading-search-string txt)
9624 (error "")))
9625 desc (or (and (eq et 'keyword) eok ev)
9626 (nth 4 (ignore-errors (org-heading-components)))
9627 "NONE")))))
9628 (if (string-match "::\\'" cpltxt)
9629 (setq cpltxt (substring cpltxt 0 -2)))
9630 (setq link cpltxt))))
9632 ((buffer-file-name (buffer-base-buffer))
9633 ;; Just link to this file here.
9634 (setq cpltxt (concat "file:"
9635 (abbreviate-file-name
9636 (buffer-file-name (buffer-base-buffer)))))
9637 ;; Add a context string.
9638 (when (org-xor org-context-in-file-links arg)
9639 (setq txt (if (org-region-active-p)
9640 (buffer-substring (region-beginning) (region-end))
9641 (buffer-substring (point-at-bol) (point-at-eol))))
9642 ;; Only use search option if there is some text.
9643 (when (string-match "\\S-" txt)
9644 (setq cpltxt
9645 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9646 desc "NONE")))
9647 (setq link cpltxt))
9649 ((org-called-interactively-p 'interactive)
9650 (user-error "No method for storing a link from this buffer"))
9652 (t (setq link nil)))
9654 ;; We're done setting link and desc, clean up
9655 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9656 (setq link (or link cpltxt)
9657 desc (or desc cpltxt))
9658 (cond ((equal desc "NONE") (setq desc nil))
9659 ((string-match org-bracket-link-analytic-regexp desc)
9660 (let ((d0 (match-string 3 desc))
9661 (p0 (match-string 5 desc)))
9662 (setq desc
9663 (replace-regexp-in-string
9664 org-bracket-link-regexp
9665 (concat (or p0 d0)
9666 (if (equal (length (match-string 0 desc))
9667 (length desc)) "*" "")) desc)))))
9669 ;; Return the link
9670 (if (not (and (or (org-called-interactively-p 'any)
9671 executing-kbd-macro) link))
9672 (or agenda-link (and link (org-make-link-string link desc)))
9673 (push (list link desc) org-stored-links)
9674 (message "Stored: %s" (or desc link))
9675 (when custom-id
9676 (setq link (concat "file:" (abbreviate-file-name
9677 (buffer-file-name)) "::#" custom-id))
9678 (push (list link desc) org-stored-links)))))))
9680 (defun org-store-link-props (&rest plist)
9681 "Store link properties, extract names and addresses."
9682 (let (x adr)
9683 (when (setq x (plist-get plist :from))
9684 (setq adr (mail-extract-address-components x))
9685 (setq plist (plist-put plist :fromname (car adr)))
9686 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9687 (when (setq x (plist-get plist :to))
9688 (setq adr (mail-extract-address-components x))
9689 (setq plist (plist-put plist :toname (car adr)))
9690 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9691 (let ((from (plist-get plist :from))
9692 (to (plist-get plist :to)))
9693 (when (and from to org-from-is-user-regexp)
9694 (setq plist
9695 (plist-put plist :fromto
9696 (if (string-match org-from-is-user-regexp from)
9697 (concat "to %t")
9698 (concat "from %f"))))))
9699 (setq org-store-link-plist plist))
9701 (defun org-add-link-props (&rest plist)
9702 "Add these properties to the link property list."
9703 (let (key value)
9704 (while plist
9705 (setq key (pop plist) value (pop plist))
9706 (setq org-store-link-plist
9707 (plist-put org-store-link-plist key value)))))
9709 (defun org-email-link-description (&optional fmt)
9710 "Return the description part of an email link.
9711 This takes information from `org-store-link-plist' and formats it
9712 according to FMT (default from `org-email-link-description-format')."
9713 (setq fmt (or fmt org-email-link-description-format))
9714 (let* ((p org-store-link-plist)
9715 (to (plist-get p :toaddress))
9716 (from (plist-get p :fromaddress))
9717 (table
9718 (list
9719 (cons "%c" (plist-get p :fromto))
9720 (cons "%F" (plist-get p :from))
9721 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9722 (cons "%T" (plist-get p :to))
9723 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9724 (cons "%s" (plist-get p :subject))
9725 (cons "%d" (plist-get p :date))
9726 (cons "%m" (plist-get p :message-id)))))
9727 (when (string-match "%c" fmt)
9728 ;; Check if the user wrote this message
9729 (if (and org-from-is-user-regexp from to
9730 (save-match-data (string-match org-from-is-user-regexp from)))
9731 (setq fmt (replace-match "to %t" t t fmt))
9732 (setq fmt (replace-match "from %f" t t fmt))))
9733 (org-replace-escapes fmt table)))
9735 (defun org-make-org-heading-search-string (&optional string)
9736 "Make search string for the current headline or STRING."
9737 (let ((s (or string
9738 (and (derived-mode-p 'org-mode)
9739 (save-excursion
9740 (org-back-to-heading t)
9741 (org-element-property :raw-value (org-element-at-point))))))
9742 (lines org-context-in-file-links))
9743 (or string (setq s (concat "*" s))) ; Add * for headlines
9744 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9745 (when (and string (integerp lines) (> lines 0))
9746 (let ((slines (org-split-string s "\n")))
9747 (when (< lines (length slines))
9748 (setq s (mapconcat
9749 'identity
9750 (reverse (nthcdr (- (length slines) lines)
9751 (reverse slines))) "\n")))))
9752 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9754 (defun org-make-link-string (link &optional description)
9755 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9756 (unless (string-match "\\S-" link)
9757 (error "Empty link"))
9758 (when (and description
9759 (stringp description)
9760 (not (string-match "\\S-" description)))
9761 (setq description nil))
9762 (when (stringp description)
9763 ;; Remove brackets from the description, they are fatal.
9764 (while (string-match "\\[" description)
9765 (setq description (replace-match "{" t t description)))
9766 (while (string-match "\\]" description)
9767 (setq description (replace-match "}" t t description))))
9768 (when (equal link description)
9769 ;; No description needed, it is identical
9770 (setq description nil))
9771 (when (and (not description)
9772 (not (string-match (org-image-file-name-regexp) link))
9773 (not (equal link (org-link-escape link))))
9774 (setq description (org-extract-attributes link)))
9775 (setq link
9776 (cond ((string-match (org-image-file-name-regexp) link) link)
9777 ((string-match org-link-types-re link)
9778 (concat (match-string 1 link)
9779 (org-link-escape (substring link (match-end 1)))))
9780 (t (org-link-escape link))))
9781 (concat "[[" link "]"
9782 (if description (concat "[" description "]") "")
9783 "]"))
9785 (defconst org-link-escape-chars
9786 ;;%20 %2B %3B %3D %5B %5D
9787 '(?\ ?\+ ?\; ?\= ?\[ ?\])
9788 "List of characters that should be escaped in link.
9789 This is the list that is used for internal purposes.")
9791 (defconst org-link-escape-chars-browser
9792 ;;%20 %22
9793 '(?\ ?\")
9794 "List of escapes for characters that are problematic in links.
9795 This is the list that is used before handing over to the browser.")
9797 (defun org-link-escape (text &optional table merge)
9798 "Return percent escaped representation of TEXT.
9799 TEXT is a string with the text to escape.
9800 Optional argument TABLE is a list with characters that should be
9801 escaped. When nil, `org-link-escape-chars' is used.
9802 If optional argument MERGE is set, merge TABLE into
9803 `org-link-escape-chars'."
9804 (cond
9805 ((and table merge)
9806 (mapc (lambda (defchr)
9807 (unless (member defchr table)
9808 (setq table (cons defchr table)))) org-link-escape-chars))
9809 ((null table)
9810 (setq table org-link-escape-chars)))
9811 (mapconcat
9812 (lambda (char)
9813 (if (or (member char table)
9814 (and (or (< char 32) (= char ?\%) (> char 126))
9815 org-url-hexify-p))
9816 (mapconcat (lambda (sequence-element)
9817 (format "%%%.2X" sequence-element))
9818 (or (encode-coding-char char 'utf-8)
9819 (error "Unable to percent escape character: %s"
9820 (char-to-string char))) "")
9821 (char-to-string char))) text ""))
9823 (defun org-link-escape-browser (text)
9824 (if (org-string-match-p
9825 (concat "[[:nonascii:]" org-link-escape-chars-browser "]")
9826 text)
9827 (org-link-escape text org-link-escape-chars-browser)
9828 text))
9830 (defun org-link-unescape (str)
9831 "Unhex hexified Unicode strings as returned from the JavaScript function
9832 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9833 (unless (and (null str) (string= "" str))
9834 (let ((pos 0) (case-fold-search t) unhexed)
9835 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9836 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9837 (setq str (replace-match unhexed t t str))
9838 (setq pos (+ pos (length unhexed))))))
9839 str)
9841 (defun org-link-unescape-compound (hex)
9842 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9843 Note: this function also decodes single byte encodings like
9844 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9845 (save-match-data
9846 (let* ((bytes (cdr (split-string hex "%")))
9847 (ret "")
9848 (eat 0)
9849 (sum 0))
9850 (while bytes
9851 (let* ((val (string-to-number (pop bytes) 16))
9852 (shift-xor
9853 (if (= 0 eat)
9854 (cond
9855 ((>= val 252) (cons 6 252))
9856 ((>= val 248) (cons 5 248))
9857 ((>= val 240) (cons 4 240))
9858 ((>= val 224) (cons 3 224))
9859 ((>= val 192) (cons 2 192))
9860 (t (cons 0 0)))
9861 (cons 6 128))))
9862 (if (>= val 192) (setq eat (car shift-xor)))
9863 (setq val (logxor val (cdr shift-xor)))
9864 (setq sum (+ (lsh sum (car shift-xor)) val))
9865 (if (> eat 0) (setq eat (- eat 1)))
9866 (cond
9867 ((= 0 eat) ;multi byte
9868 (setq ret (concat ret (org-char-to-string sum)))
9869 (setq sum 0))
9870 ((not bytes) ; single byte(s)
9871 (setq ret (org-link-unescape-single-byte-sequence hex))))
9872 )) ;; end (while bytes
9873 ret )))
9875 (defun org-link-unescape-single-byte-sequence (hex)
9876 "Unhexify hex-encoded single byte character sequences."
9877 (mapconcat (lambda (byte)
9878 (char-to-string (string-to-number byte 16)))
9879 (cdr (split-string hex "%")) ""))
9881 (defun org-xor (a b)
9882 "Exclusive or."
9883 (if a (not b) b))
9885 (defun org-fixup-message-id-for-http (s)
9886 "Replace special characters in a message id, so it can be used in an http query."
9887 (when (string-match "%" s)
9888 (setq s (mapconcat (lambda (c)
9889 (if (eq c ?%)
9890 "%25"
9891 (char-to-string c)))
9892 s "")))
9893 (while (string-match "<" s)
9894 (setq s (replace-match "%3C" t t s)))
9895 (while (string-match ">" s)
9896 (setq s (replace-match "%3E" t t s)))
9897 (while (string-match "@" s)
9898 (setq s (replace-match "%40" t t s)))
9901 (defun org-link-prettify (link)
9902 "Return a human-readable representation of LINK.
9903 The car of LINK must be a raw link the cdr of LINK must be either
9904 a link description or nil."
9905 (let ((desc (or (cadr link) "<no description>")))
9906 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9907 "<" (car link) ">")))
9909 ;;;###autoload
9910 (defun org-insert-link-global ()
9911 "Insert a link like Org-mode does.
9912 This command can be called in any mode to insert a link in Org-mode syntax."
9913 (interactive)
9914 (org-load-modules-maybe)
9915 (org-run-like-in-org-mode 'org-insert-link))
9917 (defun org-insert-all-links (&optional keep)
9918 "Insert all links in `org-stored-links'."
9919 (interactive "P")
9920 (let ((links (copy-sequence org-stored-links)) l)
9921 (while (setq l (if keep (pop links) (pop org-stored-links)))
9922 (insert "- ")
9923 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9924 (insert "\n"))))
9926 (defun org-link-fontify-links-to-this-file ()
9927 "Fontify links to the current file in `org-stored-links'."
9928 (let ((f (buffer-file-name)) a b)
9929 (setq a (mapcar (lambda(l)
9930 (let ((ll (car l)))
9931 (when (and (string-match "^file:\\(.+\\)::" ll)
9932 (equal f (expand-file-name (match-string 1 ll))))
9933 ll)))
9934 org-stored-links))
9935 (when (featurep 'org-id)
9936 (setq b (mapcar (lambda(l)
9937 (let ((ll (car l)))
9938 (when (and (string-match "^id:\\(.+\\)$" ll)
9939 (equal f (expand-file-name
9940 (or (org-id-find-id-file
9941 (match-string 1 ll)) ""))))
9942 ll)))
9943 org-stored-links)))
9944 (mapcar (lambda(l)
9945 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9946 (delq nil (append a b)))))
9948 (defvar org-link-links-in-this-file nil)
9949 (defun org-insert-link (&optional complete-file link-location default-description)
9950 "Insert a link. At the prompt, enter the link.
9952 Completion can be used to insert any of the link protocol prefixes like
9953 http or ftp in use.
9955 The history can be used to select a link previously stored with
9956 `org-store-link'. When the empty string is entered (i.e. if you just
9957 press RET at the prompt), the link defaults to the most recently
9958 stored link. As SPC triggers completion in the minibuffer, you need to
9959 use M-SPC or C-q SPC to force the insertion of a space character.
9961 You will also be prompted for a description, and if one is given, it will
9962 be displayed in the buffer instead of the link.
9964 If there is already a link at point, this command will allow you to edit link
9965 and description parts.
9967 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9968 be selected using completion. The path to the file will be relative to the
9969 current directory if the file is in the current directory or a subdirectory.
9970 Otherwise, the link will be the absolute path as completed in the minibuffer
9971 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9972 option `org-link-file-path-type'.
9974 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9975 the current directory or below.
9977 With three \\[universal-argument] prefixes, negate the meaning of
9978 `org-keep-stored-link-after-insertion'.
9980 If `org-make-link-description-function' is non-nil, this function will be
9981 called with the link target, and the result will be the default
9982 link description.
9984 If the LINK-LOCATION parameter is non-nil, this value will be
9985 used as the link location instead of reading one interactively.
9987 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9988 be used as the default description."
9989 (interactive "P")
9990 (let* ((wcf (current-window-configuration))
9991 (origbuf (current-buffer))
9992 (region (if (org-region-active-p)
9993 (buffer-substring (region-beginning) (region-end))))
9994 (remove (and region (list (region-beginning) (region-end))))
9995 (desc region)
9996 tmphist ; byte-compile incorrectly complains about this
9997 (link link-location)
9998 (abbrevs org-link-abbrev-alist-local)
9999 entry file all-prefixes auto-desc)
10000 (cond
10001 (link-location) ; specified by arg, just use it.
10002 ((org-in-regexp org-bracket-link-regexp 1)
10003 ;; We do have a link at point, and we are going to edit it.
10004 (setq remove (list (match-beginning 0) (match-end 0)))
10005 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
10006 (setq link (read-string "Link: "
10007 (org-link-unescape
10008 (org-match-string-no-properties 1)))))
10009 ((or (org-in-regexp org-angle-link-re)
10010 (org-in-regexp org-plain-link-re))
10011 ;; Convert to bracket link
10012 (setq remove (list (match-beginning 0) (match-end 0))
10013 link (read-string "Link: "
10014 (org-remove-angle-brackets (match-string 0)))))
10015 ((member complete-file '((4) (16)))
10016 ;; Completing read for file names.
10017 (setq link (org-file-complete-link complete-file)))
10019 ;; Read link, with completion for stored links.
10020 (org-link-fontify-links-to-this-file)
10021 (org-switch-to-buffer-other-window "*Org Links*")
10022 (with-current-buffer "*Org Links*"
10023 (erase-buffer)
10024 (insert "Insert a link.
10025 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10026 (when org-stored-links
10027 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10028 (insert (mapconcat 'org-link-prettify
10029 (reverse org-stored-links) "\n")))
10030 (goto-char (point-min)))
10031 (let ((cw (selected-window)))
10032 (select-window (get-buffer-window "*Org Links*" 'visible))
10033 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10034 (unless (pos-visible-in-window-p (point-max))
10035 (org-fit-window-to-buffer))
10036 (and (window-live-p cw) (select-window cw)))
10037 ;; Fake a link history, containing the stored links.
10038 (setq tmphist (append (mapcar 'car org-stored-links)
10039 org-insert-link-history))
10040 (setq all-prefixes (append (mapcar 'car abbrevs)
10041 (mapcar 'car org-link-abbrev-alist)
10042 org-link-types))
10043 (unwind-protect
10044 (progn
10045 (setq link
10046 (org-completing-read
10047 "Link: "
10048 (append
10049 (mapcar (lambda (x) (concat x ":"))
10050 all-prefixes)
10051 (mapcar 'car org-stored-links))
10052 nil nil nil
10053 'tmphist
10054 (caar org-stored-links)))
10055 (if (not (string-match "\\S-" link))
10056 (user-error "No link selected"))
10057 (mapc (lambda(l)
10058 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
10059 org-stored-links)
10060 (if (or (member link all-prefixes)
10061 (and (equal ":" (substring link -1))
10062 (member (substring link 0 -1) all-prefixes)
10063 (setq link (substring link 0 -1))))
10064 (setq link (with-current-buffer origbuf
10065 (org-link-try-special-completion link)))))
10066 (set-window-configuration wcf)
10067 (kill-buffer "*Org Links*"))
10068 (setq entry (assoc link org-stored-links))
10069 (or entry (push link org-insert-link-history))
10070 (setq desc (or desc (nth 1 entry)))))
10072 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10073 (not org-keep-stored-link-after-insertion))
10074 (setq org-stored-links (delq (assoc link org-stored-links)
10075 org-stored-links)))
10077 (if (and (string-match org-plain-link-re link)
10078 (not (string-match org-ts-regexp link)))
10079 ;; URL-like link, normalize the use of angular brackets.
10080 (setq link (org-remove-angle-brackets link)))
10082 ;; Check if we are linking to the current file with a search
10083 ;; option If yes, simplify the link by using only the search
10084 ;; option.
10085 (when (and buffer-file-name
10086 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10087 (let* ((path (match-string 1 link))
10088 (case-fold-search nil)
10089 (search (match-string 2 link)))
10090 (save-match-data
10091 (if (equal (file-truename buffer-file-name) (file-truename path))
10092 ;; We are linking to this same file, with a search option
10093 (setq link search)))))
10095 ;; Check if we can/should use a relative path. If yes, simplify the link
10096 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10097 (let* ((type (match-string 1 link))
10098 (path (match-string 2 link))
10099 (origpath path)
10100 (case-fold-search nil))
10101 (cond
10102 ((or (eq org-link-file-path-type 'absolute)
10103 (equal complete-file '(16)))
10104 (setq path (abbreviate-file-name (expand-file-name path))))
10105 ((eq org-link-file-path-type 'noabbrev)
10106 (setq path (expand-file-name path)))
10107 ((eq org-link-file-path-type 'relative)
10108 (setq path (file-relative-name path)))
10110 (save-match-data
10111 (if (string-match (concat "^" (regexp-quote
10112 (expand-file-name
10113 (file-name-as-directory
10114 default-directory))))
10115 (expand-file-name path))
10116 ;; We are linking a file with relative path name.
10117 (setq path (substring (expand-file-name path)
10118 (match-end 0)))
10119 (setq path (abbreviate-file-name (expand-file-name path)))))))
10120 (setq link (concat type path))
10121 (if (equal desc origpath)
10122 (setq desc path))))
10124 (if org-make-link-description-function
10125 (setq desc
10126 (or (condition-case nil
10127 (funcall org-make-link-description-function link desc)
10128 (error (progn (message "Can't get link description from `%s'"
10129 (symbol-name org-make-link-description-function))
10130 (sit-for 2) nil)))
10131 (read-string "Description: " default-description)))
10132 (if default-description (setq desc default-description)
10133 (setq desc (or (and auto-desc desc)
10134 (read-string "Description: " desc)))))
10136 (unless (string-match "\\S-" desc) (setq desc nil))
10137 (if remove (apply 'delete-region remove))
10138 (insert (org-make-link-string link desc))))
10140 (defun org-link-try-special-completion (type)
10141 "If there is completion support for link type TYPE, offer it."
10142 (let ((fun (intern (concat "org-" type "-complete-link"))))
10143 (if (functionp fun)
10144 (funcall fun)
10145 (read-string "Link (no completion support): " (concat type ":")))))
10147 (defun org-file-complete-link (&optional arg)
10148 "Create a file link using completion."
10149 (let (file link)
10150 (setq file (org-iread-file-name "File: "))
10151 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10152 (pwd1 (file-name-as-directory (abbreviate-file-name
10153 (expand-file-name ".")))))
10154 (cond
10155 ((equal arg '(16))
10156 (setq link (concat
10157 "file:"
10158 (abbreviate-file-name (expand-file-name file)))))
10159 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10160 (setq link (concat "file:" (match-string 1 file))))
10161 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10162 (expand-file-name file))
10163 (setq link (concat
10164 "file:" (match-string 1 (expand-file-name file)))))
10165 (t (setq link (concat "file:" file)))))
10166 link))
10168 (defun org-iread-file-name (&rest args)
10169 "Read-file-name using `ido-mode' speedup if available.
10170 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10171 See `read-file-name' for a description of parameters."
10172 (org-without-partial-completion
10173 (if (and org-completion-use-ido
10174 (fboundp 'ido-read-file-name)
10175 (boundp 'ido-mode) ido-mode
10176 (listp (second args)))
10177 (let ((ido-enter-matching-directory nil))
10178 (apply 'ido-read-file-name args))
10179 (apply 'read-file-name args))))
10181 (defun org-completing-read (&rest args)
10182 "Completing-read with SPACE being a normal character."
10183 (let ((enable-recursive-minibuffers t)
10184 (minibuffer-local-completion-map
10185 (copy-keymap minibuffer-local-completion-map)))
10186 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10187 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10188 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10189 (apply 'org-icompleting-read args)))
10191 (defun org-completing-read-no-i (&rest args)
10192 (let (org-completion-use-ido org-completion-use-iswitchb)
10193 (apply 'org-completing-read args)))
10195 (defun org-iswitchb-completing-read (prompt choices &rest args)
10196 "Use iswitch as a completing-read replacement to choose from choices.
10197 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10198 from."
10199 (let* ((iswitchb-use-virtual-buffers nil)
10200 (iswitchb-make-buflist-hook
10201 (lambda ()
10202 (setq iswitchb-temp-buflist choices))))
10203 (iswitchb-read-buffer prompt)))
10205 (defun org-icompleting-read (&rest args)
10206 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10207 (org-without-partial-completion
10208 (if (and org-completion-use-ido
10209 (fboundp 'ido-completing-read)
10210 (boundp 'ido-mode) ido-mode
10211 (listp (second args)))
10212 (let ((ido-enter-matching-directory nil))
10213 (apply 'ido-completing-read (concat (car args))
10214 (if (consp (car (nth 1 args)))
10215 (mapcar 'car (nth 1 args))
10216 (nth 1 args))
10217 (cddr args)))
10218 (if (and org-completion-use-iswitchb
10219 (boundp 'iswitchb-mode) iswitchb-mode
10220 (listp (second args)))
10221 (apply 'org-iswitchb-completing-read (concat (car args))
10222 (if (consp (car (nth 1 args)))
10223 (mapcar 'car (nth 1 args))
10224 (nth 1 args))
10225 (cddr args))
10226 (apply 'completing-read args)))))
10228 (defun org-extract-attributes (s)
10229 "Extract the attributes cookie from a string and set as text property."
10230 (let (a attr (start 0) key value)
10231 (save-match-data
10232 (when (string-match "{{\\([^}]+\\)}}$" s)
10233 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10234 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10235 (setq key (match-string 1 a) value (match-string 2 a)
10236 start (match-end 0)
10237 attr (plist-put attr (intern key) value))))
10238 (org-add-props s nil 'org-attr attr))
10241 ;;; Opening/following a link
10243 (defvar org-link-search-failed nil)
10245 (defvar org-open-link-functions nil
10246 "Hook for functions finding a plain text link.
10247 These functions must take a single argument, the link content.
10248 They will be called for links that look like [[link text][description]]
10249 when LINK TEXT does not have a protocol like \"http:\" and does not look
10250 like a filename (e.g. \"./blue.png\").
10252 These functions will be called *before* Org attempts to resolve the
10253 link by doing text searches in the current buffer - so if you want a
10254 link \"[[target]]\" to still find \"<<target>>\", your function should
10255 handle this as a special case.
10257 When the function does handle the link, it must return a non-nil value.
10258 If it decides that it is not responsible for this link, it must return
10259 nil to indicate that that Org-mode can continue with other options
10260 like exact and fuzzy text search.")
10262 (defun org-next-link (&optional search-backward)
10263 "Move forward to the next link.
10264 If the link is in hidden text, expose it."
10265 (interactive "P")
10266 (when (and org-link-search-failed (eq this-command last-command))
10267 (goto-char (point-min))
10268 (message "Link search wrapped back to beginning of buffer"))
10269 (setq org-link-search-failed nil)
10270 (let* ((pos (point))
10271 (ct (org-context))
10272 (a (assoc :link ct))
10273 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10274 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10275 ((looking-at org-any-link-re)
10276 ;; Don't stay stuck at link without an org-link face
10277 (forward-char (if search-backward -1 1))))
10278 (if (funcall srch-fun org-any-link-re nil t)
10279 (progn
10280 (goto-char (match-beginning 0))
10281 (if (outline-invisible-p) (org-show-context)))
10282 (goto-char pos)
10283 (setq org-link-search-failed t)
10284 (message "No further link found"))))
10286 (defun org-previous-link ()
10287 "Move backward to the previous link.
10288 If the link is in hidden text, expose it."
10289 (interactive)
10290 (funcall 'org-next-link t))
10292 (defun org-translate-link (s)
10293 "Translate a link string if a translation function has been defined."
10294 (if (and org-link-translation-function
10295 (fboundp org-link-translation-function)
10296 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10297 (progn
10298 (setq s (funcall org-link-translation-function
10299 (match-string 1 s) (match-string 2 s)))
10300 (concat (car s) ":" (cdr s)))
10303 (defun org-translate-link-from-planner (type path)
10304 "Translate a link from Emacs Planner syntax so that Org can follow it.
10305 This is still an experimental function, your mileage may vary."
10306 (cond
10307 ((member type '("http" "https" "news" "ftp"))
10308 ;; standard Internet links are the same.
10309 nil)
10310 ((and (equal type "irc") (string-match "^//" path))
10311 ;; Planner has two / at the beginning of an irc link, we have 1.
10312 ;; We should have zero, actually....
10313 (setq path (substring path 1)))
10314 ((and (equal type "lisp") (string-match "^/" path))
10315 ;; Planner has a slash, we do not.
10316 (setq type "elisp" path (substring path 1)))
10317 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10318 ;; A typical message link. Planner has the id after the final slash,
10319 ;; we separate it with a hash mark
10320 (setq path (concat (match-string 1 path) "#"
10321 (org-remove-angle-brackets (match-string 2 path))))))
10322 (cons type path))
10324 (defun org-find-file-at-mouse (ev)
10325 "Open file link or URL at mouse."
10326 (interactive "e")
10327 (mouse-set-point ev)
10328 (org-open-at-point 'in-emacs))
10330 (defun org-open-at-mouse (ev)
10331 "Open file link or URL at mouse.
10332 See the docstring of `org-open-file' for details."
10333 (interactive "e")
10334 (mouse-set-point ev)
10335 (if (eq major-mode 'org-agenda-mode)
10336 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10337 (org-open-at-point))
10339 (defvar org-window-config-before-follow-link nil
10340 "The window configuration before following a link.
10341 This is saved in case the need arises to restore it.")
10343 (defvar org-open-link-marker (make-marker)
10344 "Marker pointing to the location where `org-open-at-point; was called.")
10346 ;;;###autoload
10347 (defun org-open-at-point-global ()
10348 "Follow a link like Org-mode does.
10349 This command can be called in any mode to follow a link that has
10350 Org-mode syntax."
10351 (interactive)
10352 (org-run-like-in-org-mode 'org-open-at-point))
10354 ;;;###autoload
10355 (defun org-open-link-from-string (s &optional arg reference-buffer)
10356 "Open a link in the string S, as if it was in Org-mode."
10357 (interactive "sLink: \nP")
10358 (let ((reference-buffer (or reference-buffer (current-buffer))))
10359 (with-temp-buffer
10360 (let ((org-inhibit-startup (not reference-buffer)))
10361 (org-mode)
10362 (insert s)
10363 (goto-char (point-min))
10364 (when reference-buffer
10365 (setq org-link-abbrev-alist-local
10366 (with-current-buffer reference-buffer
10367 org-link-abbrev-alist-local)))
10368 (org-open-at-point arg reference-buffer)))))
10370 (defvar org-open-at-point-functions nil
10371 "Hook that is run when following a link at point.
10373 Functions in this hook must return t if they identify and follow
10374 a link at point. If they don't find anything interesting at point,
10375 they must return nil.")
10377 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10378 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10379 (defun org-open-at-point (&optional arg reference-buffer)
10380 "Open link at or after point.
10381 If there is no link at point, this function will search forward up to
10382 the end of the current line.
10383 Normally, files will be opened by an appropriate application. If the
10384 optional prefix argument ARG is non-nil, Emacs will visit the file.
10385 With a double prefix argument, try to open outside of Emacs, in the
10386 application the system uses for this file type."
10387 (interactive "P")
10388 ;; if in a code block, then open the block's results
10389 (unless (call-interactively #'org-babel-open-src-block-result)
10390 (org-load-modules-maybe)
10391 (move-marker org-open-link-marker (point))
10392 (setq org-window-config-before-follow-link (current-window-configuration))
10393 (org-remove-occur-highlights nil nil t)
10394 (cond
10395 ((and (org-at-heading-p)
10396 (not (org-at-timestamp-p t))
10397 (not (org-in-regexp
10398 (concat org-plain-link-re "\\|"
10399 org-bracket-link-regexp "\\|"
10400 org-angle-link-re "\\|"
10401 "[ \t]:[^ \t\n]+:[ \t]*$")))
10402 (not (get-text-property (point) 'org-linked-text)))
10403 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10404 (lk0 (car lkall))
10405 (lk (if (stringp lk0) (list lk0) lk0))
10406 (lkend (cdr lkall)))
10407 (mapcar (lambda(l)
10408 (search-forward l nil lkend)
10409 (goto-char (match-beginning 0))
10410 (org-open-at-point))
10411 lk))
10412 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10413 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10414 ((and (org-at-timestamp-p t)
10415 (not (org-in-regexp org-bracket-link-regexp)))
10416 (org-follow-timestamp-link))
10417 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10418 (not (org-in-regexp org-any-link-re)))
10419 (org-footnote-action))
10421 (let (type path link line search (pos (point)))
10422 (catch 'match
10423 (save-excursion
10424 (skip-chars-forward "^]\n\r")
10425 (when (org-in-regexp org-bracket-link-regexp 1)
10426 (setq link (org-extract-attributes
10427 (org-link-unescape (org-match-string-no-properties 1))))
10428 (while (string-match " *\n *" link)
10429 (setq link (replace-match " " t t link)))
10430 (setq link (org-link-expand-abbrev link))
10431 (cond
10432 ((or (file-name-absolute-p link)
10433 (string-match "^\\.\\.?/" link))
10434 (setq type "file" path link))
10435 ((string-match org-link-re-with-space3 link)
10436 (setq type (match-string 1 link) path (match-string 2 link)))
10437 ((string-match "^help:+\\(.+\\)" link)
10438 (setq type "help" path (match-string 1 link)))
10439 (t (setq type "thisfile" path link)))
10440 (throw 'match t)))
10442 (when (get-text-property (point) 'org-linked-text)
10443 (setq type "thisfile"
10444 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10445 (1+ (point)) (point))
10446 path (buffer-substring
10447 (or (previous-single-property-change pos 'org-linked-text)
10448 (point-min))
10449 (or (next-single-property-change pos 'org-linked-text)
10450 (point-max)))
10451 ;; Ensure we will search for a <<<radio>>> link, not
10452 ;; a simple reference like <<ref>>
10453 path (concat "<" path))
10454 (throw 'match t))
10456 (save-excursion
10457 (when (or (org-in-regexp org-angle-link-re)
10458 (let ((match (org-in-regexp org-plain-link-re)))
10459 ;; Check a plain link is not within a bracket link
10460 (and match
10461 (save-excursion
10462 (progn
10463 (goto-char (car match))
10464 (not (org-in-regexp org-bracket-link-regexp))))))
10465 (let ((line_ending (save-excursion (end-of-line) (point))))
10466 ;; We are in a line before a plain or bracket link
10467 (or (re-search-forward org-plain-link-re line_ending t)
10468 (re-search-forward org-bracket-link-regexp line_ending t))))
10469 (setq type (match-string 1)
10470 path (org-link-unescape (match-string 2)))
10471 (throw 'match t)))
10472 (save-excursion
10473 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10474 (setq type "tags"
10475 path (match-string 1))
10476 (while (string-match ":" path)
10477 (setq path (replace-match "+" t t path)))
10478 (throw 'match t)))
10479 (when (org-in-regexp "<\\([^><\n]+\\)>")
10480 (setq type "tree-match"
10481 path (match-string 1))
10482 (throw 'match t)))
10483 (unless path
10484 (user-error "No link found"))
10486 ;; switch back to reference buffer
10487 ;; needed when if called in a temporary buffer through
10488 ;; org-open-link-from-string
10489 (with-current-buffer (or reference-buffer (current-buffer))
10491 ;; Remove any trailing spaces in path
10492 (if (string-match " +\\'" path)
10493 (setq path (replace-match "" t t path)))
10494 (if (and org-link-translation-function
10495 (fboundp org-link-translation-function))
10496 ;; Check if we need to translate the link
10497 (let ((tmp (funcall org-link-translation-function type path)))
10498 (setq type (car tmp) path (cdr tmp))))
10500 (cond
10502 ((assoc type org-link-protocols)
10503 (funcall (nth 1 (assoc type org-link-protocols)) path))
10505 ((equal type "help")
10506 (let ((f-or-v (intern path)))
10507 (cond ((fboundp f-or-v)
10508 (describe-function f-or-v))
10509 ((boundp f-or-v)
10510 (describe-variable f-or-v))
10511 (t (error "Not a known function or variable")))))
10513 ((equal type "mailto")
10514 (let ((cmd (car org-link-mailto-program))
10515 (args (cdr org-link-mailto-program)) args1
10516 (address path) (subject "") a)
10517 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10518 (setq address (match-string 1 path)
10519 subject (org-link-escape (match-string 2 path))))
10520 (while args
10521 (cond
10522 ((not (stringp (car args))) (push (pop args) args1))
10523 (t (setq a (pop args))
10524 (if (string-match "%a" a)
10525 (setq a (replace-match address t t a)))
10526 (if (string-match "%s" a)
10527 (setq a (replace-match subject t t a)))
10528 (push a args1))))
10529 (apply cmd (nreverse args1))))
10531 ((member type '("http" "https" "ftp" "news"))
10532 ;; In the example of the http Org link
10533 ;; [[http://lists.gnu.org/archive/cgi-bin/namazu.cgi?idxname=emacs-orgmode&query=%252Bsubject:"Release+8.2"]]
10534 ;; to open a browser with +subject:"Release 8.2" in the
10535 ;; query field the variable `path' contains
10536 ;; [...]=%2Bsubject:"Release+8.2", `url-encode-url'
10537 ;; converts correct to [...]=%2Bsubject:%22Release+8.2%22
10538 ;; and `org-link-escape-browser' converts wrong to
10539 ;; [...]=%252Bsubject:%22Release+8.2%22.
10541 ;; `url-encode-url' is available since Emacs 24.3.1 and
10542 ;; `org-link-escape-browser' can be removed altogether
10543 ;; once Org drops support for Emacs 24.1 and 24.2.
10544 (browse-url (funcall (if (fboundp 'url-encode-url)
10545 #'url-encode-url
10546 #'org-link-escape-browser)
10547 (concat type ":" path))))
10549 ((string= type "doi")
10550 ;; See comments for type http above
10551 (browse-url (funcall (if (fboundp 'url-encode-url)
10552 #'url-encode-url
10553 #'org-link-escape-browser)
10554 (concat org-doi-server-url path))))
10556 ((member type '("message"))
10557 (browse-url (concat type ":" path)))
10559 ((string= type "tags")
10560 (org-tags-view arg path))
10562 ((string= type "tree-match")
10563 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10565 ((string= type "file")
10566 (if (string-match "::\\([0-9]+\\)\\'" path)
10567 (setq line (string-to-number (match-string 1 path))
10568 path (substring path 0 (match-beginning 0)))
10569 (if (string-match "::\\(.+\\)\\'" path)
10570 (setq search (match-string 1 path)
10571 path (substring path 0 (match-beginning 0)))))
10572 (if (string-match "[*?{]" (file-name-nondirectory path))
10573 (dired path)
10574 (org-open-file path arg line search)))
10576 ((string= type "shell")
10577 (let ((buf (generate-new-buffer "*Org Shell Output"))
10578 (cmd path))
10579 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10580 (string-match org-confirm-shell-link-not-regexp cmd))
10581 (not org-confirm-shell-link-function)
10582 (funcall org-confirm-shell-link-function
10583 (format "Execute \"%s\" in shell? "
10584 (org-add-props cmd nil
10585 'face 'org-warning))))
10586 (progn
10587 (message "Executing %s" cmd)
10588 (shell-command cmd buf)
10589 (if (featurep 'midnight)
10590 (setq clean-buffer-list-kill-buffer-names
10591 (cons buf clean-buffer-list-kill-buffer-names))))
10592 (error "Abort"))))
10594 ((string= type "elisp")
10595 (let ((cmd path))
10596 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10597 (string-match org-confirm-elisp-link-not-regexp cmd))
10598 (not org-confirm-elisp-link-function)
10599 (funcall org-confirm-elisp-link-function
10600 (format "Execute \"%s\" as elisp? "
10601 (org-add-props cmd nil
10602 'face 'org-warning))))
10603 (message "%s => %s" cmd
10604 (if (equal (string-to-char cmd) ?\()
10605 (eval (read cmd))
10606 (call-interactively (read cmd))))
10607 (error "Abort"))))
10609 ((and (string= type "thisfile")
10610 (or (run-hook-with-args-until-success
10611 'org-open-link-functions path)
10612 (and link
10613 (string-match "^id:" link)
10614 (or (featurep 'org-id) (require 'org-id))
10615 (progn
10616 (funcall (nth 1 (assoc "id" org-link-protocols))
10617 (substring path 3))
10618 t)))))
10620 ((string= type "thisfile")
10621 (if arg
10622 (switch-to-buffer-other-window
10623 (org-get-buffer-for-internal-link (current-buffer)))
10624 (org-mark-ring-push))
10625 (let ((cmd `(org-link-search
10626 ,path
10627 ,(cond ((equal arg '(4)) ''occur)
10628 ((equal arg '(16)) ''org-occur))
10629 ,pos)))
10630 (condition-case nil (let ((org-link-search-inhibit-query t))
10631 (eval cmd))
10632 (error (progn (widen) (eval cmd))))))
10634 (t (browse-url-at-point)))))))
10635 (move-marker org-open-link-marker nil)
10636 (run-hook-with-args 'org-follow-link-hook)))
10638 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10639 "Offer links in the current entry and return the selected link.
10640 If there is only one link, return it.
10641 If NTH is an integer, return the NTH link found.
10642 If ZERO is a string, check also this string for a link, and if
10643 there is one, return it."
10644 (with-current-buffer buffer
10645 (save-excursion
10646 (save-restriction
10647 (widen)
10648 (goto-char marker)
10649 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10650 "\\(" org-angle-link-re "\\)\\|"
10651 "\\(" org-plain-link-re "\\)"))
10652 (cnt ?0)
10653 (in-emacs (if (integerp nth) nil nth))
10654 have-zero end links link c)
10655 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10656 (push (match-string 0 zero) links)
10657 (setq cnt (1- cnt) have-zero t))
10658 (save-excursion
10659 (org-back-to-heading t)
10660 (setq end (save-excursion (outline-next-heading) (point)))
10661 (while (re-search-forward re end t)
10662 (push (match-string 0) links))
10663 (setq links (org-uniquify (reverse links))))
10664 (cond
10665 ((null links)
10666 (message "No links"))
10667 ((equal (length links) 1)
10668 (setq link (car links)))
10669 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10670 (setq link (nth (if have-zero nth (1- nth)) links)))
10671 (t ; we have to select a link
10672 (save-excursion
10673 (save-window-excursion
10674 (delete-other-windows)
10675 (with-output-to-temp-buffer "*Select Link*"
10676 (mapc (lambda (l)
10677 (if (not (string-match org-bracket-link-regexp l))
10678 (princ (format "[%c] %s\n" (incf cnt)
10679 (org-remove-angle-brackets l)))
10680 (if (match-end 3)
10681 (princ (format "[%c] %s (%s)\n" (incf cnt)
10682 (match-string 3 l) (match-string 1 l)))
10683 (princ (format "[%c] %s\n" (incf cnt)
10684 (match-string 1 l))))))
10685 links))
10686 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10687 (message "Select link to open, RET to open all:")
10688 (setq c (read-char-exclusive))
10689 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10690 (when (equal c ?q) (error "Abort"))
10691 (if (equal c ?\C-m)
10692 (setq link links)
10693 (setq nth (- c ?0))
10694 (if have-zero (setq nth (1+ nth)))
10695 (unless (and (integerp nth) (>= (length links) nth))
10696 (user-error "Invalid link selection"))
10697 (setq link (nth (1- nth) links)))))
10698 (cons link end))))))
10700 ;; Add special file links that specify the way of opening
10702 (org-add-link-type "file+sys" 'org-open-file-with-system)
10703 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10704 (defun org-open-file-with-system (path)
10705 "Open file at PATH using the system way of opening it."
10706 (org-open-file path 'system))
10707 (defun org-open-file-with-emacs (path)
10708 "Open file at PATH in Emacs."
10709 (org-open-file path 'emacs))
10712 ;;; File search
10714 (defvar org-create-file-search-functions nil
10715 "List of functions to construct the right search string for a file link.
10716 These functions are called in turn with point at the location to
10717 which the link should point.
10719 A function in the hook should first test if it would like to
10720 handle this file type, for example by checking the `major-mode'
10721 or the file extension. If it decides not to handle this file, it
10722 should just return nil to give other functions a chance. If it
10723 does handle the file, it must return the search string to be used
10724 when following the link. The search string will be part of the
10725 file link, given after a double colon, and `org-open-at-point'
10726 will automatically search for it. If special measures must be
10727 taken to make the search successful, another function should be
10728 added to the companion hook `org-execute-file-search-functions',
10729 which see.
10731 A function in this hook may also use `setq' to set the variable
10732 `description' to provide a suggestion for the descriptive text to
10733 be used for this link when it gets inserted into an Org-mode
10734 buffer with \\[org-insert-link].")
10736 (defvar org-execute-file-search-functions nil
10737 "List of functions to execute a file search triggered by a link.
10739 Functions added to this hook must accept a single argument, the
10740 search string that was part of the file link, the part after the
10741 double colon. The function must first check if it would like to
10742 handle this search, for example by checking the `major-mode' or
10743 the file extension. If it decides not to handle this search, it
10744 should just return nil to give other functions a chance. If it
10745 does handle the search, it must return a non-nil value to keep
10746 other functions from trying.
10748 Each function can access the current prefix argument through the
10749 variable `current-prefix-arg'. Note that a single prefix is used
10750 to force opening a link in Emacs, so it may be good to only use a
10751 numeric or double prefix to guide the search function.
10753 In case this is needed, a function in this hook can also restore
10754 the window configuration before `org-open-at-point' was called using:
10756 (set-window-configuration org-window-config-before-follow-link)")
10758 (defun org-link-search (s &optional type avoid-pos stealth)
10759 "Search for a link search option.
10760 If S is surrounded by forward slashes, it is interpreted as a
10761 regular expression. In org-mode files, this will create an `org-occur'
10762 sparse tree. In ordinary files, `occur' will be used to list matches.
10763 If the current buffer is in `dired-mode', grep will be used to search
10764 in all files. If AVOID-POS is given, ignore matches near that position.
10766 When optional argument STEALTH is non-nil, do not modify
10767 visibility around point, thus ignoring
10768 `org-show-hierarchy-above', `org-show-following-heading' and
10769 `org-show-siblings' variables."
10770 (let ((case-fold-search t)
10771 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10772 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10773 (append '(("") (" ") ("\t") ("\n"))
10774 org-emphasis-alist)
10775 "\\|") "\\)"))
10776 (pos (point))
10777 (pre nil) (post nil)
10778 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10779 (cond
10780 ;; First check if there are any special search functions
10781 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10782 ;; Now try the builtin stuff
10783 ((and (equal (string-to-char s0) ?#)
10784 (> (length s0) 1)
10785 (save-excursion
10786 (goto-char (point-min))
10787 (and
10788 (re-search-forward
10789 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10790 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10791 (setq type 'dedicated
10792 pos (match-beginning 0))))
10793 ;; There is an exact target for this
10794 (goto-char pos)
10795 (org-back-to-heading t)))
10796 ((save-excursion
10797 (goto-char (point-min))
10798 (and
10799 (re-search-forward
10800 (concat "<<" (regexp-quote s0) ">>") nil t)
10801 (setq type 'dedicated
10802 pos (match-beginning 0))))
10803 ;; There is an exact target for this
10804 (goto-char pos))
10805 ((save-excursion
10806 (goto-char (point-min))
10807 (and
10808 (re-search-forward
10809 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10810 (setq type 'dedicated pos (match-beginning 0))))
10811 ;; Found an element with a matching #+name affiliated keyword.
10812 (goto-char pos))
10813 ((and (string-match "^(\\(.*\\))$" s0)
10814 (save-excursion
10815 (goto-char (point-min))
10816 (and
10817 (re-search-forward
10818 (concat "[^[]" (regexp-quote
10819 (format org-coderef-label-format
10820 (match-string 1 s0))))
10821 nil t)
10822 (setq type 'dedicated
10823 pos (1+ (match-beginning 0))))))
10824 ;; There is a coderef target for this
10825 (goto-char pos))
10826 ((string-match "^/\\(.*\\)/$" s)
10827 ;; A regular expression
10828 (cond
10829 ((derived-mode-p 'org-mode)
10830 (org-occur (match-string 1 s)))
10831 (t (org-do-occur (match-string 1 s)))))
10832 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10833 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10834 (goto-char (point-min))
10835 (cond
10836 ((let (case-fold-search)
10837 (re-search-forward (format org-complex-heading-regexp-format
10838 (regexp-quote s))
10839 nil t))
10840 ;; OK, found a match
10841 (setq type 'dedicated)
10842 (goto-char (match-beginning 0)))
10843 ((and (not org-link-search-inhibit-query)
10844 (eq org-link-search-must-match-exact-headline 'query-to-create)
10845 (y-or-n-p "No match - create this as a new heading? "))
10846 (goto-char (point-max))
10847 (or (bolp) (newline))
10848 (insert "* " s "\n")
10849 (beginning-of-line 0))
10851 (goto-char pos)
10852 (error "No match"))))
10854 ;; A normal search string
10855 (when (equal (string-to-char s) ?*)
10856 ;; Anchor on headlines, post may include tags.
10857 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10858 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10859 s (substring s 1)))
10860 (remove-text-properties
10861 0 (length s)
10862 '(face nil mouse-face nil keymap nil fontified nil) s)
10863 ;; Make a series of regular expressions to find a match
10864 (setq words (org-split-string s "[ \n\r\t]+")
10866 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10867 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10868 "\\)" markers)
10869 re2a_ (concat "\\(" (mapconcat 'downcase words
10870 "[ \t\r\n]+") "\\)[ \t\r\n]")
10871 re2a (concat "[ \t\r\n]" re2a_)
10872 re4_ (concat "\\(" (mapconcat 'downcase words
10873 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10874 re4 (concat "[^a-zA-Z_]" re4_)
10876 re1 (concat pre re2 post)
10877 re3 (concat pre (if pre re4_ re4) post)
10878 re5 (concat pre ".*" re4)
10879 re2 (concat pre re2)
10880 re2a (concat pre (if pre re2a_ re2a))
10881 re4 (concat pre (if pre re4_ re4))
10882 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10883 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10884 re5 "\\)"))
10885 (cond
10886 ((eq type 'org-occur) (org-occur reall))
10887 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10888 (t (goto-char (point-min))
10889 (setq type 'fuzzy)
10890 (if (or (and (org-search-not-self 1 re0 nil t)
10891 (setq type 'dedicated))
10892 (org-search-not-self 1 re1 nil t)
10893 (org-search-not-self 1 re2 nil t)
10894 (org-search-not-self 1 re2a nil t)
10895 (org-search-not-self 1 re3 nil t)
10896 (org-search-not-self 1 re4 nil t)
10897 (org-search-not-self 1 re5 nil t))
10898 (goto-char (match-beginning 1))
10899 (goto-char pos)
10900 (error "No match"))))))
10901 (and (derived-mode-p 'org-mode)
10902 (not stealth)
10903 (org-show-context 'link-search))
10904 type))
10906 (defun org-search-not-self (group &rest args)
10907 "Execute `re-search-forward', but only accept matches that do not
10908 enclose the position of `org-open-link-marker'."
10909 (let ((m org-open-link-marker))
10910 (catch 'exit
10911 (while (apply 're-search-forward args)
10912 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10913 (goto-char (match-end group))
10914 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10915 (> (match-beginning 0) (marker-position m))
10916 (< (match-end 0) (marker-position m)))
10917 (save-match-data
10918 (or (not (org-in-regexp
10919 org-bracket-link-analytic-regexp 1))
10920 (not (match-end 4)) ; no description
10921 (and (<= (match-beginning 4) (point))
10922 (>= (match-end 4) (point))))))
10923 (throw 'exit (point))))))))
10925 (defun org-get-buffer-for-internal-link (buffer)
10926 "Return a buffer to be used for displaying the link target of internal links."
10927 (cond
10928 ((not org-display-internal-link-with-indirect-buffer)
10929 buffer)
10930 ((string-match "(Clone)$" (buffer-name buffer))
10931 (message "Buffer is already a clone, not making another one")
10932 ;; we also do not modify visibility in this case
10933 buffer)
10934 (t ; make a new indirect buffer for displaying the link
10935 (let* ((bn (buffer-name buffer))
10936 (ibn (concat bn "(Clone)"))
10937 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10938 (with-current-buffer ib (org-overview))
10939 ib))))
10941 (defun org-do-occur (regexp &optional cleanup)
10942 "Call the Emacs command `occur'.
10943 If CLEANUP is non-nil, remove the printout of the regular expression
10944 in the *Occur* buffer. This is useful if the regex is long and not useful
10945 to read."
10946 (occur regexp)
10947 (when cleanup
10948 (let ((cwin (selected-window)) win beg end)
10949 (when (setq win (get-buffer-window "*Occur*"))
10950 (select-window win))
10951 (goto-char (point-min))
10952 (when (re-search-forward "match[a-z]+" nil t)
10953 (setq beg (match-end 0))
10954 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10955 (setq end (1- (match-beginning 0)))))
10956 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10957 (goto-char (point-min))
10958 (select-window cwin))))
10960 ;;; The mark ring for links jumps
10962 (defvar org-mark-ring nil
10963 "Mark ring for positions before jumps in Org-mode.")
10964 (defvar org-mark-ring-last-goto nil
10965 "Last position in the mark ring used to go back.")
10966 ;; Fill and close the ring
10967 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10968 (loop for i from 1 to org-mark-ring-length do
10969 (push (make-marker) org-mark-ring))
10970 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10971 org-mark-ring)
10973 (defun org-mark-ring-push (&optional pos buffer)
10974 "Put the current position or POS into the mark ring and rotate it."
10975 (interactive)
10976 (setq pos (or pos (point)))
10977 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10978 (move-marker (car org-mark-ring)
10979 (or pos (point))
10980 (or buffer (current-buffer)))
10981 (message "%s"
10982 (substitute-command-keys
10983 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10985 (defun org-mark-ring-goto (&optional n)
10986 "Jump to the previous position in the mark ring.
10987 With prefix arg N, jump back that many stored positions. When
10988 called several times in succession, walk through the entire ring.
10989 Org-mode commands jumping to a different position in the current file,
10990 or to another Org-mode file, automatically push the old position
10991 onto the ring."
10992 (interactive "p")
10993 (let (p m)
10994 (if (eq last-command this-command)
10995 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10996 (setq p org-mark-ring))
10997 (setq org-mark-ring-last-goto p)
10998 (setq m (car p))
10999 (org-pop-to-buffer-same-window (marker-buffer m))
11000 (goto-char m)
11001 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11003 (defun org-remove-angle-brackets (s)
11004 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
11005 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
11007 (defun org-add-angle-brackets (s)
11008 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
11009 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
11011 (defun org-remove-double-quotes (s)
11012 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
11013 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
11016 ;;; Following specific links
11018 (defun org-follow-timestamp-link ()
11019 "Open an agenda view for the time-stamp date/range at point."
11020 (cond
11021 ((org-at-date-range-p t)
11022 (let ((org-agenda-start-on-weekday)
11023 (t1 (match-string 1))
11024 (t2 (match-string 2)) tt1 tt2)
11025 (setq tt1 (time-to-days (org-time-string-to-time t1))
11026 tt2 (time-to-days (org-time-string-to-time t2)))
11027 (let ((org-agenda-buffer-tmp-name
11028 (format "*Org Agenda(a:%s)"
11029 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11030 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11031 ((org-at-timestamp-p t)
11032 (let ((org-agenda-buffer-tmp-name
11033 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11034 (org-agenda-list nil (time-to-days (org-time-string-to-time
11035 (substring (match-string 1) 0 10)))
11036 1)))
11037 (t (error "This should not happen"))))
11040 ;;; Following file links
11041 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11042 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11043 (declare-function mailcap-mime-info
11044 "mailcap" (string &optional request no-decode))
11045 (defvar org-wait nil)
11046 (defun org-open-file (path &optional in-emacs line search)
11047 "Open the file at PATH.
11048 First, this expands any special file name abbreviations. Then the
11049 configuration variable `org-file-apps' is checked if it contains an
11050 entry for this file type, and if yes, the corresponding command is launched.
11052 If no application is found, Emacs simply visits the file.
11054 With optional prefix argument IN-EMACS, Emacs will visit the file.
11055 With a double \\[universal-argument] \\[universal-argument] \
11056 prefix arg, Org tries to avoid opening in Emacs
11057 and to use an external application to visit the file.
11059 Optional LINE specifies a line to go to, optional SEARCH a string
11060 to search for. If LINE or SEARCH is given, the file will be
11061 opened in Emacs, unless an entry from org-file-apps that makes
11062 use of groups in a regexp matches.
11064 If you want to change the way frames are used when following a
11065 link, please customize `org-link-frame-setup'.
11067 If the file does not exist, an error is thrown."
11068 (let* ((file (if (equal path "")
11069 buffer-file-name
11070 (substitute-in-file-name (expand-file-name path))))
11071 (file-apps (append org-file-apps (org-default-apps)))
11072 (apps (org-remove-if
11073 'org-file-apps-entry-match-against-dlink-p file-apps))
11074 (apps-dlink (org-remove-if-not
11075 'org-file-apps-entry-match-against-dlink-p file-apps))
11076 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11077 (dirp (if remp nil (file-directory-p file)))
11078 (file (if (and dirp org-open-directory-means-index-dot-org)
11079 (concat (file-name-as-directory file) "index.org")
11080 file))
11081 (a-m-a-p (assq 'auto-mode apps))
11082 (dfile (downcase file))
11083 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
11084 (link (cond ((and (eq line nil)
11085 (eq search nil))
11086 file)
11087 (line
11088 (concat file "::" (number-to-string line)))
11089 (search
11090 (concat file "::" search))))
11091 (dlink (downcase link))
11092 (old-buffer (current-buffer))
11093 (old-pos (point))
11094 (old-mode major-mode)
11095 ext cmd link-match-data)
11096 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11097 (setq ext (match-string 1 dfile))
11098 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11099 (setq ext (match-string 1 dfile))))
11100 (cond
11101 ((member in-emacs '((16) system))
11102 (setq cmd (cdr (assoc 'system apps))))
11103 (in-emacs (setq cmd 'emacs))
11105 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11106 (and dirp (cdr (assoc 'directory apps)))
11107 ; first, try matching against apps-dlink
11108 ; if we get a match here, store the match data for later
11109 (let ((match (assoc-default dlink apps-dlink
11110 'string-match)))
11111 (if match
11112 (progn (setq link-match-data (match-data))
11113 match)
11114 (progn (setq in-emacs (or in-emacs line search))
11115 nil))) ; if we have no match in apps-dlink,
11116 ; always open the file in emacs if line or search
11117 ; is given (for backwards compatibility)
11118 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11119 'string-match)
11120 (cdr (assoc ext apps))
11121 (cdr (assoc t apps))))))
11122 (when (eq cmd 'system)
11123 (setq cmd (cdr (assoc 'system apps))))
11124 (when (eq cmd 'default)
11125 (setq cmd (cdr (assoc t apps))))
11126 (when (eq cmd 'mailcap)
11127 (require 'mailcap)
11128 (mailcap-parse-mailcaps)
11129 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11130 (command (mailcap-mime-info mime-type)))
11131 (if (stringp command)
11132 (setq cmd command)
11133 (setq cmd 'emacs))))
11134 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11135 (not (file-exists-p file))
11136 (not org-open-non-existing-files))
11137 (user-error "No such file: %s" file))
11138 (cond
11139 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11140 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11141 (while (string-match "['\"]%s['\"]" cmd)
11142 (setq cmd (replace-match "%s" t t cmd)))
11143 (while (string-match "%s" cmd)
11144 (setq cmd (replace-match
11145 (save-match-data
11146 (shell-quote-argument
11147 (convert-standard-filename file)))
11148 t t cmd)))
11150 ;; Replace "%1", "%2" etc. in command with group matches from regex
11151 (save-match-data
11152 (let ((match-index 1)
11153 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11154 (set-match-data link-match-data)
11155 (while (<= match-index number-of-groups)
11156 (let ((regex (concat "%" (number-to-string match-index)))
11157 (replace-with (match-string match-index dlink)))
11158 (while (string-match regex cmd)
11159 (setq cmd (replace-match replace-with t t cmd))))
11160 (setq match-index (+ match-index 1)))))
11162 (save-window-excursion
11163 (message "Running %s...done" cmd)
11164 (start-process-shell-command cmd nil cmd)
11165 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11166 ((or (stringp cmd)
11167 (eq cmd 'emacs))
11168 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11169 (widen)
11170 (if line (progn (org-goto-line line)
11171 (if (derived-mode-p 'org-mode)
11172 (org-reveal)))
11173 (if search (org-link-search search))))
11174 ((consp cmd)
11175 (let ((file (convert-standard-filename file)))
11176 (save-match-data
11177 (set-match-data link-match-data)
11178 (eval cmd))))
11179 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11180 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11181 (or (not (equal old-buffer (current-buffer)))
11182 (not (equal old-pos (point))))
11183 (org-mark-ring-push old-pos old-buffer))))
11185 (defun org-file-apps-entry-match-against-dlink-p (entry)
11186 "This function returns non-nil if `entry' uses a regular
11187 expression which should be matched against the whole link by
11188 org-open-file.
11190 It assumes that is the case when the entry uses a regular
11191 expression which has at least one grouping construct and the
11192 action is either a lisp form or a command string containing
11193 '%1', i.e. using at least one subexpression match as a
11194 parameter."
11195 (let ((selector (car entry))
11196 (action (cdr entry)))
11197 (if (stringp selector)
11198 (and (> (regexp-opt-depth selector) 0)
11199 (or (and (stringp action)
11200 (string-match "%[0-9]" action))
11201 (consp action)))
11202 nil)))
11204 (defun org-default-apps ()
11205 "Return the default applications for this operating system."
11206 (cond
11207 ((eq system-type 'darwin)
11208 org-file-apps-defaults-macosx)
11209 ((eq system-type 'windows-nt)
11210 org-file-apps-defaults-windowsnt)
11211 (t org-file-apps-defaults-gnu)))
11213 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11214 "Convert extensions to regular expressions in the cars of LIST.
11215 Also, weed out any non-string entries, because the return value is used
11216 only for regexp matching.
11217 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11218 point to the symbol `emacs', indicating that the file should
11219 be opened in Emacs."
11220 (append
11221 (delq nil
11222 (mapcar (lambda (x)
11223 (if (not (stringp (car x)))
11225 (if (string-match "\\W" (car x))
11227 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11228 list))
11229 (if add-auto-mode
11230 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11232 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11233 (defun org-file-remote-p (file)
11234 "Test whether FILE specifies a location on a remote system.
11235 Return non-nil if the location is indeed remote.
11237 For example, the filename \"/user@host:/foo\" specifies a location
11238 on the system \"/user@host:\"."
11239 (cond ((fboundp 'file-remote-p)
11240 (file-remote-p file))
11241 ((fboundp 'tramp-handle-file-remote-p)
11242 (tramp-handle-file-remote-p file))
11243 ((and (boundp 'ange-ftp-name-format)
11244 (string-match (car ange-ftp-name-format) file))
11245 t)))
11248 ;;;; Refiling
11250 (defun org-get-org-file ()
11251 "Read a filename, with default directory `org-directory'."
11252 (let ((default (or org-default-notes-file remember-data-file)))
11253 (read-file-name (format "File name [%s]: " default)
11254 (file-name-as-directory org-directory)
11255 default)))
11257 (defun org-notes-order-reversed-p ()
11258 "Check if the current file should receive notes in reversed order."
11259 (cond
11260 ((not org-reverse-note-order) nil)
11261 ((eq t org-reverse-note-order) t)
11262 ((not (listp org-reverse-note-order)) nil)
11263 (t (catch 'exit
11264 (let ((all org-reverse-note-order)
11265 entry)
11266 (while (setq entry (pop all))
11267 (if (string-match (car entry) buffer-file-name)
11268 (throw 'exit (cdr entry))))
11269 nil)))))
11271 (defvar org-refile-target-table nil
11272 "The list of refile targets, created by `org-refile'.")
11274 (defvar org-agenda-new-buffers nil
11275 "Buffers created to visit agenda files.")
11277 (defvar org-refile-cache nil
11278 "Cache for refile targets.")
11280 (defvar org-refile-markers nil
11281 "All the markers used for caching refile locations.")
11283 (defun org-refile-marker (pos)
11284 "Get a new refile marker, but only if caching is in use."
11285 (if (not org-refile-use-cache)
11287 (let ((m (make-marker)))
11288 (move-marker m pos)
11289 (push m org-refile-markers)
11290 m)))
11292 (defun org-refile-cache-clear ()
11293 "Clear the refile cache and disable all the markers."
11294 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11295 (setq org-refile-markers nil)
11296 (setq org-refile-cache nil)
11297 (message "Refile cache has been cleared"))
11299 (defun org-refile-cache-check-set (set)
11300 "Check if all the markers in the cache still have live buffers."
11301 (let (marker)
11302 (catch 'exit
11303 (while (and set (setq marker (nth 3 (pop set))))
11304 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11305 (when (and marker (null (marker-buffer marker)))
11306 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11307 (sit-for 3)
11308 (throw 'exit nil)))
11309 t)))
11311 (defun org-refile-cache-put (set &rest identifiers)
11312 "Push the refile targets SET into the cache, under IDENTIFIERS."
11313 (let* ((key (sha1 (prin1-to-string identifiers)))
11314 (entry (assoc key org-refile-cache)))
11315 (if entry
11316 (setcdr entry set)
11317 (push (cons key set) org-refile-cache))))
11319 (defun org-refile-cache-get (&rest identifiers)
11320 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11321 (cond
11322 ((not org-refile-cache) nil)
11323 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11325 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11326 org-refile-cache))))
11327 (and set (org-refile-cache-check-set set) set)))))
11329 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11330 "Produce a table with refile targets."
11331 (let ((case-fold-search nil)
11332 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11333 (entries (or org-refile-targets '((nil . (:level . 1)))))
11334 targets tgs txt re files f desc descre fast-path-p level pos0)
11335 (message "Getting targets...")
11336 (with-current-buffer (or default-buffer (current-buffer))
11337 (while (setq entry (pop entries))
11338 (setq files (car entry) desc (cdr entry))
11339 (setq fast-path-p nil)
11340 (cond
11341 ((null files) (setq files (list (current-buffer))))
11342 ((eq files 'org-agenda-files)
11343 (setq files (org-agenda-files 'unrestricted)))
11344 ((and (symbolp files) (fboundp files))
11345 (setq files (funcall files)))
11346 ((and (symbolp files) (boundp files))
11347 (setq files (symbol-value files))))
11348 (if (stringp files) (setq files (list files)))
11349 (cond
11350 ((eq (car desc) :tag)
11351 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11352 ((eq (car desc) :todo)
11353 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11354 ((eq (car desc) :regexp)
11355 (setq descre (cdr desc)))
11356 ((eq (car desc) :level)
11357 (setq descre (concat "^\\*\\{" (number-to-string
11358 (if org-odd-levels-only
11359 (1- (* 2 (cdr desc)))
11360 (cdr desc)))
11361 "\\}[ \t]")))
11362 ((eq (car desc) :maxlevel)
11363 (setq fast-path-p t)
11364 (setq descre (concat "^\\*\\{1," (number-to-string
11365 (if org-odd-levels-only
11366 (1- (* 2 (cdr desc)))
11367 (cdr desc)))
11368 "\\}[ \t]")))
11369 (t (error "Bad refiling target description %s" desc)))
11370 (while (setq f (pop files))
11371 (with-current-buffer
11372 (if (bufferp f) f (org-get-agenda-file-buffer f))
11374 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11375 (progn
11376 (if (bufferp f) (setq f (buffer-file-name
11377 (buffer-base-buffer f))))
11378 (setq f (and f (expand-file-name f)))
11379 (if (eq org-refile-use-outline-path 'file)
11380 (push (list (file-name-nondirectory f) f nil nil) tgs))
11381 (save-excursion
11382 (save-restriction
11383 (widen)
11384 (goto-char (point-min))
11385 (while (re-search-forward descre nil t)
11386 (goto-char (setq pos0 (point-at-bol)))
11387 (catch 'next
11388 (when org-refile-target-verify-function
11389 (save-match-data
11390 (or (funcall org-refile-target-verify-function)
11391 (throw 'next t))))
11392 (when (and (looking-at org-complex-heading-regexp)
11393 (not (member (match-string 4) excluded-entries))
11394 (match-string 4))
11395 (setq level (org-reduced-level
11396 (- (match-end 1) (match-beginning 1)))
11397 txt (org-link-display-format (match-string 4))
11398 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11399 re (format org-complex-heading-regexp-format
11400 (regexp-quote (match-string 4))))
11401 (when org-refile-use-outline-path
11402 (setq txt (mapconcat
11403 'org-protect-slash
11404 (append
11405 (if (eq org-refile-use-outline-path
11406 'file)
11407 (list (file-name-nondirectory
11408 (buffer-file-name
11409 (buffer-base-buffer))))
11410 (if (eq org-refile-use-outline-path
11411 'full-file-path)
11412 (list (buffer-file-name
11413 (buffer-base-buffer)))))
11414 (org-get-outline-path fast-path-p
11415 level txt)
11416 (list txt))
11417 "/")))
11418 (push (list txt f re (org-refile-marker (point)))
11419 tgs)))
11420 (when (= (point) pos0)
11421 ;; verification function has not moved point
11422 (goto-char (point-at-eol))))))))
11423 (when org-refile-use-cache
11424 (org-refile-cache-put tgs (buffer-file-name) descre))
11425 (setq targets (append tgs targets))))))
11426 (message "Getting targets...done")
11427 (nreverse targets)))
11429 (defun org-protect-slash (s)
11430 (while (string-match "/" s)
11431 (setq s (replace-match "\\" t t s)))
11434 (defvar org-olpa (make-vector 20 nil))
11436 (defun org-get-outline-path (&optional fastp level heading)
11437 "Return the outline path to the current entry, as a list.
11439 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11440 routine which makes outline path derivations for an entire file,
11441 avoiding backtracing. Refile target collection makes use of that."
11442 (if fastp
11443 (progn
11444 (if (> level 19)
11445 (error "Outline path failure, more than 19 levels"))
11446 (loop for i from level upto 19 do
11447 (aset org-olpa i nil))
11448 (prog1
11449 (delq nil (append org-olpa nil))
11450 (aset org-olpa level heading)))
11451 (let (rtn case-fold-search)
11452 (save-excursion
11453 (save-restriction
11454 (widen)
11455 (while (org-up-heading-safe)
11456 (when (looking-at org-complex-heading-regexp)
11457 (push (org-trim
11458 (replace-regexp-in-string
11459 ;; Remove statistical/checkboxes cookies
11460 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11461 (org-match-string-no-properties 4)))
11462 rtn)))
11463 rtn)))))
11465 (defun org-format-outline-path (path &optional width prefix separator)
11466 "Format the outline path PATH for display.
11467 WIDTH is the maximum number of characters that is available.
11468 PREFIX is a prefix to be included in the returned string,
11469 such as the file name.
11470 SEPARATOR is inserted between the different parts of the path,
11471 the default is \"/\"."
11472 (setq width (or width 79))
11473 (if prefix (setq width (- width (length prefix))))
11474 (if (not path)
11475 (or prefix "")
11476 (let* ((nsteps (length path))
11477 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11478 (maxwidth (if (<= total-width width)
11479 10000 ;; everything fits
11480 ;; we need to shorten the level headings
11481 (/ (- width nsteps) nsteps)))
11482 (org-odd-levels-only nil)
11483 (n 0)
11484 (total (1+ (length prefix))))
11485 (setq maxwidth (max maxwidth 10))
11486 (concat prefix
11487 (if prefix (or separator "/"))
11488 (mapconcat
11489 (lambda (h)
11490 (setq n (1+ n))
11491 (if (and (= n nsteps) (< maxwidth 10000))
11492 (setq maxwidth (- total-width total)))
11493 (if (< (length h) maxwidth)
11494 (progn (setq total (+ total (length h) 1)) h)
11495 (setq h (substring h 0 (- maxwidth 2))
11496 total (+ total maxwidth 1))
11497 (if (string-match "[ \t]+\\'" h)
11498 (setq h (substring h 0 (match-beginning 0))))
11499 (setq h (concat h "..")))
11500 (org-add-props h nil 'face
11501 (nth (% (1- n) org-n-level-faces)
11502 org-level-faces))
11504 path (or separator "/"))))))
11506 (defun org-display-outline-path (&optional file current separator just-return-string)
11507 "Display the current outline path in the echo area.
11509 If FILE is non-nil, prepend the output with the file name.
11510 If CURRENT is non-nil, append the current heading to the output.
11511 SEPARATOR is passed through to `org-format-outline-path'. It separates
11512 the different parts of the path and defaults to \"/\".
11513 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11514 (interactive "P")
11515 (let* (case-fold-search
11516 (bfn (buffer-file-name (buffer-base-buffer)))
11517 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11518 res)
11519 (if current (setq path (append path
11520 (save-excursion
11521 (org-back-to-heading t)
11522 (if (looking-at org-complex-heading-regexp)
11523 (list (match-string 4)))))))
11524 (setq res
11525 (org-format-outline-path
11526 path
11527 (1- (frame-width))
11528 (and file bfn (concat (file-name-nondirectory bfn) separator))
11529 separator))
11530 (if just-return-string
11531 (org-no-properties res)
11532 (org-unlogged-message "%s" res))))
11534 (defvar org-refile-history nil
11535 "History for refiling operations.")
11537 (defvar org-after-refile-insert-hook nil
11538 "Hook run after `org-refile' has inserted its stuff at the new location.
11539 Note that this is still *before* the stuff will be removed from
11540 the *old* location.")
11542 (defvar org-capture-last-stored-marker)
11543 (defvar org-refile-keep nil
11544 "Non-nil means `org-refile' will copy instead of refile.")
11546 (defun org-copy ()
11547 "Like `org-refile', but copy."
11548 (interactive)
11549 (let ((org-refile-keep t))
11550 (funcall 'org-refile nil nil nil "Copy")))
11552 (defun org-refile (&optional goto default-buffer rfloc msg)
11553 "Move the entry or entries at point to another heading.
11554 The list of target headings is compiled using the information in
11555 `org-refile-targets', which see.
11557 At the target location, the entry is filed as a subitem of the target
11558 heading. Depending on `org-reverse-note-order', the new subitem will
11559 either be the first or the last subitem.
11561 If there is an active region, all entries in that region will be moved.
11562 However, the region must fulfill the requirement that the first heading
11563 is the first one sets the top-level of the moved text - at most siblings
11564 below it are allowed.
11566 With prefix arg GOTO, the command will only visit the target location
11567 and not actually move anything.
11569 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11570 go to the location where the last refiling operation has put the subtree.
11572 With a numeric prefix argument of `2', refile to the running clock.
11574 With a numeric prefix argument of `3', emulate `org-refile-keep'
11575 being set to `t' and copy to the target location, don't move it.
11576 Beware that keeping refiled entries may result in duplicated ID
11577 properties.
11579 RFLOC can be a refile location obtained in a different way.
11581 MSG is a string to replace \"Refile\" in the default prompt with
11582 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11584 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11586 If you are using target caching (see `org-refile-use-cache'),
11587 you have to clear the target cache in order to find new targets.
11588 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11589 prefix argument (`C-u C-u C-u C-c C-w')."
11591 (interactive "P")
11592 (if (member goto '(0 (64)))
11593 (org-refile-cache-clear)
11594 (let* ((actionmsg (or msg "Refile"))
11595 (cbuf (current-buffer))
11596 (regionp (org-region-active-p))
11597 (region-start (and regionp (region-beginning)))
11598 (region-end (and regionp (region-end)))
11599 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11600 (org-refile-keep (if (equal goto 3) t org-refile-keep))
11601 pos it nbuf file re level reversed)
11602 (setq last-command nil)
11603 (when regionp
11604 (goto-char region-start)
11605 (or (bolp) (goto-char (point-at-bol)))
11606 (setq region-start (point))
11607 (unless (or (org-kill-is-subtree-p
11608 (buffer-substring region-start region-end))
11609 (prog1 org-refile-active-region-within-subtree
11610 (let ((s (point-at-eol)))
11611 (org-toggle-heading)
11612 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11613 (user-error "The region is not a (sequence of) subtree(s)")))
11614 (if (equal goto '(16))
11615 (org-refile-goto-last-stored)
11616 (when (or
11617 (and (equal goto 2)
11618 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11619 (prog1
11620 (setq it (list (or org-clock-heading "running clock")
11621 (buffer-file-name
11622 (marker-buffer org-clock-hd-marker))
11624 (marker-position org-clock-hd-marker)))
11625 (setq goto nil)))
11626 (setq it (or rfloc
11627 (let (heading-text)
11628 (save-excursion
11629 (unless goto
11630 (org-back-to-heading t)
11631 (setq heading-text
11632 (nth 4 (org-heading-components))))
11634 (org-refile-get-location
11635 (cond (goto "Goto")
11636 (regionp (concat actionmsg " region to"))
11637 (t (concat actionmsg " subtree \""
11638 heading-text "\" to")))
11639 default-buffer
11640 (and (not (equal '(4) goto))
11641 org-refile-allow-creating-parent-nodes)
11642 goto))))))
11643 (setq file (nth 1 it)
11644 re (nth 2 it)
11645 pos (nth 3 it))
11646 (if (and (not goto)
11648 (equal (buffer-file-name) file)
11649 (if regionp
11650 (and (>= pos region-start)
11651 (<= pos region-end))
11652 (and (>= pos (point))
11653 (< pos (save-excursion
11654 (org-end-of-subtree t t))))))
11655 (error "Cannot refile to position inside the tree or region"))
11657 (setq nbuf (or (find-buffer-visiting file)
11658 (find-file-noselect file)))
11659 (if (and goto (not (equal goto 3)))
11660 (progn
11661 (org-pop-to-buffer-same-window nbuf)
11662 (goto-char pos)
11663 (org-show-context 'org-goto))
11664 (if regionp
11665 (progn
11666 (org-kill-new (buffer-substring region-start region-end))
11667 (org-save-markers-in-region region-start region-end))
11668 (org-copy-subtree 1 nil t))
11669 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11670 (find-file-noselect file)))
11671 (setq reversed (org-notes-order-reversed-p))
11672 (save-excursion
11673 (save-restriction
11674 (widen)
11675 (if pos
11676 (progn
11677 (goto-char pos)
11678 (looking-at org-outline-regexp)
11679 (setq level (org-get-valid-level (funcall outline-level) 1))
11680 (goto-char
11681 (if reversed
11682 (or (outline-next-heading) (point-max))
11683 (or (save-excursion (org-get-next-sibling))
11684 (org-end-of-subtree t t)
11685 (point-max)))))
11686 (setq level 1)
11687 (if (not reversed)
11688 (goto-char (point-max))
11689 (goto-char (point-min))
11690 (or (outline-next-heading) (goto-char (point-max)))))
11691 (if (not (bolp)) (newline))
11692 (org-paste-subtree level)
11693 (when org-log-refile
11694 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11695 (unless (eq org-log-refile 'note)
11696 (save-excursion (org-add-log-note))))
11697 (and org-auto-align-tags
11698 (let ((org-loop-over-headlines-in-active-region nil))
11699 (org-set-tags nil t)))
11700 (let ((bookmark-name (plist-get org-bookmark-names-plist
11701 :last-refile)))
11702 (when bookmark-name
11703 (with-demoted-errors
11704 (bookmark-set bookmark-name))))
11705 ;; If we are refiling for capture, make sure that the
11706 ;; last-capture pointers point here
11707 (when (org-bound-and-true-p org-refile-for-capture)
11708 (let ((bookmark-name (plist-get org-bookmark-names-plist
11709 :last-capture-marker)))
11710 (when bookmark-name
11711 (with-demoted-errors
11712 (bookmark-set bookmark-name))))
11713 (move-marker org-capture-last-stored-marker (point)))
11714 (if (fboundp 'deactivate-mark) (deactivate-mark))
11715 (run-hooks 'org-after-refile-insert-hook))))
11716 (unless org-refile-keep
11717 (if regionp
11718 (delete-region (point) (+ (point) (- region-end region-start)))
11719 (delete-region
11720 (and (org-back-to-heading t) (point))
11721 (min (buffer-size) (org-end-of-subtree t t) (point)))))
11722 (when (featurep 'org-inlinetask)
11723 (org-inlinetask-remove-END-maybe))
11724 (setq org-markers-to-move nil)
11725 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11727 (defun org-refile-goto-last-stored ()
11728 "Go to the location where the last refile was stored."
11729 (interactive)
11730 (bookmark-jump "org-refile-last-stored")
11731 (message "This is the location of the last refile"))
11733 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11734 no-exclude)
11735 "Prompt the user for a refile location, using PROMPT.
11736 PROMPT should not be suffixed with a colon and a space, because
11737 this function appends the default value from
11738 `org-refile-history' automatically, if that is not empty.
11739 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11740 this is used for the GOTO interface."
11741 (let ((org-refile-targets org-refile-targets)
11742 (org-refile-use-outline-path org-refile-use-outline-path)
11743 excluded-entries)
11744 (when (and (derived-mode-p 'org-mode)
11745 (not org-refile-use-cache)
11746 (not no-exclude))
11747 (org-map-tree
11748 (lambda()
11749 (setq excluded-entries
11750 (append excluded-entries (list (org-get-heading t t)))))))
11751 (setq org-refile-target-table
11752 (org-refile-get-targets default-buffer excluded-entries)))
11753 (unless org-refile-target-table
11754 (user-error "No refile targets"))
11755 (let* ((cbuf (current-buffer))
11756 (partial-completion-mode nil)
11757 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11758 (cfunc (if (and org-refile-use-outline-path
11759 org-outline-path-complete-in-steps)
11760 'org-olpath-completing-read
11761 'org-icompleting-read))
11762 (extra (if org-refile-use-outline-path "/" ""))
11763 (cbnex (concat (buffer-name) extra))
11764 (filename (and cfn (expand-file-name cfn)))
11765 (tbl (mapcar
11766 (lambda (x)
11767 (if (and (not (member org-refile-use-outline-path
11768 '(file full-file-path)))
11769 (not (equal filename (nth 1 x))))
11770 (cons (concat (car x) extra " ("
11771 (file-name-nondirectory (nth 1 x)) ")")
11772 (cdr x))
11773 (cons (concat (car x) extra) (cdr x))))
11774 org-refile-target-table))
11775 (completion-ignore-case t)
11776 cdef
11777 (prompt (concat prompt
11778 (or (and (car org-refile-history)
11779 (concat " (default " (car org-refile-history) ")"))
11780 (and (assoc cbnex tbl) (setq cdef cbnex)
11781 (concat " (default " cbnex ")"))) ": "))
11782 pa answ parent-target child parent old-hist)
11783 (setq old-hist org-refile-history)
11784 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11785 nil 'org-refile-history (or cdef (car org-refile-history))))
11786 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11787 (org-refile-check-position pa)
11788 (if pa
11789 (progn
11790 (when (or (not org-refile-history)
11791 (not (eq old-hist org-refile-history))
11792 (not (equal (car pa) (car org-refile-history))))
11793 (setq org-refile-history
11794 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11795 org-refile-history
11796 (cdr org-refile-history))))
11797 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11798 (pop org-refile-history)))
11800 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11801 (progn
11802 (setq parent (match-string 1 answ)
11803 child (match-string 2 answ))
11804 (setq parent-target (or (assoc parent tbl)
11805 (assoc (concat parent "/") tbl)))
11806 (when (and parent-target
11807 (or (eq new-nodes t)
11808 (and (eq new-nodes 'confirm)
11809 (y-or-n-p (format "Create new node \"%s\"? "
11810 child)))))
11811 (org-refile-new-child parent-target child)))
11812 (user-error "Invalid target location")))))
11814 (declare-function org-string-nw-p "org-macs" (s))
11815 (defun org-refile-check-position (refile-pointer)
11816 "Check if the refile pointer matches the headline to which it points."
11817 (let* ((file (nth 1 refile-pointer))
11818 (re (nth 2 refile-pointer))
11819 (pos (nth 3 refile-pointer))
11820 buffer)
11821 (if (and (not (markerp pos)) (not file))
11822 (if file
11823 (user-error "Please save the buffer to a file before refiling")
11824 (user-error "Please indicate a target file in the refile path"))
11825 (when (org-string-nw-p re)
11826 (setq buffer (if (markerp pos)
11827 (marker-buffer pos)
11828 (or (find-buffer-visiting file)
11829 (find-file-noselect file))))
11830 (with-current-buffer buffer
11831 (save-excursion
11832 (save-restriction
11833 (widen)
11834 (goto-char pos)
11835 (beginning-of-line 1)
11836 (unless (org-looking-at-p re)
11837 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11839 (defun org-refile-new-child (parent-target child)
11840 "Use refile target PARENT-TARGET to add new CHILD below it."
11841 (unless parent-target
11842 (error "Cannot find parent for new node"))
11843 (let ((file (nth 1 parent-target))
11844 (pos (nth 3 parent-target))
11845 level)
11846 (with-current-buffer (or (find-buffer-visiting file)
11847 (find-file-noselect file))
11848 (save-excursion
11849 (save-restriction
11850 (widen)
11851 (if pos
11852 (goto-char pos)
11853 (goto-char (point-max))
11854 (if (not (bolp)) (newline)))
11855 (when (looking-at org-outline-regexp)
11856 (setq level (funcall outline-level))
11857 (org-end-of-subtree t t))
11858 (org-back-over-empty-lines)
11859 (insert "\n" (make-string
11860 (if pos (org-get-valid-level level 1) 1) ?*)
11861 " " child "\n")
11862 (beginning-of-line 0)
11863 (list (concat (car parent-target) "/" child) file "" (point)))))))
11865 (defun org-olpath-completing-read (prompt collection &rest args)
11866 "Read an outline path like a file name."
11867 (let ((thetable collection)
11868 (org-completion-use-ido nil) ; does not work with ido.
11869 (org-completion-use-iswitchb nil)) ; or iswitchb
11870 (apply
11871 'org-icompleting-read prompt
11872 (lambda (string predicate &optional flag)
11873 (let (rtn r f (l (length string)))
11874 (cond
11875 ((eq flag nil)
11876 ;; try completion
11877 (try-completion string thetable))
11878 ((eq flag t)
11879 ;; all-completions
11880 (setq rtn (all-completions string thetable predicate))
11881 (mapcar
11882 (lambda (x)
11883 (setq r (substring x l))
11884 (if (string-match " ([^)]*)$" x)
11885 (setq f (match-string 0 x))
11886 (setq f ""))
11887 (if (string-match "/" r)
11888 (concat string (substring r 0 (match-end 0)) f)
11890 rtn))
11891 ((eq flag 'lambda)
11892 ;; exact match?
11893 (assoc string thetable)))))
11894 args)))
11896 ;;;; Dynamic blocks
11898 (defun org-find-dblock (name)
11899 "Find the first dynamic block with name NAME in the buffer.
11900 If not found, stay at current position and return nil."
11901 (let ((case-fold-search t) pos)
11902 (save-excursion
11903 (goto-char (point-min))
11904 (setq pos (and (re-search-forward
11905 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11906 (match-beginning 0))))
11907 (if pos (goto-char pos))
11908 pos))
11910 (defun org-create-dblock (plist)
11911 "Create a dynamic block section, with parameters taken from PLIST.
11912 PLIST must contain a :name entry which is used as name of the block."
11913 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11914 (end-of-line 1)
11915 (newline))
11916 (let ((col (current-column))
11917 (name (plist-get plist :name)))
11918 (insert "#+BEGIN: " name)
11919 (while plist
11920 (if (eq (car plist) :name)
11921 (setq plist (cddr plist))
11922 (insert " " (prin1-to-string (pop plist)))))
11923 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11924 (beginning-of-line -2)))
11926 (defun org-prepare-dblock ()
11927 "Prepare dynamic block for refresh.
11928 This empties the block, puts the cursor at the insert position and returns
11929 the property list including an extra property :name with the block name."
11930 (unless (looking-at org-dblock-start-re)
11931 (user-error "Not at a dynamic block"))
11932 (let* ((begdel (1+ (match-end 0)))
11933 (name (org-no-properties (match-string 1)))
11934 (params (append (list :name name)
11935 (read (concat "(" (match-string 3) ")")))))
11936 (save-excursion
11937 (beginning-of-line 1)
11938 (skip-chars-forward " \t")
11939 (setq params (plist-put params :indentation-column (current-column))))
11940 (unless (re-search-forward org-dblock-end-re nil t)
11941 (error "Dynamic block not terminated"))
11942 (setq params
11943 (append params
11944 (list :content (buffer-substring
11945 begdel (match-beginning 0)))))
11946 (delete-region begdel (match-beginning 0))
11947 (goto-char begdel)
11948 (open-line 1)
11949 params))
11951 (defun org-map-dblocks (&optional command)
11952 "Apply COMMAND to all dynamic blocks in the current buffer.
11953 If COMMAND is not given, use `org-update-dblock'."
11954 (let ((cmd (or command 'org-update-dblock)))
11955 (save-excursion
11956 (goto-char (point-min))
11957 (while (re-search-forward org-dblock-start-re nil t)
11958 (goto-char (match-beginning 0))
11959 (save-excursion
11960 (condition-case nil
11961 (funcall cmd)
11962 (error (message "Error during update of dynamic block"))))
11963 (unless (re-search-forward org-dblock-end-re nil t)
11964 (error "Dynamic block not terminated"))))))
11966 (defun org-dblock-update (&optional arg)
11967 "User command for updating dynamic blocks.
11968 Update the dynamic block at point. With prefix ARG, update all dynamic
11969 blocks in the buffer."
11970 (interactive "P")
11971 (if arg
11972 (org-update-all-dblocks)
11973 (or (looking-at org-dblock-start-re)
11974 (org-beginning-of-dblock))
11975 (org-update-dblock)))
11977 (defun org-update-dblock ()
11978 "Update the dynamic block at point.
11979 This means to empty the block, parse for parameters and then call
11980 the correct writing function."
11981 (interactive)
11982 (save-window-excursion
11983 (let* ((pos (point))
11984 (line (org-current-line))
11985 (params (org-prepare-dblock))
11986 (name (plist-get params :name))
11987 (indent (plist-get params :indentation-column))
11988 (cmd (intern (concat "org-dblock-write:" name))))
11989 (message "Updating dynamic block `%s' at line %d..." name line)
11990 (funcall cmd params)
11991 (message "Updating dynamic block `%s' at line %d...done" name line)
11992 (goto-char pos)
11993 (when (and indent (> indent 0))
11994 (setq indent (make-string indent ?\ ))
11995 (save-excursion
11996 (org-beginning-of-dblock)
11997 (forward-line 1)
11998 (while (not (looking-at org-dblock-end-re))
11999 (insert indent)
12000 (beginning-of-line 2))
12001 (when (looking-at org-dblock-end-re)
12002 (and (looking-at "[ \t]+")
12003 (replace-match ""))
12004 (insert indent)))))))
12006 (defun org-beginning-of-dblock ()
12007 "Find the beginning of the dynamic block at point.
12008 Error if there is no such block at point."
12009 (let ((pos (point))
12010 beg)
12011 (end-of-line 1)
12012 (if (and (re-search-backward org-dblock-start-re nil t)
12013 (setq beg (match-beginning 0))
12014 (re-search-forward org-dblock-end-re nil t)
12015 (> (match-end 0) pos))
12016 (goto-char beg)
12017 (goto-char pos)
12018 (error "Not in a dynamic block"))))
12020 (defun org-update-all-dblocks ()
12021 "Update all dynamic blocks in the buffer.
12022 This function can be used in a hook."
12023 (interactive)
12024 (when (derived-mode-p 'org-mode)
12025 (org-map-dblocks 'org-update-dblock)))
12028 ;;;; Completion
12030 (declare-function org-export-backend-name "org-export" (cl-x))
12031 (declare-function org-export-backend-options "org-export" (cl-x))
12032 (defun org-get-export-keywords ()
12033 "Return a list of all currently understood export keywords.
12034 Export keywords include options, block names, attributes and
12035 keywords relative to each registered export back-end."
12036 (let (keywords)
12037 (dolist (backend
12038 (org-bound-and-true-p org-export--registered-backends)
12039 (delq nil keywords))
12040 ;; Back-end name (for keywords, like #+LATEX:)
12041 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12042 (dolist (option-entry (org-export-backend-options backend))
12043 ;; Back-end options.
12044 (push (nth 1 option-entry) keywords)))))
12046 (defconst org-options-keywords
12047 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12048 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12049 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12050 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12051 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12053 (defcustom org-structure-template-alist
12054 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC" "<src lang=\"?\">\n\n</src>")
12055 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE" "<example>\n?\n</example>")
12056 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE" "<quote>\n?\n</quote>")
12057 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE" "<verse>\n?\n</verse>")
12058 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM" "<verbatim>\n?\n</verbatim>")
12059 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER" "<center>\n?\n</center>")
12060 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
12061 "<literal style=\"latex\">\n?\n</literal>")
12062 ("L" "#+LaTeX: " "<literal style=\"latex\">?</literal>")
12063 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
12064 "<literal style=\"html\">\n?\n</literal>")
12065 ("H" "#+HTML: " "<literal style=\"html\">?</literal>")
12066 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII" "")
12067 ("A" "#+ASCII: " "")
12068 ("i" "#+INDEX: ?" "#+INDEX: ?")
12069 ("I" "#+INCLUDE: %file ?"
12070 "<include file=%file markup=\"?\">"))
12071 "Structure completion elements.
12072 This is a list of abbreviation keys and values. The value gets inserted
12073 if you type `<' followed by the key and then press the completion key,
12074 usually `M-TAB'. %file will be replaced by a file name after prompting
12075 for the file using completion. The cursor will be placed at the position
12076 of the `?` in the template.
12077 There are two templates for each key, the first uses the original Org syntax,
12078 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12079 the default when the /org-mtags.el/ module has been loaded. See also the
12080 variable `org-mtags-prefer-muse-templates'."
12081 :group 'org-completion
12082 :type '(repeat
12083 (list
12084 (string :tag "Key")
12085 (string :tag "Template")
12086 (string :tag "Muse Template"))))
12088 (defun org-try-structure-completion ()
12089 "Try to complete a structure template before point.
12090 This looks for strings like \"<e\" on an otherwise empty line and
12091 expands them."
12092 (let ((l (buffer-substring (point-at-bol) (point)))
12094 (when (and (looking-at "[ \t]*$")
12095 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12096 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12097 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12098 (match-beginning 1)) a)
12099 t)))
12101 (defun org-complete-expand-structure-template (start cell)
12102 "Expand a structure template."
12103 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
12104 (rpl (nth (if musep 2 1) cell))
12105 (ind ""))
12106 (delete-region start (point))
12107 (when (string-match "\\`#\\+" rpl)
12108 (cond
12109 ((bolp))
12110 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12111 (setq ind (buffer-substring (point-at-bol) (point))))
12112 (t (newline))))
12113 (setq start (point))
12114 (if (string-match "%file" rpl)
12115 (setq rpl (replace-match
12116 (concat
12117 "\""
12118 (save-match-data
12119 (abbreviate-file-name (read-file-name "Include file: ")))
12120 "\"")
12121 t t rpl)))
12122 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12123 (concat "\n" ind)))
12124 (insert rpl)
12125 (if (re-search-backward "\\?" start t) (delete-char 1))))
12127 ;;;; TODO, DEADLINE, Comments
12129 (defun org-toggle-comment ()
12130 "Change the COMMENT state of an entry."
12131 (interactive)
12132 (save-excursion
12133 (org-back-to-heading)
12134 (let (case-fold-search)
12135 (cond
12136 ((looking-at (format org-heading-keyword-regexp-format
12137 org-comment-string))
12138 (goto-char (match-end 1))
12139 (looking-at (concat " +" org-comment-string))
12140 (replace-match "" t t)
12141 (when (eolp) (insert " ")))
12142 ((looking-at org-outline-regexp)
12143 (goto-char (match-end 0))
12144 (insert org-comment-string " "))))))
12146 (defvar org-last-todo-state-is-todo nil
12147 "This is non-nil when the last TODO state change led to a TODO state.
12148 If the last change removed the TODO tag or switched to DONE, then
12149 this is nil.")
12151 (defvar org-setting-tags nil) ; dynamically skipped
12153 (defvar org-todo-setup-filter-hook nil
12154 "Hook for functions that pre-filter todo specs.
12155 Each function takes a todo spec and returns either nil or the spec
12156 transformed into canonical form." )
12158 (defvar org-todo-get-default-hook nil
12159 "Hook for functions that get a default item for todo.
12160 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12161 nil or a string to be used for the todo mark." )
12163 (defvar org-agenda-headline-snapshot-before-repeat)
12165 (defun org-current-effective-time ()
12166 "Return current time adjusted for `org-extend-today-until' variable."
12167 (let* ((ct (org-current-time))
12168 (dct (decode-time ct))
12169 (ct1
12170 (cond
12171 (org-use-last-clock-out-time-as-effective-time
12172 (or (org-clock-get-last-clock-out-time) ct))
12173 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12174 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12175 (t ct))))
12176 ct1))
12178 (defun org-todo-yesterday (&optional arg)
12179 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12180 (interactive "P")
12181 (if (eq major-mode 'org-agenda-mode)
12182 (apply 'org-agenda-todo-yesterday arg)
12183 (let* ((hour (third (decode-time
12184 (org-current-time))))
12185 (org-extend-today-until (1+ hour)))
12186 (org-todo arg))))
12188 (defvar org-block-entry-blocking ""
12189 "First entry preventing the TODO state change.")
12191 (defun org-cancel-repeater ()
12192 "Cancel a repeater by setting its numeric value to zero."
12193 (interactive)
12194 (save-excursion
12195 (org-back-to-heading t)
12196 (let ((bound1 (point))
12197 (bound0 (save-excursion (outline-next-heading) (point))))
12198 (when (re-search-forward
12199 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12200 org-deadline-time-regexp "\\)\\|\\("
12201 org-ts-regexp "\\)")
12202 bound0 t)
12203 (if (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]" bound1 t)
12204 (replace-match "0" t nil nil 1))))))
12206 (defun org-todo (&optional arg)
12207 "Change the TODO state of an item.
12208 The state of an item is given by a keyword at the start of the heading,
12209 like
12210 *** TODO Write paper
12211 *** DONE Call mom
12213 The different keywords are specified in the variable `org-todo-keywords'.
12214 By default the available states are \"TODO\" and \"DONE\".
12215 So for this example: when the item starts with TODO, it is changed to DONE.
12216 When it starts with DONE, the DONE is removed. And when neither TODO nor
12217 DONE are present, add TODO at the beginning of the heading.
12219 With \\[universal-argument] prefix arg, use completion to determine the new \
12220 state.
12221 With numeric prefix arg, switch to that state.
12222 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12223 keywords (nextset).
12224 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12225 With a numeric prefix arg of 0, inhibit note taking for the change.
12226 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12228 When called through ELisp, arg is also interpreted in the following way:
12229 'none -> empty state
12230 \"\"(empty string) -> switch to empty state
12231 'done -> switch to DONE
12232 'nextset -> switch to the next set of keywords
12233 'previousset -> switch to the previous set of keywords
12234 \"WAITING\" -> switch to the specified keyword, but only if it
12235 really is a member of `org-todo-keywords'."
12236 (interactive "P")
12237 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12238 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12239 'region-start-level 'region))
12240 org-loop-over-headlines-in-active-region)
12241 (org-map-entries
12242 `(org-todo ,arg)
12243 org-loop-over-headlines-in-active-region
12244 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12245 (if (equal arg '(16)) (setq arg 'nextset))
12246 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12247 (let ((org-blocker-hook org-blocker-hook)
12248 commentp
12249 case-fold-search)
12250 (when (equal arg '(64))
12251 (setq arg nil org-blocker-hook nil))
12252 (when (and org-blocker-hook
12253 (or org-inhibit-blocking
12254 (org-entry-get nil "NOBLOCKING")))
12255 (setq org-blocker-hook nil))
12256 (save-excursion
12257 (catch 'exit
12258 (org-back-to-heading t)
12259 (when (looking-at (concat "^\\*+ " org-comment-string))
12260 (org-toggle-comment)
12261 (setq commentp t))
12262 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12263 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12264 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12265 (let* ((match-data (match-data))
12266 (startpos (point-at-bol))
12267 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12268 (org-log-done org-log-done)
12269 (org-log-repeat org-log-repeat)
12270 (org-todo-log-states org-todo-log-states)
12271 (org-inhibit-logging
12272 (if (equal arg 0)
12273 (progn (setq arg nil) 'note) org-inhibit-logging))
12274 (this (match-string 1))
12275 (hl-pos (match-beginning 0))
12276 (head (org-get-todo-sequence-head this))
12277 (ass (assoc head org-todo-kwd-alist))
12278 (interpret (nth 1 ass))
12279 (done-word (nth 3 ass))
12280 (final-done-word (nth 4 ass))
12281 (org-last-state (or this ""))
12282 (completion-ignore-case t)
12283 (member (member this org-todo-keywords-1))
12284 (tail (cdr member))
12285 (org-state (cond
12286 ((and org-todo-key-trigger
12287 (or (and (equal arg '(4))
12288 (eq org-use-fast-todo-selection 'prefix))
12289 (and (not arg) org-use-fast-todo-selection
12290 (not (eq org-use-fast-todo-selection
12291 'prefix)))))
12292 ;; Use fast selection
12293 (org-fast-todo-selection))
12294 ((and (equal arg '(4))
12295 (or (not org-use-fast-todo-selection)
12296 (not org-todo-key-trigger)))
12297 ;; Read a state with completion
12298 (org-icompleting-read
12299 "State: " (mapcar 'list org-todo-keywords-1)
12300 nil t))
12301 ((eq arg 'right)
12302 (if this
12303 (if tail (car tail) nil)
12304 (car org-todo-keywords-1)))
12305 ((eq arg 'left)
12306 (if (equal member org-todo-keywords-1)
12308 (if this
12309 (nth (- (length org-todo-keywords-1)
12310 (length tail) 2)
12311 org-todo-keywords-1)
12312 (org-last org-todo-keywords-1))))
12313 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12314 (setq arg nil))) ; hack to fall back to cycling
12315 (arg
12316 ;; user or caller requests a specific state
12317 (cond
12318 ((equal arg "") nil)
12319 ((eq arg 'none) nil)
12320 ((eq arg 'done) (or done-word (car org-done-keywords)))
12321 ((eq arg 'nextset)
12322 (or (car (cdr (member head org-todo-heads)))
12323 (car org-todo-heads)))
12324 ((eq arg 'previousset)
12325 (let ((org-todo-heads (reverse org-todo-heads)))
12326 (or (car (cdr (member head org-todo-heads)))
12327 (car org-todo-heads))))
12328 ((car (member arg org-todo-keywords-1)))
12329 ((stringp arg)
12330 (user-error "State `%s' not valid in this file" arg))
12331 ((nth (1- (prefix-numeric-value arg))
12332 org-todo-keywords-1))))
12333 ((null member) (or head (car org-todo-keywords-1)))
12334 ((equal this final-done-word) nil) ;; -> make empty
12335 ((null tail) nil) ;; -> first entry
12336 ((memq interpret '(type priority))
12337 (if (eq this-command last-command)
12338 (car tail)
12339 (if (> (length tail) 0)
12340 (or done-word (car org-done-keywords))
12341 nil)))
12343 (car tail))))
12344 (org-state (or
12345 (run-hook-with-args-until-success
12346 'org-todo-get-default-hook org-state org-last-state)
12347 org-state))
12348 (next (if org-state (concat " " org-state " ") " "))
12349 (change-plist (list :type 'todo-state-change :from this :to org-state
12350 :position startpos))
12351 dolog now-done-p)
12352 (when org-blocker-hook
12353 (setq org-last-todo-state-is-todo
12354 (not (member this org-done-keywords)))
12355 (unless (save-excursion
12356 (save-match-data
12357 (org-with-wide-buffer
12358 (run-hook-with-args-until-failure
12359 'org-blocker-hook change-plist))))
12360 (if (org-called-interactively-p 'interactive)
12361 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12362 this org-state org-block-entry-blocking)
12363 ;; fail silently
12364 (message "TODO state change from %s to %s blocked (by \"%s\")"
12365 this org-state org-block-entry-blocking)
12366 (throw 'exit nil))))
12367 (store-match-data match-data)
12368 (replace-match next t t)
12369 (unless (pos-visible-in-window-p hl-pos)
12370 (message "TODO state changed to %s" (org-trim next)))
12371 (unless head
12372 (setq head (org-get-todo-sequence-head org-state)
12373 ass (assoc head org-todo-kwd-alist)
12374 interpret (nth 1 ass)
12375 done-word (nth 3 ass)
12376 final-done-word (nth 4 ass)))
12377 (when (memq arg '(nextset previousset))
12378 (message "Keyword-Set %d/%d: %s"
12379 (- (length org-todo-sets) -1
12380 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12381 (length org-todo-sets)
12382 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12383 (setq org-last-todo-state-is-todo
12384 (not (member org-state org-done-keywords)))
12385 (setq now-done-p (and (member org-state org-done-keywords)
12386 (not (member this org-done-keywords))))
12387 (and logging (org-local-logging logging))
12388 (when (and (or org-todo-log-states org-log-done)
12389 (not (eq org-inhibit-logging t))
12390 (not (memq arg '(nextset previousset))))
12391 ;; we need to look at recording a time and note
12392 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12393 (nth 2 (assoc this org-todo-log-states))))
12394 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12395 (setq dolog 'time))
12396 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12397 (and org-state
12398 (member org-state org-not-done-keywords)
12399 (not (member this org-not-done-keywords))))
12400 ;; This is now a todo state and was not one before
12401 ;; If there was a CLOSED time stamp, get rid of it.
12402 (org-add-planning-info nil nil 'closed))
12403 (when (and now-done-p org-log-done)
12404 ;; It is now done, and it was not done before
12405 (org-add-planning-info 'closed (org-current-effective-time))
12406 (if (and (not dolog) (eq 'note org-log-done))
12407 (org-add-log-setup 'done org-state this 'findpos 'note)))
12408 (when (and org-state dolog)
12409 ;; This is a non-nil state, and we need to log it
12410 (org-add-log-setup 'state org-state this 'findpos dolog)))
12411 ;; Fixup tag positioning
12412 (org-todo-trigger-tag-changes org-state)
12413 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12414 (when org-provide-todo-statistics
12415 (org-update-parent-todo-statistics))
12416 (run-hooks 'org-after-todo-state-change-hook)
12417 (if (and arg (not (member org-state org-done-keywords)))
12418 (setq head (org-get-todo-sequence-head org-state)))
12419 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12420 ;; Do we need to trigger a repeat?
12421 (when now-done-p
12422 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12423 ;; This is for the agenda, take a snapshot of the headline.
12424 (save-match-data
12425 (setq org-agenda-headline-snapshot-before-repeat
12426 (org-get-heading))))
12427 (org-auto-repeat-maybe org-state))
12428 ;; Fixup cursor location if close to the keyword
12429 (if (and (outline-on-heading-p)
12430 (not (bolp))
12431 (save-excursion (beginning-of-line 1)
12432 (looking-at org-todo-line-regexp))
12433 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12434 (progn
12435 (goto-char (or (match-end 2) (match-end 1)))
12436 (and (looking-at " ") (just-one-space))))
12437 (when org-trigger-hook
12438 (save-excursion
12439 (run-hook-with-args 'org-trigger-hook change-plist)))
12440 (when commentp (org-toggle-comment))))))))
12442 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12443 "Block turning an entry into a TODO, using the hierarchy.
12444 This checks whether the current task should be blocked from state
12445 changes. Such blocking occurs when:
12447 1. The task has children which are not all in a completed state.
12449 2. A task has a parent with the property :ORDERED:, and there
12450 are siblings prior to the current task with incomplete
12451 status.
12453 3. The parent of the task is blocked because it has siblings that should
12454 be done first, or is child of a block grandparent TODO entry."
12456 (if (not org-enforce-todo-dependencies)
12457 t ; if locally turned off don't block
12458 (catch 'dont-block
12459 ;; If this is not a todo state change, or if this entry is already DONE,
12460 ;; do not block
12461 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12462 (member (plist-get change-plist :from)
12463 (cons 'done org-done-keywords))
12464 (member (plist-get change-plist :to)
12465 (cons 'todo org-not-done-keywords))
12466 (not (plist-get change-plist :to)))
12467 (throw 'dont-block t))
12468 ;; If this task has children, and any are undone, it's blocked
12469 (save-excursion
12470 (org-back-to-heading t)
12471 (let ((this-level (funcall outline-level)))
12472 (outline-next-heading)
12473 (let ((child-level (funcall outline-level)))
12474 (while (and (not (eobp))
12475 (> child-level this-level))
12476 ;; this todo has children, check whether they are all
12477 ;; completed
12478 (if (and (not (org-entry-is-done-p))
12479 (org-entry-is-todo-p))
12480 (progn (setq org-block-entry-blocking (org-get-heading))
12481 (throw 'dont-block nil)))
12482 (outline-next-heading)
12483 (setq child-level (funcall outline-level))))))
12484 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12485 ;; any previous siblings are undone, it's blocked
12486 (save-excursion
12487 (org-back-to-heading t)
12488 (let* ((pos (point))
12489 (parent-pos (and (org-up-heading-safe) (point))))
12490 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12491 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12492 (forward-line 1)
12493 (re-search-forward org-not-done-heading-regexp pos t))
12494 (setq org-block-entry-blocking (match-string 0))
12495 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12496 ;; Search further up the hierarchy, to see if an ancestor is blocked
12497 (while t
12498 (goto-char parent-pos)
12499 (if (not (looking-at org-not-done-heading-regexp))
12500 (throw 'dont-block t)) ; do not block, parent is not a TODO
12501 (setq pos (point))
12502 (setq parent-pos (and (org-up-heading-safe) (point)))
12503 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12504 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12505 (forward-line 1)
12506 (re-search-forward org-not-done-heading-regexp pos t)
12507 (setq org-block-entry-blocking (org-get-heading)))
12508 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12510 (defcustom org-track-ordered-property-with-tag nil
12511 "Should the ORDERED property also be shown as a tag?
12512 The ORDERED property decides if an entry should require subtasks to be
12513 completed in sequence. Since a property is not very visible, setting
12514 this option means that toggling the ORDERED property with the command
12515 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12516 not relevant for the behavior, but it makes things more visible.
12518 Note that toggling the tag with tags commands will not change the property
12519 and therefore not influence behavior!
12521 This can be t, meaning the tag ORDERED should be used, It can also be a
12522 string to select a different tag for this task."
12523 :group 'org-todo
12524 :type '(choice
12525 (const :tag "No tracking" nil)
12526 (const :tag "Track with ORDERED tag" t)
12527 (string :tag "Use other tag")))
12529 (defun org-toggle-ordered-property ()
12530 "Toggle the ORDERED property of the current entry.
12531 For better visibility, you can track the value of this property with a tag.
12532 See variable `org-track-ordered-property-with-tag'."
12533 (interactive)
12534 (let* ((t1 org-track-ordered-property-with-tag)
12535 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12536 (save-excursion
12537 (org-back-to-heading)
12538 (if (org-entry-get nil "ORDERED")
12539 (progn
12540 (org-delete-property "ORDERED")
12541 (and tag (org-toggle-tag tag 'off))
12542 (message "Subtasks can be completed in arbitrary order"))
12543 (org-entry-put nil "ORDERED" "t")
12544 (and tag (org-toggle-tag tag 'on))
12545 (message "Subtasks must be completed in sequence")))))
12547 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12548 (defun org-block-todo-from-checkboxes (change-plist)
12549 "Block turning an entry into a TODO, using checkboxes.
12550 This checks whether the current task should be blocked from state
12551 changes because there are unchecked boxes in this entry."
12552 (if (not org-enforce-todo-checkbox-dependencies)
12553 t ; if locally turned off don't block
12554 (catch 'dont-block
12555 ;; If this is not a todo state change, or if this entry is already DONE,
12556 ;; do not block
12557 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12558 (member (plist-get change-plist :from)
12559 (cons 'done org-done-keywords))
12560 (member (plist-get change-plist :to)
12561 (cons 'todo org-not-done-keywords))
12562 (not (plist-get change-plist :to)))
12563 (throw 'dont-block t))
12564 ;; If this task has checkboxes that are not checked, it's blocked
12565 (save-excursion
12566 (org-back-to-heading t)
12567 (let ((beg (point)) end)
12568 (outline-next-heading)
12569 (setq end (point))
12570 (goto-char beg)
12571 (if (org-list-search-forward
12572 (concat (org-item-beginning-re)
12573 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12574 "\\[[- ]\\]")
12575 end t)
12576 (progn
12577 (if (boundp 'org-blocked-by-checkboxes)
12578 (setq org-blocked-by-checkboxes t))
12579 (throw 'dont-block nil)))))
12580 t))) ; do not block
12582 (defun org-entry-blocked-p ()
12583 "Is the current entry blocked?"
12584 (org-with-silent-modifications
12585 (if (org-entry-get nil "NOBLOCKING")
12586 nil ;; Never block this entry
12587 (not (run-hook-with-args-until-failure
12588 'org-blocker-hook
12589 (list :type 'todo-state-change
12590 :position (point)
12591 :from 'todo
12592 :to 'done))))))
12594 (defun org-update-statistics-cookies (all)
12595 "Update the statistics cookie, either from TODO or from checkboxes.
12596 This should be called with the cursor in a line with a statistics cookie."
12597 (interactive "P")
12598 (if all
12599 (progn
12600 (org-update-checkbox-count 'all)
12601 (org-map-entries 'org-update-parent-todo-statistics))
12602 (if (not (org-at-heading-p))
12603 (org-update-checkbox-count)
12604 (let ((pos (point-marker))
12605 end l1 l2)
12606 (ignore-errors (org-back-to-heading t))
12607 (if (not (org-at-heading-p))
12608 (org-update-checkbox-count)
12609 (setq l1 (org-outline-level))
12610 (setq end (save-excursion
12611 (outline-next-heading)
12612 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12613 (point)))
12614 (if (and (save-excursion
12615 (re-search-forward
12616 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12617 (not (save-excursion (re-search-forward
12618 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12619 (org-update-checkbox-count)
12620 (if (and l2 (> l2 l1))
12621 (progn
12622 (goto-char end)
12623 (org-update-parent-todo-statistics))
12624 (goto-char pos)
12625 (beginning-of-line 1)
12626 (while (re-search-forward
12627 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12628 (point-at-eol) t)
12629 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12630 (goto-char pos)
12631 (move-marker pos nil)))))
12633 (defvar org-entry-property-inherited-from) ;; defined below
12634 (defun org-update-parent-todo-statistics ()
12635 "Update any statistics cookie in the parent of the current headline.
12636 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12637 the entire subtree and this will travel up the hierarchy and update
12638 statistics everywhere."
12639 (let* ((prop (save-excursion (org-up-heading-safe)
12640 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12641 (recursive (or (not org-hierarchical-todo-statistics)
12642 (and prop (string-match "\\<recursive\\>" prop))))
12643 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12645 (first t)
12646 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12647 level ltoggle l1 new ndel
12648 (cnt-all 0) (cnt-done 0) is-percent kwd
12649 checkbox-beg ov ovs ove cookie-present)
12650 (catch 'exit
12651 (save-excursion
12652 (beginning-of-line 1)
12653 (setq ltoggle (funcall outline-level))
12654 ;; Three situations are to consider:
12656 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12657 ;; to the top-level ancestor on the headline;
12659 ;; 2. If parent has "recursive" property, repeat up to the
12660 ;; headline setting that property, taking inheritance into
12661 ;; account;
12663 ;; 3. Else, move up to direct parent and proceed only once.
12664 (while (and (setq level (org-up-heading-safe))
12665 (or recursive first)
12666 (>= (point) lim))
12667 (setq first nil cookie-present nil)
12668 (unless (and level
12669 (not (string-match
12670 "\\<checkbox\\>"
12671 (downcase (or (org-entry-get nil "COOKIE_DATA")
12672 "")))))
12673 (throw 'exit nil))
12674 (while (re-search-forward box-re (point-at-eol) t)
12675 (setq cnt-all 0 cnt-done 0 cookie-present t)
12676 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12677 (save-match-data
12678 (unless (outline-next-heading) (throw 'exit nil))
12679 (while (and (looking-at org-complex-heading-regexp)
12680 (> (setq l1 (length (match-string 1))) level))
12681 (setq kwd (and (or recursive (= l1 ltoggle))
12682 (match-string 2)))
12683 (if (or (eq org-provide-todo-statistics 'all-headlines)
12684 (and (listp org-provide-todo-statistics)
12685 (or (member kwd org-provide-todo-statistics)
12686 (member kwd org-done-keywords))))
12687 (setq cnt-all (1+ cnt-all))
12688 (if (eq org-provide-todo-statistics t)
12689 (and kwd (setq cnt-all (1+ cnt-all)))))
12690 (and (member kwd org-done-keywords)
12691 (setq cnt-done (1+ cnt-done)))
12692 (outline-next-heading)))
12693 (setq new
12694 (if is-percent
12695 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12696 (format "[%d/%d]" cnt-done cnt-all))
12697 ndel (- (match-end 0) checkbox-beg))
12698 ;; handle overlays when updating cookie from column view
12699 (when (setq ov (car (overlays-at checkbox-beg)))
12700 (setq ovs (overlay-start ov) ove (overlay-end ov))
12701 (delete-overlay ov))
12702 (goto-char checkbox-beg)
12703 (insert new)
12704 (delete-region (point) (+ (point) ndel))
12705 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12706 (when ov (move-overlay ov ovs ove)))
12707 (when cookie-present
12708 (run-hook-with-args 'org-after-todo-statistics-hook
12709 cnt-done (- cnt-all cnt-done))))))
12710 (run-hooks 'org-todo-statistics-hook)))
12712 (defvar org-after-todo-statistics-hook nil
12713 "Hook that is called after a TODO statistics cookie has been updated.
12714 Each function is called with two arguments: the number of not-done entries
12715 and the number of done entries.
12717 For example, the following function, when added to this hook, will switch
12718 an entry to DONE when all children are done, and back to TODO when new
12719 entries are set to a TODO status. Note that this hook is only called
12720 when there is a statistics cookie in the headline!
12722 (defun org-summary-todo (n-done n-not-done)
12723 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12724 (let (org-log-done org-log-states) ; turn off logging
12725 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12728 (defvar org-todo-statistics-hook nil
12729 "Hook that is run whenever Org thinks TODO statistics should be updated.
12730 This hook runs even if there is no statistics cookie present, in which case
12731 `org-after-todo-statistics-hook' would not run.")
12733 (defun org-todo-trigger-tag-changes (state)
12734 "Apply the changes defined in `org-todo-state-tags-triggers'."
12735 (let ((l org-todo-state-tags-triggers)
12736 changes)
12737 (when (or (not state) (equal state ""))
12738 (setq changes (append changes (cdr (assoc "" l)))))
12739 (when (and (stringp state) (> (length state) 0))
12740 (setq changes (append changes (cdr (assoc state l)))))
12741 (when (member state org-not-done-keywords)
12742 (setq changes (append changes (cdr (assoc 'todo l)))))
12743 (when (member state org-done-keywords)
12744 (setq changes (append changes (cdr (assoc 'done l)))))
12745 (dolist (c changes)
12746 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12748 (defun org-local-logging (value)
12749 "Get logging settings from a property VALUE."
12750 (let* (words w a)
12751 ;; directly set the variables, they are already local.
12752 (setq org-log-done nil
12753 org-log-repeat nil
12754 org-todo-log-states nil)
12755 (setq words (org-split-string value))
12756 (while (setq w (pop words))
12757 (cond
12758 ((setq a (assoc w org-startup-options))
12759 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12760 (set (nth 1 a) (nth 2 a))))
12761 ((setq a (org-extract-log-state-settings w))
12762 (and (member (car a) org-todo-keywords-1)
12763 (push a org-todo-log-states)))))))
12765 (defun org-get-todo-sequence-head (kwd)
12766 "Return the head of the TODO sequence to which KWD belongs.
12767 If KWD is not set, check if there is a text property remembering the
12768 right sequence."
12769 (let (p)
12770 (cond
12771 ((not kwd)
12772 (or (get-text-property (point-at-bol) 'org-todo-head)
12773 (progn
12774 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12775 nil (point-at-eol)))
12776 (get-text-property p 'org-todo-head))))
12777 ((not (member kwd org-todo-keywords-1))
12778 (car org-todo-keywords-1))
12779 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12781 (defun org-fast-todo-selection ()
12782 "Fast TODO keyword selection with single keys.
12783 Returns the new TODO keyword, or nil if no state change should occur."
12784 (let* ((fulltable org-todo-key-alist)
12785 (done-keywords org-done-keywords) ;; needed for the faces.
12786 (maxlen (apply 'max (mapcar
12787 (lambda (x)
12788 (if (stringp (car x)) (string-width (car x)) 0))
12789 fulltable)))
12790 (expert nil)
12791 (fwidth (+ maxlen 3 1 3))
12792 (ncol (/ (- (window-width) 4) fwidth))
12793 tg cnt e c tbl
12794 groups ingroup)
12795 (save-excursion
12796 (save-window-excursion
12797 (if expert
12798 (set-buffer (get-buffer-create " *Org todo*"))
12799 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12800 (erase-buffer)
12801 (org-set-local 'org-done-keywords done-keywords)
12802 (setq tbl fulltable cnt 0)
12803 (while (setq e (pop tbl))
12804 (cond
12805 ((equal e '(:startgroup))
12806 (push '() groups) (setq ingroup t)
12807 (when (not (= cnt 0))
12808 (setq cnt 0)
12809 (insert "\n"))
12810 (insert "{ "))
12811 ((equal e '(:endgroup))
12812 (setq ingroup nil cnt 0)
12813 (insert "}\n"))
12814 ((equal e '(:newline))
12815 (when (not (= cnt 0))
12816 (setq cnt 0)
12817 (insert "\n")
12818 (setq e (car tbl))
12819 (while (equal (car tbl) '(:newline))
12820 (insert "\n")
12821 (setq tbl (cdr tbl)))))
12823 (setq tg (car e) c (cdr e))
12824 (if ingroup (push tg (car groups)))
12825 (setq tg (org-add-props tg nil 'face
12826 (org-get-todo-face tg)))
12827 (if (and (= cnt 0) (not ingroup)) (insert " "))
12828 (insert "[" c "] " tg (make-string
12829 (- fwidth 4 (length tg)) ?\ ))
12830 (when (= (setq cnt (1+ cnt)) ncol)
12831 (insert "\n")
12832 (if ingroup (insert " "))
12833 (setq cnt 0)))))
12834 (insert "\n")
12835 (goto-char (point-min))
12836 (if (not expert) (org-fit-window-to-buffer))
12837 (message "[a-z..]:Set [SPC]:clear")
12838 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12839 (cond
12840 ((or (= c ?\C-g)
12841 (and (= c ?q) (not (rassoc c fulltable))))
12842 (setq quit-flag t))
12843 ((= c ?\ ) nil)
12844 ((setq e (rassoc c fulltable) tg (car e))
12846 (t (setq quit-flag t)))))))
12848 (defun org-entry-is-todo-p ()
12849 (member (org-get-todo-state) org-not-done-keywords))
12851 (defun org-entry-is-done-p ()
12852 (member (org-get-todo-state) org-done-keywords))
12854 (defun org-get-todo-state ()
12855 "Return the TODO keyword of the current subtree."
12856 (save-excursion
12857 (org-back-to-heading t)
12858 (and (looking-at org-todo-line-regexp)
12859 (match-end 2)
12860 (match-string 2))))
12862 (defun org-at-date-range-p (&optional inactive-ok)
12863 "Is the cursor inside a date range?"
12864 (interactive)
12865 (save-excursion
12866 (catch 'exit
12867 (let ((pos (point)))
12868 (skip-chars-backward "^[<\r\n")
12869 (skip-chars-backward "<[")
12870 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12871 (>= (match-end 0) pos)
12872 (throw 'exit t))
12873 (skip-chars-backward "^<[\r\n")
12874 (skip-chars-backward "<[")
12875 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12876 (>= (match-end 0) pos)
12877 (throw 'exit t)))
12878 nil)))
12880 (defun org-get-repeat (&optional tagline)
12881 "Check if there is a deadline/schedule with repeater in this entry."
12882 (save-match-data
12883 (save-excursion
12884 (org-back-to-heading t)
12885 (and (re-search-forward (if tagline
12886 (concat tagline "\\s-*" org-repeat-re)
12887 org-repeat-re)
12888 (org-entry-end-position) t)
12889 (match-string-no-properties 1)))))
12891 (defvar org-last-changed-timestamp)
12892 (defvar org-last-inserted-timestamp)
12893 (defvar org-log-post-message)
12894 (defvar org-log-note-purpose)
12895 (defvar org-log-note-how)
12896 (defvar org-log-note-extra)
12897 (defun org-auto-repeat-maybe (done-word)
12898 "Check if the current headline contains a repeated deadline/schedule.
12899 If yes, set TODO state back to what it was and change the base date
12900 of repeating deadline/scheduled time stamps to new date.
12901 This function is run automatically after each state change to a DONE state."
12902 ;; last-state is dynamically scoped into this function
12903 (let* ((repeat (org-get-repeat))
12904 (aa (assoc org-last-state org-todo-kwd-alist))
12905 (interpret (nth 1 aa))
12906 (head (nth 2 aa))
12907 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12908 (msg "Entry repeats: ")
12909 (org-log-done nil)
12910 (org-todo-log-states nil)
12911 re type n what ts time to-state)
12912 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
12913 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12914 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12915 org-todo-repeat-to-state))
12916 (unless (and to-state (member to-state org-todo-keywords-1))
12917 (setq to-state (if (eq interpret 'type) org-last-state head)))
12918 (org-todo to-state)
12919 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12920 (org-entry-put nil "LAST_REPEAT" (format-time-string
12921 (org-time-stamp-format t t))))
12922 (when org-log-repeat
12923 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12924 (memq 'org-add-log-note post-command-hook))
12925 ;; OK, we are already setup for some record
12926 (if (eq org-log-repeat 'note)
12927 ;; make sure we take a note, not only a time stamp
12928 (setq org-log-note-how 'note))
12929 ;; Set up for taking a record
12930 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12931 org-last-state
12932 'findpos org-log-repeat)))
12933 (org-back-to-heading t)
12934 (org-add-planning-info nil nil 'closed)
12935 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12936 org-deadline-time-regexp "\\)\\|\\("
12937 org-ts-regexp "\\)"))
12938 (while (re-search-forward
12939 re (save-excursion (outline-next-heading) (point)) t)
12940 (setq type (if (match-end 1) org-scheduled-string
12941 (if (match-end 3) org-deadline-string "Plain:"))
12942 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12943 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12944 (setq n (string-to-number (match-string 2 ts))
12945 what (match-string 3 ts))
12946 (if (equal what "w") (setq n (* n 7) what "d"))
12947 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12948 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12949 ;; Preparation, see if we need to modify the start date for the change
12950 (when (match-end 1)
12951 (setq time (save-match-data (org-time-string-to-time ts)))
12952 (cond
12953 ((equal (match-string 1 ts) ".")
12954 ;; Shift starting date to today
12955 (org-timestamp-change
12956 (- (org-today) (time-to-days time))
12957 'day))
12958 ((equal (match-string 1 ts) "+")
12959 (let ((nshiftmax 10) (nshift 0))
12960 (while (or (= nshift 0)
12961 (<= (time-to-days time)
12962 (time-to-days (current-time))))
12963 (when (= (incf nshift) nshiftmax)
12964 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12965 (error "Abort")))
12966 (org-timestamp-change n (cdr (assoc what whata)))
12967 (org-at-timestamp-p t)
12968 (setq ts (match-string 1))
12969 (setq time (save-match-data (org-time-string-to-time ts)))))
12970 (org-timestamp-change (- n) (cdr (assoc what whata)))
12971 ;; rematch, so that we have everything in place for the real shift
12972 (org-at-timestamp-p t)
12973 (setq ts (match-string 1))
12974 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12975 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12976 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12977 (setq org-log-post-message msg)
12978 (message "%s" msg))))
12980 (defun org-show-todo-tree (arg)
12981 "Make a compact tree which shows all headlines marked with TODO.
12982 The tree will show the lines where the regexp matches, and all higher
12983 headlines above the match.
12984 With a \\[universal-argument] prefix, prompt for a regexp to match.
12985 With a numeric prefix N, construct a sparse tree for the Nth element
12986 of `org-todo-keywords-1'."
12987 (interactive "P")
12988 (let ((case-fold-search nil)
12989 (kwd-re
12990 (cond ((null arg) org-not-done-regexp)
12991 ((equal arg '(4))
12992 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12993 (mapcar 'list org-todo-keywords-1))))
12994 (concat "\\("
12995 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12996 "\\)\\>")))
12997 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12998 (regexp-quote (nth (1- (prefix-numeric-value arg))
12999 org-todo-keywords-1)))
13000 (t (user-error "Invalid prefix argument: %s" arg)))))
13001 (message "%d TODO entries found"
13002 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13004 (defun org-deadline (arg &optional time)
13005 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13006 With one universal prefix argument, remove any deadline from the item.
13007 With two universal prefix arguments, prompt for a warning delay.
13008 With argument TIME, set the deadline at the corresponding date. TIME
13009 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13010 (interactive "P")
13011 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13012 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13013 'region-start-level 'region))
13014 org-loop-over-headlines-in-active-region)
13015 (org-map-entries
13016 `(org-deadline ',arg ,time)
13017 org-loop-over-headlines-in-active-region
13018 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13019 (let* ((old-date (org-entry-get nil "DEADLINE"))
13020 (old-date-time (if old-date (org-time-string-to-time old-date)))
13021 (repeater (and old-date
13022 (string-match
13023 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13024 old-date)
13025 (match-string 1 old-date))))
13026 (cond
13027 ((equal arg '(4))
13028 (when (and old-date org-log-redeadline)
13029 (org-add-log-setup 'deldeadline nil old-date 'findpos
13030 org-log-redeadline))
13031 (org-remove-timestamp-with-keyword org-deadline-string)
13032 (message "Item no longer has a deadline."))
13033 ((equal arg '(16))
13034 (save-excursion
13035 (org-back-to-heading t)
13036 (if (re-search-forward
13037 org-deadline-time-regexp
13038 (save-excursion (outline-next-heading) (point)) t)
13039 (let* ((rpl0 (match-string 1))
13040 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13041 (replace-match
13042 (concat org-deadline-string
13043 " <" rpl
13044 (format " -%dd"
13045 (abs
13046 (- (time-to-days
13047 (save-match-data
13048 (org-read-date nil t nil "Warn starting from" old-date-time)))
13049 (time-to-days old-date-time))))
13050 ">") t t))
13051 (user-error "No deadline information to update"))))
13053 (org-add-planning-info 'deadline time 'closed)
13054 (when (and old-date org-log-redeadline
13055 (not (equal old-date
13056 (substring org-last-inserted-timestamp 1 -1))))
13057 (org-add-log-setup 'redeadline nil old-date 'findpos
13058 org-log-redeadline))
13059 (when repeater
13060 (save-excursion
13061 (org-back-to-heading t)
13062 (when (re-search-forward (concat org-deadline-string " "
13063 org-last-inserted-timestamp)
13064 (save-excursion
13065 (outline-next-heading) (point)) t)
13066 (goto-char (1- (match-end 0)))
13067 (insert " " repeater)
13068 (setq org-last-inserted-timestamp
13069 (concat (substring org-last-inserted-timestamp 0 -1)
13070 " " repeater
13071 (substring org-last-inserted-timestamp -1))))))
13072 (message "Deadline on %s" org-last-inserted-timestamp))))))
13074 (defun org-schedule (arg &optional time)
13075 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13076 With one universal prefix argument, remove any scheduling date from the item.
13077 With two universal prefix arguments, prompt for a delay cookie.
13078 With argument TIME, scheduled at the corresponding date. TIME can
13079 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13080 (interactive "P")
13081 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13082 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13083 'region-start-level 'region))
13084 org-loop-over-headlines-in-active-region)
13085 (org-map-entries
13086 `(org-schedule ',arg ,time)
13087 org-loop-over-headlines-in-active-region
13088 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13089 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13090 (old-date-time (if old-date (org-time-string-to-time old-date)))
13091 (repeater (and old-date
13092 (string-match
13093 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13094 old-date)
13095 (match-string 1 old-date))))
13096 (cond
13097 ((equal arg '(4))
13098 (progn
13099 (when (and old-date org-log-reschedule)
13100 (org-add-log-setup 'delschedule nil old-date 'findpos
13101 org-log-reschedule))
13102 (org-remove-timestamp-with-keyword org-scheduled-string)
13103 (message "Item is no longer scheduled.")))
13104 ((equal arg '(16))
13105 (save-excursion
13106 (org-back-to-heading t)
13107 (if (re-search-forward
13108 org-scheduled-time-regexp
13109 (save-excursion (outline-next-heading) (point)) t)
13110 (let* ((rpl0 (match-string 1))
13111 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13112 (replace-match
13113 (concat org-scheduled-string
13114 " <" rpl
13115 (format " -%dd"
13116 (abs
13117 (- (time-to-days
13118 (save-match-data
13119 (org-read-date nil t nil "Delay until" old-date-time)))
13120 (time-to-days old-date-time))))
13121 ">") t t))
13122 (user-error "No scheduled information to update"))))
13124 (org-add-planning-info 'scheduled time 'closed)
13125 (when (and old-date org-log-reschedule
13126 (not (equal old-date
13127 (substring org-last-inserted-timestamp 1 -1))))
13128 (org-add-log-setup 'reschedule nil old-date 'findpos
13129 org-log-reschedule))
13130 (when repeater
13131 (save-excursion
13132 (org-back-to-heading t)
13133 (when (re-search-forward (concat org-scheduled-string " "
13134 org-last-inserted-timestamp)
13135 (save-excursion
13136 (outline-next-heading) (point)) t)
13137 (goto-char (1- (match-end 0)))
13138 (insert " " repeater)
13139 (setq org-last-inserted-timestamp
13140 (concat (substring org-last-inserted-timestamp 0 -1)
13141 " " repeater
13142 (substring org-last-inserted-timestamp -1))))))
13143 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13145 (defun org-get-scheduled-time (pom &optional inherit)
13146 "Get the scheduled time as a time tuple, of a format suitable
13147 for calling org-schedule with, or if there is no scheduling,
13148 returns nil."
13149 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13150 (when time
13151 (apply 'encode-time (org-parse-time-string time)))))
13153 (defun org-get-deadline-time (pom &optional inherit)
13154 "Get the deadline as a time tuple, of a format suitable for
13155 calling org-deadline with, or if there is no scheduling, returns
13156 nil."
13157 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13158 (when time
13159 (apply 'encode-time (org-parse-time-string time)))))
13161 (defun org-remove-timestamp-with-keyword (keyword)
13162 "Remove all time stamps with KEYWORD in the current entry."
13163 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13164 beg)
13165 (save-excursion
13166 (org-back-to-heading t)
13167 (setq beg (point))
13168 (outline-next-heading)
13169 (while (re-search-backward re beg t)
13170 (replace-match "")
13171 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13172 (equal (char-before) ?\ ))
13173 (backward-delete-char 1)
13174 (if (string-match "^[ \t]*$" (buffer-substring
13175 (point-at-bol) (point-at-eol)))
13176 (delete-region (point-at-bol)
13177 (min (point-max) (1+ (point-at-eol))))))))))
13179 (defvar org-time-was-given) ; dynamically scoped parameter
13180 (defvar org-end-time-was-given) ; dynamically scoped parameter
13182 (defun org-add-planning-info (what &optional time &rest remove)
13183 "Insert new timestamp with keyword in the line directly after the headline.
13184 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13185 If non is given, the user is prompted for a date.
13186 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13187 be removed."
13188 (interactive)
13189 (let (org-time-was-given org-end-time-was-given ts
13190 end default-time default-input)
13192 (catch 'exit
13193 (when (and (memq what '(scheduled deadline))
13194 (or (not time)
13195 (and (stringp time)
13196 (string-match "^[-+]+[0-9]" time))))
13197 ;; Try to get a default date/time from existing timestamp
13198 (save-excursion
13199 (org-back-to-heading t)
13200 (setq end (save-excursion (outline-next-heading) (point)))
13201 (when (re-search-forward (if (eq what 'scheduled)
13202 org-scheduled-time-regexp
13203 org-deadline-time-regexp)
13204 end t)
13205 (setq ts (match-string 1)
13206 default-time
13207 (apply 'encode-time (org-parse-time-string ts))
13208 default-input (and ts (org-get-compact-tod ts))))))
13209 (when what
13210 (setq time
13211 (if (stringp time)
13212 ;; This is a string (relative or absolute), set proper date
13213 (apply 'encode-time
13214 (org-read-date-analyze
13215 time default-time (decode-time default-time)))
13216 ;; If necessary, get the time from the user
13217 (or time (org-read-date nil 'to-time nil nil
13218 default-time default-input)))))
13220 (when (and org-insert-labeled-timestamps-at-point
13221 (member what '(scheduled deadline)))
13222 (insert
13223 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13224 (org-insert-time-stamp time org-time-was-given
13225 nil nil nil (list org-end-time-was-given))
13226 (setq what nil))
13227 (save-excursion
13228 (save-restriction
13229 (let (col list elt ts buffer-invisibility-spec)
13230 (org-back-to-heading t)
13231 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13232 (goto-char (match-end 1))
13233 (setq col (current-column))
13234 (goto-char (match-end 0))
13235 (if (eobp) (insert "\n") (forward-char 1))
13236 (when (and (not what)
13237 (not (looking-at
13238 (concat "[ \t]*"
13239 org-keyword-time-not-clock-regexp))))
13240 ;; Nothing to add, nothing to remove...... :-)
13241 (throw 'exit nil))
13242 (if (and (not (looking-at org-outline-regexp))
13243 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13244 "[^\r\n]*"))
13245 (not (equal (match-string 1) org-clock-string)))
13246 (narrow-to-region (match-beginning 0) (match-end 0))
13247 (insert-before-markers "\n")
13248 (backward-char 1)
13249 (narrow-to-region (point) (point))
13250 (and org-adapt-indentation (org-indent-to-column col)))
13251 ;; Check if we have to remove something.
13252 (setq list (cons what remove))
13253 (while list
13254 (setq elt (pop list))
13255 (when (or (and (eq elt 'scheduled)
13256 (re-search-forward org-scheduled-time-regexp nil t))
13257 (and (eq elt 'deadline)
13258 (re-search-forward org-deadline-time-regexp nil t))
13259 (and (eq elt 'closed)
13260 (re-search-forward org-closed-time-regexp nil t)))
13261 (replace-match "")
13262 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13263 (and (looking-at "[ \t]+") (replace-match ""))
13264 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13265 (when what
13266 (insert
13267 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13268 (cond ((eq what 'scheduled) org-scheduled-string)
13269 ((eq what 'deadline) org-deadline-string)
13270 ((eq what 'closed) org-closed-string))
13271 " ")
13272 (setq ts (org-insert-time-stamp
13273 time
13274 (or org-time-was-given
13275 (and (eq what 'closed) org-log-done-with-time))
13276 (eq what 'closed)
13277 nil nil (list org-end-time-was-given)))
13278 (insert
13279 (if (not (or (bolp) (eq (char-before) ?\ )
13280 (memq (char-after) '(32 10))
13281 (eobp))) " " ""))
13282 (end-of-line 1))
13283 (goto-char (point-min))
13284 (widen)
13285 (if (and (looking-at "[ \t]*\n")
13286 (equal (char-before) ?\n))
13287 (delete-region (1- (point)) (point-at-eol)))
13288 ts))))))
13290 (defvar org-log-note-marker (make-marker))
13291 (defvar org-log-note-purpose nil)
13292 (defvar org-log-note-state nil)
13293 (defvar org-log-note-previous-state nil)
13294 (defvar org-log-note-how nil)
13295 (defvar org-log-note-extra nil)
13296 (defvar org-log-note-window-configuration nil)
13297 (defvar org-log-note-return-to (make-marker))
13298 (defvar org-log-note-effective-time nil
13299 "Remembered current time so that dynamically scoped
13300 `org-extend-today-until' affects tha timestamps in state change
13301 log")
13303 (defvar org-log-post-message nil
13304 "Message to be displayed after a log note has been stored.
13305 The auto-repeater uses this.")
13307 (defun org-add-note ()
13308 "Add a note to the current entry.
13309 This is done in the same way as adding a state change note."
13310 (interactive)
13311 (org-add-log-setup 'note nil nil 'findpos nil))
13313 (defvar org-property-end-re)
13314 (defun org-add-log-setup (&optional purpose state prev-state
13315 findpos how extra)
13316 "Set up the post command hook to take a note.
13317 If this is about to TODO state change, the new state is expected in STATE.
13318 When FINDPOS is non-nil, find the correct position for the note in
13319 the current entry. If not, assume that it can be inserted at point.
13320 HOW is an indicator what kind of note should be created.
13321 EXTRA is additional text that will be inserted into the notes buffer."
13322 (let* ((org-log-into-drawer (org-log-into-drawer))
13323 (drawer (cond ((stringp org-log-into-drawer)
13324 org-log-into-drawer)
13325 (org-log-into-drawer "LOGBOOK"))))
13326 (save-restriction
13327 (save-excursion
13328 (when findpos
13329 (org-back-to-heading t)
13330 (narrow-to-region (point) (save-excursion
13331 (outline-next-heading) (point)))
13332 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13333 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13334 "[^\r\n]*\\)?"))
13335 (goto-char (match-end 0))
13336 (cond
13337 (drawer
13338 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13339 nil t)
13340 (progn
13341 (goto-char (match-end 0))
13342 (or org-log-states-order-reversed
13343 (and (re-search-forward org-property-end-re nil t)
13344 (goto-char (1- (match-beginning 0))))))
13345 (insert "\n:" drawer ":\n:END:")
13346 (beginning-of-line 0)
13347 (org-indent-line)
13348 (beginning-of-line 2)
13349 (org-indent-line)
13350 (end-of-line 0)))
13351 ((and org-log-state-notes-insert-after-drawers
13352 (save-excursion
13353 (forward-line) (looking-at org-drawer-regexp)))
13354 (forward-line)
13355 (while (looking-at org-drawer-regexp)
13356 (goto-char (match-end 0))
13357 (re-search-forward org-property-end-re (point-max) t)
13358 (forward-line))
13359 (forward-line -1)))
13360 (unless org-log-states-order-reversed
13361 (and (= (char-after) ?\n) (forward-char 1))
13362 (org-skip-over-state-notes)
13363 (skip-chars-backward " \t\n\r")))
13364 (move-marker org-log-note-marker (point))
13365 (setq org-log-note-purpose purpose
13366 org-log-note-state state
13367 org-log-note-previous-state prev-state
13368 org-log-note-how how
13369 org-log-note-extra extra
13370 org-log-note-effective-time (org-current-effective-time))
13371 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13373 (defun org-skip-over-state-notes ()
13374 "Skip past the list of State notes in an entry."
13375 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13376 (when (ignore-errors (goto-char (org-in-item-p)))
13377 (let* ((struct (org-list-struct))
13378 (prevs (org-list-prevs-alist struct)))
13379 (while (looking-at "[ \t]*- State")
13380 (goto-char (or (org-list-get-next-item (point) struct prevs)
13381 (org-list-get-item-end (point) struct)))))))
13383 (defun org-add-log-note (&optional purpose)
13384 "Pop up a window for taking a note, and add this note later at point."
13385 (remove-hook 'post-command-hook 'org-add-log-note)
13386 (setq org-log-note-window-configuration (current-window-configuration))
13387 (delete-other-windows)
13388 (move-marker org-log-note-return-to (point))
13389 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13390 (goto-char org-log-note-marker)
13391 (org-switch-to-buffer-other-window "*Org Note*")
13392 (erase-buffer)
13393 (if (memq org-log-note-how '(time state))
13394 (let (current-prefix-arg) (org-store-log-note))
13395 (let ((org-inhibit-startup t)) (org-mode))
13396 (insert (format "# Insert note for %s.
13397 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13398 (cond
13399 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13400 ((eq org-log-note-purpose 'done) "closed todo item")
13401 ((eq org-log-note-purpose 'state)
13402 (format "state change from \"%s\" to \"%s\""
13403 (or org-log-note-previous-state "")
13404 (or org-log-note-state "")))
13405 ((eq org-log-note-purpose 'reschedule)
13406 "rescheduling")
13407 ((eq org-log-note-purpose 'delschedule)
13408 "no longer scheduled")
13409 ((eq org-log-note-purpose 'redeadline)
13410 "changing deadline")
13411 ((eq org-log-note-purpose 'deldeadline)
13412 "removing deadline")
13413 ((eq org-log-note-purpose 'refile)
13414 "refiling")
13415 ((eq org-log-note-purpose 'note)
13416 "this entry")
13417 (t (error "This should not happen")))))
13418 (if org-log-note-extra (insert org-log-note-extra))
13419 (org-set-local 'org-finish-function 'org-store-log-note)
13420 (run-hooks 'org-log-buffer-setup-hook)))
13422 (defvar org-note-abort nil) ; dynamically scoped
13423 (defun org-store-log-note ()
13424 "Finish taking a log note, and insert it to where it belongs."
13425 (let ((txt (buffer-string)))
13426 (kill-buffer (current-buffer))
13427 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13428 lines ind bul)
13429 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13430 (setq txt (replace-match "" t t txt)))
13431 (if (string-match "\\s-+\\'" txt)
13432 (setq txt (replace-match "" t t txt)))
13433 (setq lines (org-split-string txt "\n"))
13434 (when (and note (string-match "\\S-" note))
13435 (setq note
13436 (org-replace-escapes
13437 note
13438 (list (cons "%u" (user-login-name))
13439 (cons "%U" user-full-name)
13440 (cons "%t" (format-time-string
13441 (org-time-stamp-format 'long 'inactive)
13442 org-log-note-effective-time))
13443 (cons "%T" (format-time-string
13444 (org-time-stamp-format 'long nil)
13445 org-log-note-effective-time))
13446 (cons "%d" (format-time-string
13447 (org-time-stamp-format nil 'inactive)
13448 org-log-note-effective-time))
13449 (cons "%D" (format-time-string
13450 (org-time-stamp-format nil nil)
13451 org-log-note-effective-time))
13452 (cons "%s" (if org-log-note-state
13453 (concat "\"" org-log-note-state "\"")
13454 ""))
13455 (cons "%S" (if org-log-note-previous-state
13456 (concat "\"" org-log-note-previous-state "\"")
13457 "\"\"")))))
13458 (if lines (setq note (concat note " \\\\")))
13459 (push note lines))
13460 (when (or current-prefix-arg org-note-abort)
13461 (when org-log-into-drawer
13462 (org-remove-empty-drawer-at org-log-note-marker))
13463 (setq lines nil))
13464 (when lines
13465 (with-current-buffer (marker-buffer org-log-note-marker)
13466 (save-excursion
13467 (goto-char org-log-note-marker)
13468 (move-marker org-log-note-marker nil)
13469 (end-of-line 1)
13470 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13471 (setq ind (save-excursion
13472 (if (ignore-errors (goto-char (org-in-item-p)))
13473 (let ((struct (org-list-struct)))
13474 (org-list-get-ind
13475 (org-list-get-top-point struct) struct))
13476 (skip-chars-backward " \r\t\n")
13477 (cond
13478 ((and (org-at-heading-p)
13479 org-adapt-indentation)
13480 (1+ (org-current-level)))
13481 ((org-at-heading-p) 0)
13482 (t (org-get-indentation))))))
13483 (setq bul (org-list-bullet-string "-"))
13484 (org-indent-line-to ind)
13485 (insert bul (pop lines))
13486 (let ((ind-body (+ (length bul) ind)))
13487 (while lines
13488 (insert "\n")
13489 (org-indent-line-to ind-body)
13490 (insert (pop lines))))
13491 (message "Note stored")
13492 (org-back-to-heading t)
13493 (org-cycle-hide-drawers 'children))
13494 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13495 ;; from within `org-add-log-note' because `buffer-undo-list'
13496 ;; is then modified outside of `org-with-remote-undo'.
13497 (when (eq this-command 'org-agenda-todo)
13498 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13499 ;; Don't add undo information when called from `org-agenda-todo'
13500 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13501 (set-window-configuration org-log-note-window-configuration)
13502 (with-current-buffer (marker-buffer org-log-note-return-to)
13503 (goto-char org-log-note-return-to))
13504 (move-marker org-log-note-return-to nil)
13505 (and org-log-post-message (message "%s" org-log-post-message))))
13507 (defun org-remove-empty-drawer-at (pos)
13508 "Remove an empty drawer at position POS.
13509 POS may also be a marker."
13510 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13511 (org-with-wide-buffer
13512 (goto-char pos)
13513 (let ((drawer (org-element-at-point)))
13514 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13515 (not (org-element-property :contents-begin drawer)))
13516 (delete-region (org-element-property :begin drawer)
13517 (progn (goto-char (org-element-property :end drawer))
13518 (skip-chars-backward " \r\t\n")
13519 (forward-line)
13520 (point))))))))
13522 (defvar org-ts-type nil)
13523 (defun org-sparse-tree (&optional arg type)
13524 "Create a sparse tree, prompt for the details.
13525 This command can create sparse trees. You first need to select the type
13526 of match used to create the tree:
13528 t Show all TODO entries.
13529 T Show entries with a specific TODO keyword.
13530 m Show entries selected by a tags/property match.
13531 p Enter a property name and its value (both with completion on existing
13532 names/values) and show entries with that property.
13533 r Show entries matching a regular expression (`/' can be used as well).
13534 b Show deadlines and scheduled items before a date.
13535 a Show deadlines and scheduled items after a date.
13536 d Show deadlines due within `org-deadline-warning-days'.
13537 D Show deadlines and scheduled items between a date range."
13538 (interactive "P")
13539 (let (ans kwd value ts-type)
13540 (setq type (or type org-sparse-tree-default-date-type))
13541 (setq org-ts-type type)
13542 (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"
13543 (cond ((eq type 'all) "all timestamps")
13544 ((eq type 'scheduled) "only scheduled")
13545 ((eq type 'deadline) "only deadline")
13546 ((eq type 'active) "only active timestamps")
13547 ((eq type 'inactive) "only inactive timestamps")
13548 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13549 ((eq type 'closed) "with a closed time-stamp")
13550 (t "scheduled/deadline")))
13551 (setq ans (read-char-exclusive))
13552 (cond
13553 ((equal ans ?c)
13554 (org-sparse-tree
13555 arg (cadr (member type '(scheduled-or-deadline
13556 all scheduled deadline active inactive closed)))))
13557 ((equal ans ?d)
13558 (call-interactively 'org-check-deadlines))
13559 ((equal ans ?b)
13560 (call-interactively 'org-check-before-date))
13561 ((equal ans ?a)
13562 (call-interactively 'org-check-after-date))
13563 ((equal ans ?D)
13564 (call-interactively 'org-check-dates-range))
13565 ((equal ans ?t)
13566 (call-interactively 'org-show-todo-tree))
13567 ((equal ans ?T)
13568 (org-show-todo-tree '(4)))
13569 ((member ans '(?T ?m))
13570 (call-interactively 'org-match-sparse-tree))
13571 ((member ans '(?p ?P))
13572 (setq kwd (org-icompleting-read "Property: "
13573 (mapcar 'list (org-buffer-property-keys))))
13574 (setq value (org-icompleting-read "Value: "
13575 (mapcar 'list (org-property-values kwd))))
13576 (unless (string-match "\\`{.*}\\'" value)
13577 (setq value (concat "\"" value "\"")))
13578 (org-match-sparse-tree arg (concat kwd "=" value)))
13579 ((member ans '(?r ?R ?/))
13580 (call-interactively 'org-occur))
13581 (t (user-error "No such sparse tree command \"%c\"" ans)))))
13583 (defvar org-occur-highlights nil
13584 "List of overlays used for occur matches.")
13585 (make-variable-buffer-local 'org-occur-highlights)
13586 (defvar org-occur-parameters nil
13587 "Parameters of the active org-occur calls.
13588 This is a list, each call to org-occur pushes as cons cell,
13589 containing the regular expression and the callback, onto the list.
13590 The list can contain several entries if `org-occur' has been called
13591 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13592 will only contain one set of parameters. When the highlights are
13593 removed (for example with `C-c C-c', or with the next edit (depending
13594 on `org-remove-highlights-with-change'), this variable is emptied
13595 as well.")
13596 (make-variable-buffer-local 'org-occur-parameters)
13598 (defun org-occur (regexp &optional keep-previous callback)
13599 "Make a compact tree which shows all matches of REGEXP.
13600 The tree will show the lines where the regexp matches, and all higher
13601 headlines above the match. It will also show the heading after the match,
13602 to make sure editing the matching entry is easy.
13603 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13604 call to `org-occur' will be kept, to allow stacking of calls to this
13605 command.
13606 If CALLBACK is non-nil, it is a function which is called to confirm
13607 that the match should indeed be shown."
13608 (interactive "sRegexp: \nP")
13609 (when (equal regexp "")
13610 (user-error "Regexp cannot be empty"))
13611 (unless keep-previous
13612 (org-remove-occur-highlights nil nil t))
13613 (push (cons regexp callback) org-occur-parameters)
13614 (let ((cnt 0))
13615 (save-excursion
13616 (goto-char (point-min))
13617 (if (or (not keep-previous) ; do not want to keep
13618 (not org-occur-highlights)) ; no previous matches
13619 ;; hide everything
13620 (org-overview))
13621 (while (re-search-forward regexp nil t)
13622 (when (or (not callback)
13623 (save-match-data (funcall callback)))
13624 (setq cnt (1+ cnt))
13625 (when org-highlight-sparse-tree-matches
13626 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13627 (org-show-context 'occur-tree))))
13628 (when org-remove-highlights-with-change
13629 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13630 nil 'local))
13631 (unless org-sparse-tree-open-archived-trees
13632 (org-hide-archived-subtrees (point-min) (point-max)))
13633 (run-hooks 'org-occur-hook)
13634 (if (org-called-interactively-p 'interactive)
13635 (message "%d match(es) for regexp %s" cnt regexp))
13636 cnt))
13638 (defun org-occur-next-match (&optional n reset)
13639 "Function for `next-error-function' to find sparse tree matches.
13640 N is the number of matches to move, when negative move backwards.
13641 RESET is entirely ignored - this function always goes back to the
13642 starting point when no match is found."
13643 (let* ((limit (if (< n 0) (point-min) (point-max)))
13644 (search-func (if (< n 0)
13645 'previous-single-char-property-change
13646 'next-single-char-property-change))
13647 (n (abs n))
13648 (pos (point))
13650 (catch 'exit
13651 (while (setq p1 (funcall search-func (point) 'org-type))
13652 (when (equal p1 limit)
13653 (goto-char pos)
13654 (error "No more matches"))
13655 (when (equal (get-char-property p1 'org-type) 'org-occur)
13656 (setq n (1- n))
13657 (when (= n 0)
13658 (goto-char p1)
13659 (throw 'exit (point))))
13660 (goto-char p1))
13661 (goto-char p1)
13662 (error "No more matches"))))
13664 (defun org-show-context (&optional key)
13665 "Make sure point and context are visible.
13666 How much context is shown depends upon the variables
13667 `org-show-hierarchy-above', `org-show-following-heading',
13668 `org-show-entry-below' and `org-show-siblings'."
13669 (let ((heading-p (org-at-heading-p t))
13670 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13671 (following-p (org-get-alist-option org-show-following-heading key))
13672 (entry-p (org-get-alist-option org-show-entry-below key))
13673 (siblings-p (org-get-alist-option org-show-siblings key)))
13674 ;; Show heading or entry text
13675 (if (and heading-p (not entry-p))
13676 (org-flag-heading nil) ; only show the heading
13677 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13678 (org-show-hidden-entry))) ; show entire entry
13679 (when following-p
13680 ;; Show next sibling, or heading below text
13681 (save-excursion
13682 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13683 (org-flag-heading nil))))
13684 (when siblings-p (org-show-siblings))
13685 (when hierarchy-p
13686 ;; show all higher headings, possibly with siblings
13687 (save-excursion
13688 (while (and (condition-case nil
13689 (progn (org-up-heading-all 1) t)
13690 (error nil))
13691 (not (bobp)))
13692 (org-flag-heading nil)
13693 (when siblings-p (org-show-siblings)))))
13694 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13696 (defvar org-reveal-start-hook nil
13697 "Hook run before revealing a location.")
13699 (defun org-reveal (&optional siblings)
13700 "Show current entry, hierarchy above it, and the following headline.
13701 This can be used to show a consistent set of context around locations
13702 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13703 not t for the search context.
13705 With optional argument SIBLINGS, on each level of the hierarchy all
13706 siblings are shown. This repairs the tree structure to what it would
13707 look like when opened with hierarchical calls to `org-cycle'.
13708 With double optional argument \\[universal-argument] \\[universal-argument], \
13709 go to the parent and show the
13710 entire tree."
13711 (interactive "P")
13712 (run-hooks 'org-reveal-start-hook)
13713 (let ((org-show-hierarchy-above t)
13714 (org-show-following-heading t)
13715 (org-show-siblings (if siblings t org-show-siblings)))
13716 (org-show-context nil))
13717 (when (equal siblings '(16))
13718 (save-excursion
13719 (when (org-up-heading-safe)
13720 (org-show-subtree)
13721 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13723 (defun org-highlight-new-match (beg end)
13724 "Highlight from BEG to END and mark the highlight is an occur headline."
13725 (let ((ov (make-overlay beg end)))
13726 (overlay-put ov 'face 'secondary-selection)
13727 (overlay-put ov 'org-type 'org-occur)
13728 (push ov org-occur-highlights)))
13730 (defun org-remove-occur-highlights (&optional beg end noremove)
13731 "Remove the occur highlights from the buffer.
13732 BEG and END are ignored. If NOREMOVE is nil, remove this function
13733 from the `before-change-functions' in the current buffer."
13734 (interactive)
13735 (unless org-inhibit-highlight-removal
13736 (mapc 'delete-overlay org-occur-highlights)
13737 (setq org-occur-highlights nil)
13738 (setq org-occur-parameters nil)
13739 (unless noremove
13740 (remove-hook 'before-change-functions
13741 'org-remove-occur-highlights 'local))))
13743 ;;;; Priorities
13745 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13746 "Regular expression matching the priority indicator.")
13748 (defvar org-remove-priority-next-time nil)
13750 (defun org-priority-up ()
13751 "Increase the priority of the current item."
13752 (interactive)
13753 (org-priority 'up))
13755 (defun org-priority-down ()
13756 "Decrease the priority of the current item."
13757 (interactive)
13758 (org-priority 'down))
13760 (defun org-priority (&optional action show)
13761 "Change the priority of an item.
13762 ACTION can be `set', `up', `down', or a character."
13763 (interactive "P")
13764 (if (equal action '(4))
13765 (org-show-priority)
13766 (unless org-enable-priority-commands
13767 (user-error "Priority commands are disabled"))
13768 (setq action (or action 'set))
13769 (let (current new news have remove)
13770 (save-excursion
13771 (org-back-to-heading t)
13772 (if (looking-at org-priority-regexp)
13773 (setq current (string-to-char (match-string 2))
13774 have t))
13775 (cond
13776 ((eq action 'remove)
13777 (setq remove t new ?\ ))
13778 ((or (eq action 'set)
13779 (if (featurep 'xemacs) (characterp action) (integerp action)))
13780 (if (not (eq action 'set))
13781 (setq new action)
13782 (message "Priority %c-%c, SPC to remove: "
13783 org-highest-priority org-lowest-priority)
13784 (save-match-data
13785 (setq new (read-char-exclusive))))
13786 (if (and (= (upcase org-highest-priority) org-highest-priority)
13787 (= (upcase org-lowest-priority) org-lowest-priority))
13788 (setq new (upcase new)))
13789 (cond ((equal new ?\ ) (setq remove t))
13790 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13791 (user-error "Priority must be between `%c' and `%c'"
13792 org-highest-priority org-lowest-priority))))
13793 ((eq action 'up)
13794 (setq new (if have
13795 (1- current) ; normal cycling
13796 ;; last priority was empty
13797 (if (eq last-command this-command)
13798 org-lowest-priority ; wrap around empty to lowest
13799 ;; default
13800 (if org-priority-start-cycle-with-default
13801 org-default-priority
13802 (1- org-default-priority))))))
13803 ((eq action 'down)
13804 (setq new (if have
13805 (1+ current) ; normal cycling
13806 ;; last priority was empty
13807 (if (eq last-command this-command)
13808 org-highest-priority ; wrap around empty to highest
13809 ;; default
13810 (if org-priority-start-cycle-with-default
13811 org-default-priority
13812 (1+ org-default-priority))))))
13813 (t (user-error "Invalid action")))
13814 (if (or (< (upcase new) org-highest-priority)
13815 (> (upcase new) org-lowest-priority))
13816 (if (and (memq action '(up down))
13817 (not have) (not (eq last-command this-command)))
13818 ;; `new' is from default priority
13819 (error
13820 "The default can not be set, see `org-default-priority' why")
13821 ;; normal cycling: `new' is beyond highest/lowest priority
13822 ;; and is wrapped around to the empty priority
13823 (setq remove t)))
13824 (setq news (format "%c" new))
13825 (if have
13826 (if remove
13827 (replace-match "" t t nil 1)
13828 (replace-match news t t nil 2))
13829 (if remove
13830 (user-error "No priority cookie found in line")
13831 (let ((case-fold-search nil))
13832 (looking-at org-todo-line-regexp))
13833 (if (match-end 2)
13834 (progn
13835 (goto-char (match-end 2))
13836 (insert " [#" news "]"))
13837 (goto-char (match-beginning 3))
13838 (insert "[#" news "] "))))
13839 (org-preserve-lc (org-set-tags nil 'align)))
13840 (if remove
13841 (message "Priority removed")
13842 (message "Priority of current item set to %s" news)))))
13844 (defun org-show-priority ()
13845 "Show the priority of the current item.
13846 This priority is composed of the main priority given with the [#A] cookies,
13847 and by additional input from the age of a schedules or deadline entry."
13848 (interactive)
13849 (let ((pri (if (eq major-mode 'org-agenda-mode)
13850 (org-get-at-bol 'priority)
13851 (save-excursion
13852 (save-match-data
13853 (beginning-of-line)
13854 (and (looking-at org-heading-regexp)
13855 (org-get-priority (match-string 0))))))))
13856 (message "Priority is %d" (if pri pri -1000))))
13858 (defun org-get-priority (s)
13859 "Find priority cookie and return priority."
13860 (save-match-data
13861 (if (functionp org-get-priority-function)
13862 (funcall org-get-priority-function)
13863 (if (not (string-match org-priority-regexp s))
13864 (* 1000 (- org-lowest-priority org-default-priority))
13865 (* 1000 (- org-lowest-priority
13866 (string-to-char (match-string 2 s))))))))
13868 ;;;; Tags
13870 (defvar org-agenda-archives-mode)
13871 (defvar org-map-continue-from nil
13872 "Position from where mapping should continue.
13873 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13875 (defvar org-scanner-tags nil
13876 "The current tag list while the tags scanner is running.")
13877 (defvar org-trust-scanner-tags nil
13878 "Should `org-get-tags-at' use the tags for the scanner.
13879 This is for internal dynamical scoping only.
13880 When this is non-nil, the function `org-get-tags-at' will return the value
13881 of `org-scanner-tags' instead of building the list by itself. This
13882 can lead to large speed-ups when the tags scanner is used in a file with
13883 many entries, and when the list of tags is retrieved, for example to
13884 obtain a list of properties. Building the tags list for each entry in such
13885 a file becomes an N^2 operation - but with this variable set, it scales
13886 as N.")
13888 (defun org-scan-tags (action matcher todo-only &optional start-level)
13889 "Sca headline tags with inheritance and produce output ACTION.
13891 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13892 or `agenda' to produce an entry list for an agenda view. It can also be
13893 a Lisp form or a function that should be called at each matched headline, in
13894 this case the return value is a list of all return values from these calls.
13896 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13897 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13898 only lines with a not-done TODO keyword are included in the output.
13899 This should be the same variable that was scoped into
13900 and set by `org-make-tags-matcher' when it constructed MATCHER.
13902 START-LEVEL can be a string with asterisks, reducing the scope to
13903 headlines matching this string."
13904 (require 'org-agenda)
13905 (let* ((re (concat "^"
13906 (if start-level
13907 ;; Get the correct level to match
13908 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13909 org-outline-regexp)
13910 " *\\(\\<\\("
13911 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13912 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13913 (props (list 'face 'default
13914 'done-face 'org-agenda-done
13915 'undone-face 'default
13916 'mouse-face 'highlight
13917 'org-not-done-regexp org-not-done-regexp
13918 'org-todo-regexp org-todo-regexp
13919 'org-complex-heading-regexp org-complex-heading-regexp
13920 'help-echo
13921 (format "mouse-2 or RET jump to org file %s"
13922 (abbreviate-file-name
13923 (or (buffer-file-name (buffer-base-buffer))
13924 (buffer-name (buffer-base-buffer)))))))
13925 (org-map-continue-from nil)
13926 lspos tags tags-list
13927 (tags-alist (list (cons 0 org-file-tags)))
13928 (llast 0) rtn rtn1 level category i txt
13929 todo marker entry priority)
13930 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13931 (setq action (list 'lambda nil action)))
13932 (save-excursion
13933 (goto-char (point-min))
13934 (when (eq action 'sparse-tree)
13935 (org-overview)
13936 (org-remove-occur-highlights))
13937 (while (let (case-fold-search)
13938 (re-search-forward re nil t))
13939 (setq org-map-continue-from nil)
13940 (catch :skip
13941 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13942 tags (if (match-end 4) (org-match-string-no-properties 4)))
13943 (goto-char (setq lspos (match-beginning 0)))
13944 (setq level (org-reduced-level (org-outline-level))
13945 category (org-get-category))
13946 (setq i llast llast level)
13947 ;; remove tag lists from same and sublevels
13948 (while (>= i level)
13949 (when (setq entry (assoc i tags-alist))
13950 (setq tags-alist (delete entry tags-alist)))
13951 (setq i (1- i)))
13952 ;; add the next tags
13953 (when tags
13954 (setq tags (org-split-string tags ":")
13955 tags-alist
13956 (cons (cons level tags) tags-alist)))
13957 ;; compile tags for current headline
13958 (setq tags-list
13959 (if org-use-tag-inheritance
13960 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13961 tags)
13962 org-scanner-tags tags-list)
13963 (when org-use-tag-inheritance
13964 (setcdr (car tags-alist)
13965 (mapcar (lambda (x)
13966 (setq x (copy-sequence x))
13967 (org-add-prop-inherited x))
13968 (cdar tags-alist))))
13969 (when (and tags org-use-tag-inheritance
13970 (or (not (eq t org-use-tag-inheritance))
13971 org-tags-exclude-from-inheritance))
13972 ;; selective inheritance, remove uninherited ones
13973 (setcdr (car tags-alist)
13974 (org-remove-uninherited-tags (cdar tags-alist))))
13975 (when (and
13977 ;; eval matcher only when the todo condition is OK
13978 (and (or (not todo-only) (member todo org-not-done-keywords))
13979 (let ((case-fold-search t) (org-trust-scanner-tags t))
13980 (eval matcher)))
13982 ;; Call the skipper, but return t if it does not skip,
13983 ;; so that the `and' form continues evaluating
13984 (progn
13985 (unless (eq action 'sparse-tree) (org-agenda-skip))
13988 ;; Check if timestamps are deselecting this entry
13989 (or (not todo-only)
13990 (and (member todo org-not-done-keywords)
13991 (or (not org-agenda-tags-todo-honor-ignore-options)
13992 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13994 ;; select this headline
13995 (cond
13996 ((eq action 'sparse-tree)
13997 (and org-highlight-sparse-tree-matches
13998 (org-get-heading) (match-end 0)
13999 (org-highlight-new-match
14000 (match-beginning 1) (match-end 1)))
14001 (org-show-context 'tags-tree))
14002 ((eq action 'agenda)
14003 (setq txt (org-agenda-format-item
14005 (concat
14006 (if (eq org-tags-match-list-sublevels 'indented)
14007 (make-string (1- level) ?.) "")
14008 (org-get-heading))
14009 level category
14010 tags-list)
14011 priority (org-get-priority txt))
14012 (goto-char lspos)
14013 (setq marker (org-agenda-new-marker))
14014 (org-add-props txt props
14015 'org-marker marker 'org-hd-marker marker 'org-category category
14016 'todo-state todo
14017 'priority priority 'type "tagsmatch")
14018 (push txt rtn))
14019 ((functionp action)
14020 (setq org-map-continue-from nil)
14021 (save-excursion
14022 (setq rtn1 (funcall action))
14023 (push rtn1 rtn)))
14024 (t (user-error "Invalid action")))
14026 ;; if we are to skip sublevels, jump to end of subtree
14027 (unless org-tags-match-list-sublevels
14028 (org-end-of-subtree t)
14029 (backward-char 1))))
14030 ;; Get the correct position from where to continue
14031 (if org-map-continue-from
14032 (goto-char org-map-continue-from)
14033 (and (= (point) lspos) (end-of-line 1)))))
14034 (when (and (eq action 'sparse-tree)
14035 (not org-sparse-tree-open-archived-trees))
14036 (org-hide-archived-subtrees (point-min) (point-max)))
14037 (nreverse rtn)))
14039 (defun org-remove-uninherited-tags (tags)
14040 "Remove all tags that are not inherited from the list TAGS."
14041 (cond
14042 ((eq org-use-tag-inheritance t)
14043 (if org-tags-exclude-from-inheritance
14044 (org-delete-all org-tags-exclude-from-inheritance tags)
14045 tags))
14046 ((not org-use-tag-inheritance) nil)
14047 ((stringp org-use-tag-inheritance)
14048 (delq nil (mapcar
14049 (lambda (x)
14050 (if (and (string-match org-use-tag-inheritance x)
14051 (not (member x org-tags-exclude-from-inheritance)))
14052 x nil))
14053 tags)))
14054 ((listp org-use-tag-inheritance)
14055 (delq nil (mapcar
14056 (lambda (x)
14057 (if (member x org-use-tag-inheritance) x nil))
14058 tags)))))
14060 (defun org-match-sparse-tree (&optional todo-only match)
14061 "Create a sparse tree according to tags string MATCH.
14062 MATCH can contain positive and negative selection of tags, like
14063 \"+WORK+URGENT-WITHBOSS\".
14064 If optional argument TODO-ONLY is non-nil, only select lines that are
14065 also TODO lines."
14066 (interactive "P")
14067 (org-agenda-prepare-buffers (list (current-buffer)))
14068 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
14070 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14072 (defvar org-cached-props nil)
14073 (defun org-cached-entry-get (pom property)
14074 (if (or (eq t org-use-property-inheritance)
14075 (and (stringp org-use-property-inheritance)
14076 (string-match org-use-property-inheritance property))
14077 (and (listp org-use-property-inheritance)
14078 (member property org-use-property-inheritance)))
14079 ;; Caching is not possible, check it directly
14080 (org-entry-get pom property 'inherit)
14081 ;; Get all properties, so that we can do complicated checks easily
14082 (cdr (assoc property (or org-cached-props
14083 (setq org-cached-props
14084 (org-entry-properties pom)))))))
14086 (defun org-global-tags-completion-table (&optional files)
14087 "Return the list of all tags in all agenda buffer/files.
14088 Optional FILES argument is a list of files which can be used
14089 instead of the agenda files."
14090 (save-excursion
14091 (org-uniquify
14092 (delq nil
14093 (apply 'append
14094 (mapcar
14095 (lambda (file)
14096 (set-buffer (find-file-noselect file))
14097 (append (org-get-buffer-tags)
14098 (mapcar (lambda (x) (if (stringp (car-safe x))
14099 (list (car-safe x)) nil))
14100 org-tag-alist)))
14101 (if (and files (car files))
14102 files
14103 (org-agenda-files))))))))
14105 (defun org-make-tags-matcher (match)
14106 "Create the TAGS/TODO matcher form for the selection string MATCH.
14108 The variable `todo-only' is scoped dynamically into this function.
14109 It will be set to t if the matcher restricts matching to TODO entries,
14110 otherwise will not be touched.
14112 Returns a cons of the selection string MATCH and the constructed
14113 lisp form implementing the matcher. The matcher is to be evaluated
14114 at an Org entry, with point on the headline, and returns t if the
14115 entry matches the selection string MATCH. The returned lisp form
14116 references two variables with information about the entry, which
14117 must be bound around the form's evaluation: todo, the TODO keyword
14118 at the entry (or nil of none); and tags-list, the list of all tags
14119 at the entry including inherited ones. Additionally, the category
14120 of the entry (if any) must be specified as the text property
14121 'org-category on the headline.
14123 See also `org-scan-tags'.
14125 (declare (special todo-only))
14126 (unless (boundp 'todo-only)
14127 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14128 (unless match
14129 ;; Get a new match request, with completion against the global
14130 ;; tags table and the local tags in current buffer
14131 (let ((org-last-tags-completion-table
14132 (org-uniquify
14133 (delq nil (append (org-get-buffer-tags)
14134 (org-global-tags-completion-table))))))
14135 (setq match (org-completing-read-no-i
14136 "Match: " 'org-tags-completion-function nil nil nil
14137 'org-tags-history))))
14139 ;; Parse the string and create a lisp form
14140 (let ((match0 match)
14141 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14142 minus tag mm
14143 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14144 orterms term orlist re-p str-p level-p level-op time-p
14145 prop-p pn pv po gv rest (start 0) (ss 0))
14146 ;; Expand group tags
14147 (setq match (org-tags-expand match))
14149 ;; Check if there is a TODO part of this match, which would be the
14150 ;; part after a "/". TO make sure that this slash is not part of
14151 ;; a property value to be matched against, we also check that there
14152 ;; is no " after that slash.
14153 ;; First, find the last slash
14154 (while (string-match "/+" match ss)
14155 (setq start (match-beginning 0) ss (match-end 0)))
14156 (if (and (string-match "/+" match start)
14157 (not (save-match-data (string-match "\"" match start))))
14158 ;; match contains also a todo-matching request
14159 (progn
14160 (setq tagsmatch (substring match 0 (match-beginning 0))
14161 todomatch (substring match (match-end 0)))
14162 (if (string-match "^!" todomatch)
14163 (setq todo-only t todomatch (substring todomatch 1)))
14164 (if (string-match "^\\s-*$" todomatch)
14165 (setq todomatch nil)))
14166 ;; only matching tags
14167 (setq tagsmatch match todomatch nil))
14169 ;; Make the tags matcher
14170 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14171 (setq tagsmatcher t)
14172 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14173 (while (setq term (pop orterms))
14174 (while (and (equal (substring term -1) "\\") orterms)
14175 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14176 (while (string-match re term)
14177 (setq rest (substring term (match-end 0))
14178 minus (and (match-end 1)
14179 (equal (match-string 1 term) "-"))
14180 tag (save-match-data (replace-regexp-in-string
14181 "\\\\-" "-"
14182 (match-string 2 term)))
14183 re-p (equal (string-to-char tag) ?{)
14184 level-p (match-end 4)
14185 prop-p (match-end 5)
14186 mm (cond
14187 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14188 (level-p
14189 (setq level-op (org-op-to-function (match-string 3 term)))
14190 `(,level-op level ,(string-to-number
14191 (match-string 4 term))))
14192 (prop-p
14193 (setq pn (match-string 5 term)
14194 po (match-string 6 term)
14195 pv (match-string 7 term)
14196 re-p (equal (string-to-char pv) ?{)
14197 str-p (equal (string-to-char pv) ?\")
14198 time-p (save-match-data
14199 (string-match "^\"[[<].*[]>]\"$" pv))
14200 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14201 (if time-p (setq pv (org-matcher-time pv)))
14202 (setq po (org-op-to-function po (if time-p 'time str-p)))
14203 (cond
14204 ((equal pn "CATEGORY")
14205 (setq gv '(get-text-property (point) 'org-category)))
14206 ((equal pn "TODO")
14207 (setq gv 'todo))
14209 (setq gv `(org-cached-entry-get nil ,pn))))
14210 (if re-p
14211 (if (eq po 'org<>)
14212 `(not (string-match ,pv (or ,gv "")))
14213 `(string-match ,pv (or ,gv "")))
14214 (if str-p
14215 `(,po (or ,gv "") ,pv)
14216 `(,po (string-to-number (or ,gv ""))
14217 ,(string-to-number pv) ))))
14218 (t `(member ,tag tags-list)))
14219 mm (if minus (list 'not mm) mm)
14220 term rest)
14221 (push mm tagsmatcher))
14222 (push (if (> (length tagsmatcher) 1)
14223 (cons 'and tagsmatcher)
14224 (car tagsmatcher))
14225 orlist)
14226 (setq tagsmatcher nil))
14227 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14228 (setq tagsmatcher
14229 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14230 ;; Make the todo matcher
14231 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14232 (setq todomatcher t)
14233 (setq orterms (org-split-string todomatch "|") orlist nil)
14234 (while (setq term (pop orterms))
14235 (while (string-match re term)
14236 (setq minus (and (match-end 1)
14237 (equal (match-string 1 term) "-"))
14238 kwd (match-string 2 term)
14239 re-p (equal (string-to-char kwd) ?{)
14240 term (substring term (match-end 0))
14241 mm (if re-p
14242 `(string-match ,(substring kwd 1 -1) todo)
14243 (list 'equal 'todo kwd))
14244 mm (if minus (list 'not mm) mm))
14245 (push mm todomatcher))
14246 (push (if (> (length todomatcher) 1)
14247 (cons 'and todomatcher)
14248 (car todomatcher))
14249 orlist)
14250 (setq todomatcher nil))
14251 (setq todomatcher (if (> (length orlist) 1)
14252 (cons 'or orlist) (car orlist))))
14254 ;; Return the string and lisp forms of the matcher
14255 (setq matcher (if todomatcher
14256 (list 'and tagsmatcher todomatcher)
14257 tagsmatcher))
14258 (when todo-only
14259 (setq matcher (list 'and '(member todo org-not-done-keywords)
14260 matcher)))
14261 (cons match0 matcher)))
14263 (defun org-tags-expand (match &optional single-as-list downcased)
14264 "Expand group tags in MATCH.
14266 This replaces every group tag in MATCH with a regexp tag search.
14267 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14268 will be replaced like this:
14270 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14271 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14272 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14274 Replacing by a regexp preserves the structure of the match.
14275 E.g., this expansion
14277 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14279 will match anything tagged with \"Lab\" and \"Home\", or tagged
14280 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14282 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14283 assumed to be a single group tag, and the function will return
14284 the list of tags in this group.
14286 When DOWNCASE is non-nil, expand downcased TAGS."
14287 (if org-group-tags
14288 (let* ((case-fold-search t)
14289 (stable org-mode-syntax-table)
14290 (tal (or org-tag-groups-alist-for-agenda
14291 org-tag-groups-alist))
14292 (tal (if downcased
14293 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14294 (tml (mapcar 'car tal))
14295 (rtnmatch match) rpl)
14296 ;; @ and _ are allowed as word-components in tags
14297 (modify-syntax-entry ?@ "w" stable)
14298 (modify-syntax-entry ?_ "w" stable)
14299 (while (and tml
14300 (with-syntax-table stable
14301 (string-match
14302 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14303 (regexp-opt tml) "\\>\\)") rtnmatch)))
14304 (let* ((dir (match-string 1 rtnmatch))
14305 (tag (match-string 2 rtnmatch))
14306 (tag (if downcased (downcase tag) tag)))
14307 (setq tml (delete tag tml))
14308 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14309 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14310 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14311 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14312 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14313 (if single-as-list
14314 (or (reverse rpl) (list rtnmatch))
14315 rtnmatch))
14316 (if single-as-list (list (if downcased (downcase match) match))
14317 match)))
14319 (defun org-op-to-function (op &optional stringp)
14320 "Turn an operator into the appropriate function."
14321 (setq op
14322 (cond
14323 ((equal op "<" ) '(< string< org-time<))
14324 ((equal op ">" ) '(> org-string> org-time>))
14325 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14326 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14327 ((member op '("=" "==")) '(= string= org-time=))
14328 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14329 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14331 (defun org<> (a b) (not (= a b)))
14332 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14333 (defun org-string>= (a b) (not (string< a b)))
14334 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14335 (defun org-string<> (a b) (not (string= a b)))
14336 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14337 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14338 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14339 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14340 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14341 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14342 (defun org-2ft (s)
14343 "Convert S to a floating point time.
14344 If S is already a number, just return it. If it is a string, parse
14345 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14346 (cond
14347 ((numberp s) s)
14348 ((stringp s)
14349 (condition-case nil
14350 (float-time (apply 'encode-time (org-parse-time-string s)))
14351 (error 0.)))
14352 (t 0.)))
14354 (defun org-time-today ()
14355 "Time in seconds today at 0:00.
14356 Returns the float number of seconds since the beginning of the
14357 epoch to the beginning of today (00:00)."
14358 (float-time (apply 'encode-time
14359 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14361 (defun org-matcher-time (s)
14362 "Interpret a time comparison value."
14363 (save-match-data
14364 (cond
14365 ((string= s "<now>") (float-time))
14366 ((string= s "<today>") (org-time-today))
14367 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14368 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14369 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14370 (+ (org-time-today)
14371 (* (string-to-number (match-string 1 s))
14372 (cdr (assoc (match-string 2 s)
14373 '(("d" . 86400.0) ("w" . 604800.0)
14374 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14375 (t (org-2ft s)))))
14377 (defun org-match-any-p (re list)
14378 "Does re match any element of list?"
14379 (setq list (mapcar (lambda (x) (string-match re x)) list))
14380 (delq nil list))
14382 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14383 (defvar org-tags-overlay (make-overlay 1 1))
14384 (org-detach-overlay org-tags-overlay)
14386 (defun org-get-local-tags-at (&optional pos)
14387 "Get a list of tags defined in the current headline."
14388 (org-get-tags-at pos 'local))
14390 (defun org-get-local-tags ()
14391 "Get a list of tags defined in the current headline."
14392 (org-get-tags-at nil 'local))
14394 (defun org-get-tags-at (&optional pos local)
14395 "Get a list of all headline tags applicable at POS.
14396 POS defaults to point. If tags are inherited, the list contains
14397 the targets in the same sequence as the headlines appear, i.e.
14398 the tags of the current headline come last.
14399 When LOCAL is non-nil, only return tags from the current headline,
14400 ignore inherited ones."
14401 (interactive)
14402 (if (and org-trust-scanner-tags
14403 (or (not pos) (equal pos (point)))
14404 (not local))
14405 org-scanner-tags
14406 (let (tags ltags lastpos parent)
14407 (save-excursion
14408 (save-restriction
14409 (widen)
14410 (goto-char (or pos (point)))
14411 (save-match-data
14412 (catch 'done
14413 (condition-case nil
14414 (progn
14415 (org-back-to-heading t)
14416 (while (not (equal lastpos (point)))
14417 (setq lastpos (point))
14418 (when (looking-at
14419 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14420 (setq ltags (org-split-string
14421 (org-match-string-no-properties 1) ":"))
14422 (when parent
14423 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14424 (setq tags (append
14425 (if parent
14426 (org-remove-uninherited-tags ltags)
14427 ltags)
14428 tags)))
14429 (or org-use-tag-inheritance (throw 'done t))
14430 (if local (throw 'done t))
14431 (or (org-up-heading-safe) (error nil))
14432 (setq parent t)))
14433 (error nil)))))
14434 (if local
14435 tags
14436 (reverse (delete-dups
14437 (reverse (append
14438 (org-remove-uninherited-tags
14439 org-file-tags) tags)))))))))
14441 (defun org-add-prop-inherited (s)
14442 (add-text-properties 0 (length s) '(inherited t) s)
14445 (defun org-toggle-tag (tag &optional onoff)
14446 "Toggle the tag TAG for the current line.
14447 If ONOFF is `on' or `off', don't toggle but set to this state."
14448 (let (res current)
14449 (save-excursion
14450 (org-back-to-heading t)
14451 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14452 (point-at-eol) t)
14453 (progn
14454 (setq current (match-string 1))
14455 (replace-match ""))
14456 (setq current ""))
14457 (setq current (nreverse (org-split-string current ":")))
14458 (cond
14459 ((eq onoff 'on)
14460 (setq res t)
14461 (or (member tag current) (push tag current)))
14462 ((eq onoff 'off)
14463 (or (not (member tag current)) (setq current (delete tag current))))
14464 (t (if (member tag current)
14465 (setq current (delete tag current))
14466 (setq res t)
14467 (push tag current))))
14468 (end-of-line 1)
14469 (if current
14470 (progn
14471 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14472 (org-set-tags nil t))
14473 (delete-horizontal-space))
14474 (run-hooks 'org-after-tags-change-hook))
14475 res))
14477 (defun org-align-tags-here (to-col)
14478 ;; Assumes that this is a headline
14479 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14480 (beginning-of-line 1)
14481 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14482 (< pos (match-beginning 2)))
14483 (progn
14484 (setq tags-l (- (match-end 2) (match-beginning 2)))
14485 (goto-char (match-beginning 1))
14486 (insert " ")
14487 (delete-region (point) (1+ (match-beginning 2)))
14488 (setq ncol (max (current-column)
14489 (1+ col)
14490 (if (> to-col 0)
14491 to-col
14492 (- (abs to-col) tags-l))))
14493 (setq p (point))
14494 (insert (make-string (- ncol (current-column)) ?\ ))
14495 (setq ncol (current-column))
14496 (when indent-tabs-mode (tabify p (point-at-eol)))
14497 (org-move-to-column (min ncol col) t nil t))
14498 (goto-char pos))))
14500 (defun org-set-tags-command (&optional arg just-align)
14501 "Call the set-tags command for the current entry."
14502 (interactive "P")
14503 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14504 (org-set-tags arg just-align)
14505 (save-excursion
14506 (unless (and (org-region-active-p)
14507 org-loop-over-headlines-in-active-region)
14508 (org-back-to-heading t))
14509 (org-set-tags arg just-align))))
14511 (defun org-set-tags-to (data)
14512 "Set the tags of the current entry to DATA, replacing the current tags.
14513 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14514 If DATA is nil or the empty string, any tags will be removed."
14515 (interactive "sTags: ")
14516 (setq data
14517 (cond
14518 ((eq data nil) "")
14519 ((equal data "") "")
14520 ((stringp data)
14521 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14522 ":"))
14523 ((listp data)
14524 (concat ":" (mapconcat 'identity data ":") ":"))))
14525 (when data
14526 (save-excursion
14527 (org-back-to-heading t)
14528 (when (looking-at org-complex-heading-regexp)
14529 (if (match-end 5)
14530 (progn
14531 (goto-char (match-beginning 5))
14532 (insert data)
14533 (delete-region (point) (point-at-eol))
14534 (org-set-tags nil 'align))
14535 (goto-char (point-at-eol))
14536 (insert " " data)
14537 (org-set-tags nil 'align)))
14538 (beginning-of-line 1)
14539 (if (looking-at ".*?\\([ \t]+\\)$")
14540 (delete-region (match-beginning 1) (match-end 1))))))
14542 (defun org-align-all-tags ()
14543 "Align the tags i all headings."
14544 (interactive)
14545 (save-excursion
14546 (or (ignore-errors (org-back-to-heading t))
14547 (outline-next-heading))
14548 (if (org-at-heading-p)
14549 (org-set-tags t)
14550 (message "No headings"))))
14552 (defvar org-indent-indentation-per-level)
14553 (defun org-set-tags (&optional arg just-align)
14554 "Set the tags for the current headline.
14555 With prefix ARG, realign all tags in headings in the current buffer."
14556 (interactive "P")
14557 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14558 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14559 'region-start-level 'region))
14560 org-loop-over-headlines-in-active-region)
14561 (org-map-entries
14562 ;; We don't use ARG and JUST-ALIGN here these args are not
14563 ;; useful when looping over headlines
14564 `(org-set-tags)
14565 org-loop-over-headlines-in-active-region
14566 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14567 (let* ((re org-outline-regexp-bol)
14568 (current (unless arg (org-get-tags-string)))
14569 (col (current-column))
14570 (org-setting-tags t)
14571 table current-tags inherited-tags ; computed below when needed
14572 tags p0 c0 c1 rpl di tc level)
14573 (if arg
14574 (save-excursion
14575 (goto-char (point-min))
14576 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14577 (while (re-search-forward re nil t)
14578 (org-set-tags nil t)
14579 (end-of-line 1)))
14580 (message "All tags realigned to column %d" org-tags-column))
14581 (if just-align
14582 (setq tags current)
14583 ;; Get a new set of tags from the user
14584 (save-excursion
14585 (setq table (append org-tag-persistent-alist
14586 (or org-tag-alist (org-get-buffer-tags))
14587 (and
14588 org-complete-tags-always-offer-all-agenda-tags
14589 (org-global-tags-completion-table
14590 (org-agenda-files))))
14591 org-last-tags-completion-table table
14592 current-tags (org-split-string current ":")
14593 inherited-tags (nreverse
14594 (nthcdr (length current-tags)
14595 (nreverse (org-get-tags-at))))
14596 tags
14597 (if (or (eq t org-use-fast-tag-selection)
14598 (and org-use-fast-tag-selection
14599 (delq nil (mapcar 'cdr table))))
14600 (org-fast-tag-selection
14601 current-tags inherited-tags table
14602 (if org-fast-tag-selection-include-todo
14603 org-todo-key-alist))
14604 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14605 (org-trim
14606 (org-icompleting-read "Tags: "
14607 'org-tags-completion-function
14608 nil nil current 'org-tags-history))))))
14609 (while (string-match "[-+&]+" tags)
14610 ;; No boolean logic, just a list
14611 (setq tags (replace-match ":" t t tags))))
14613 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14615 (if org-tags-sort-function
14616 (setq tags (mapconcat 'identity
14617 (sort (org-split-string
14618 tags (org-re "[^[:alnum:]_@#%]+"))
14619 org-tags-sort-function) ":")))
14621 (if (string-match "\\`[\t ]*\\'" tags)
14622 (setq tags "")
14623 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14624 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14626 ;; Insert new tags at the correct column
14627 (beginning-of-line 1)
14628 (setq level (or (and (looking-at org-outline-regexp)
14629 (- (match-end 0) (point) 1))
14631 (cond
14632 ((and (equal current "") (equal tags "")))
14633 ((re-search-forward
14634 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14635 (point-at-eol) t)
14636 (if (equal tags "")
14637 (setq rpl "")
14638 (goto-char (match-beginning 0))
14639 (setq c0 (current-column)
14640 ;; compute offset for the case of org-indent-mode active
14641 di (if org-indent-mode
14642 (* (1- org-indent-indentation-per-level) (1- level))
14644 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14645 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14646 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (string-width tags))))
14647 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14648 (replace-match rpl t t)
14649 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14650 tags)
14651 (t (error "Tags alignment failed")))
14652 (org-move-to-column col)
14653 (unless just-align
14654 (run-hooks 'org-after-tags-change-hook))))))
14656 (defun org-change-tag-in-region (beg end tag off)
14657 "Add or remove TAG for each entry in the region.
14658 This works in the agenda, and also in an org-mode buffer."
14659 (interactive
14660 (list (region-beginning) (region-end)
14661 (let ((org-last-tags-completion-table
14662 (if (derived-mode-p 'org-mode)
14663 (org-uniquify
14664 (delq nil (append (org-get-buffer-tags)
14665 (org-global-tags-completion-table))))
14666 (org-global-tags-completion-table))))
14667 (org-icompleting-read
14668 "Tag: " 'org-tags-completion-function nil nil nil
14669 'org-tags-history))
14670 (progn
14671 (message "[s]et or [r]emove? ")
14672 (equal (read-char-exclusive) ?r))))
14673 (if (fboundp 'deactivate-mark) (deactivate-mark))
14674 (let ((agendap (equal major-mode 'org-agenda-mode))
14675 l1 l2 m buf pos newhead (cnt 0))
14676 (goto-char end)
14677 (setq l2 (1- (org-current-line)))
14678 (goto-char beg)
14679 (setq l1 (org-current-line))
14680 (loop for l from l1 to l2 do
14681 (org-goto-line l)
14682 (setq m (get-text-property (point) 'org-hd-marker))
14683 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14684 (and agendap m))
14685 (setq buf (if agendap (marker-buffer m) (current-buffer))
14686 pos (if agendap m (point)))
14687 (with-current-buffer buf
14688 (save-excursion
14689 (save-restriction
14690 (goto-char pos)
14691 (setq cnt (1+ cnt))
14692 (org-toggle-tag tag (if off 'off 'on))
14693 (setq newhead (org-get-heading)))))
14694 (and agendap (org-agenda-change-all-lines newhead m))))
14695 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14697 (defun org-tags-completion-function (string predicate &optional flag)
14698 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14699 (confirm (lambda (x) (stringp (car x)))))
14700 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14701 (setq s1 (match-string 1 string)
14702 s2 (match-string 2 string))
14703 (setq s1 "" s2 string))
14704 (cond
14705 ((eq flag nil)
14706 ;; try completion
14707 (setq rtn (try-completion s2 ctable confirm))
14708 (if (stringp rtn)
14709 (setq rtn
14710 (concat s1 s2 (substring rtn (length s2))
14711 (if (and org-add-colon-after-tag-completion
14712 (assoc rtn ctable))
14713 ":" ""))))
14714 rtn)
14715 ((eq flag t)
14716 ;; all-completions
14717 (all-completions s2 ctable confirm))
14718 ((eq flag 'lambda)
14719 ;; exact match?
14720 (assoc s2 ctable)))))
14722 (defun org-fast-tag-insert (kwd tags face &optional end)
14723 "Insert KDW, and the TAGS, the latter with face FACE.
14724 Also insert END."
14725 (insert (format "%-12s" (concat kwd ":"))
14726 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14727 (or end "")))
14729 (defun org-fast-tag-show-exit (flag)
14730 (save-excursion
14731 (org-goto-line 3)
14732 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14733 (replace-match ""))
14734 (when flag
14735 (end-of-line 1)
14736 (org-move-to-column (- (window-width) 19) t)
14737 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14739 (defun org-set-current-tags-overlay (current prefix)
14740 "Add an overlay to CURRENT tag with PREFIX."
14741 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14742 (if (featurep 'xemacs)
14743 (org-overlay-display org-tags-overlay (concat prefix s)
14744 'secondary-selection)
14745 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14746 (org-overlay-display org-tags-overlay (concat prefix s)))))
14748 (defvar org-last-tag-selection-key nil)
14749 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14750 "Fast tag selection with single keys.
14751 CURRENT is the current list of tags in the headline, INHERITED is the
14752 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14753 possibly with grouping information. TODO-TABLE is a similar table with
14754 TODO keywords, should these have keys assigned to them.
14755 If the keys are nil, a-z are automatically assigned.
14756 Returns the new tags string, or nil to not change the current settings."
14757 (let* ((fulltable (append table todo-table))
14758 (maxlen (apply 'max (mapcar
14759 (lambda (x)
14760 (if (stringp (car x)) (string-width (car x)) 0))
14761 fulltable)))
14762 (buf (current-buffer))
14763 (expert (eq org-fast-tag-selection-single-key 'expert))
14764 (buffer-tags nil)
14765 (fwidth (+ maxlen 3 1 3))
14766 (ncol (/ (- (window-width) 4) fwidth))
14767 (i-face 'org-done)
14768 (c-face 'org-todo)
14769 tg cnt e c char c1 c2 ntable tbl rtn
14770 ov-start ov-end ov-prefix
14771 (exit-after-next org-fast-tag-selection-single-key)
14772 (done-keywords org-done-keywords)
14773 groups ingroup)
14774 (save-excursion
14775 (beginning-of-line 1)
14776 (if (looking-at
14777 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14778 (setq ov-start (match-beginning 1)
14779 ov-end (match-end 1)
14780 ov-prefix "")
14781 (setq ov-start (1- (point-at-eol))
14782 ov-end (1+ ov-start))
14783 (skip-chars-forward "^\n\r")
14784 (setq ov-prefix
14785 (concat
14786 (buffer-substring (1- (point)) (point))
14787 (if (> (current-column) org-tags-column)
14789 (make-string (- org-tags-column (current-column)) ?\ ))))))
14790 (move-overlay org-tags-overlay ov-start ov-end)
14791 (save-window-excursion
14792 (if expert
14793 (set-buffer (get-buffer-create " *Org tags*"))
14794 (delete-other-windows)
14795 (split-window-vertically)
14796 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14797 (erase-buffer)
14798 (org-set-local 'org-done-keywords done-keywords)
14799 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14800 (org-fast-tag-insert "Current" current c-face "\n\n")
14801 (org-fast-tag-show-exit exit-after-next)
14802 (org-set-current-tags-overlay current ov-prefix)
14803 (setq tbl fulltable char ?a cnt 0)
14804 (while (setq e (pop tbl))
14805 (cond
14806 ((equal (car e) :startgroup)
14807 (push '() groups) (setq ingroup t)
14808 (when (not (= cnt 0))
14809 (setq cnt 0)
14810 (insert "\n"))
14811 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14812 ((equal (car e) :endgroup)
14813 (setq ingroup nil cnt 0)
14814 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14815 ((equal e '(:newline))
14816 (when (not (= cnt 0))
14817 (setq cnt 0)
14818 (insert "\n")
14819 (setq e (car tbl))
14820 (while (equal (car tbl) '(:newline))
14821 (insert "\n")
14822 (setq tbl (cdr tbl)))))
14823 ((equal e '(:grouptags)) nil)
14825 (setq tg (copy-sequence (car e)) c2 nil)
14826 (if (cdr e)
14827 (setq c (cdr e))
14828 ;; automatically assign a character.
14829 (setq c1 (string-to-char
14830 (downcase (substring
14831 tg (if (= (string-to-char tg) ?@) 1 0)))))
14832 (if (or (rassoc c1 ntable) (rassoc c1 table))
14833 (while (or (rassoc char ntable) (rassoc char table))
14834 (setq char (1+ char)))
14835 (setq c2 c1))
14836 (setq c (or c2 char)))
14837 (if ingroup (push tg (car groups)))
14838 (setq tg (org-add-props tg nil 'face
14839 (cond
14840 ((not (assoc tg table))
14841 (org-get-todo-face tg))
14842 ((member tg current) c-face)
14843 ((member tg inherited) i-face))))
14844 (if (equal (caar tbl) :grouptags)
14845 (org-add-props tg nil 'face 'org-tag-group))
14846 (if (and (= cnt 0) (not ingroup)) (insert " "))
14847 (insert "[" c "] " tg (make-string
14848 (- fwidth 4 (length tg)) ?\ ))
14849 (push (cons tg c) ntable)
14850 (when (= (setq cnt (1+ cnt)) ncol)
14851 (insert "\n")
14852 (if ingroup (insert " "))
14853 (setq cnt 0)))))
14854 (setq ntable (nreverse ntable))
14855 (insert "\n")
14856 (goto-char (point-min))
14857 (if (not expert) (org-fit-window-to-buffer))
14858 (setq rtn
14859 (catch 'exit
14860 (while t
14861 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14862 (if (not groups) "no " "")
14863 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14864 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14865 (setq org-last-tag-selection-key c)
14866 (cond
14867 ((= c ?\r) (throw 'exit t))
14868 ((= c ?!)
14869 (setq groups (not groups))
14870 (goto-char (point-min))
14871 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14872 ((= c ?\C-c)
14873 (if (not expert)
14874 (org-fast-tag-show-exit
14875 (setq exit-after-next (not exit-after-next)))
14876 (setq expert nil)
14877 (delete-other-windows)
14878 (set-window-buffer (split-window-vertically) " *Org tags*")
14879 (org-switch-to-buffer-other-window " *Org tags*")
14880 (org-fit-window-to-buffer)))
14881 ((or (= c ?\C-g)
14882 (and (= c ?q) (not (rassoc c ntable))))
14883 (org-detach-overlay org-tags-overlay)
14884 (setq quit-flag t))
14885 ((= c ?\ )
14886 (setq current nil)
14887 (if exit-after-next (setq exit-after-next 'now)))
14888 ((= c ?\t)
14889 (condition-case nil
14890 (setq tg (org-icompleting-read
14891 "Tag: "
14892 (or buffer-tags
14893 (with-current-buffer buf
14894 (org-get-buffer-tags)))))
14895 (quit (setq tg "")))
14896 (when (string-match "\\S-" tg)
14897 (add-to-list 'buffer-tags (list tg))
14898 (if (member tg current)
14899 (setq current (delete tg current))
14900 (push tg current)))
14901 (if exit-after-next (setq exit-after-next 'now)))
14902 ((setq e (rassoc c todo-table) tg (car e))
14903 (with-current-buffer buf
14904 (save-excursion (org-todo tg)))
14905 (if exit-after-next (setq exit-after-next 'now)))
14906 ((setq e (rassoc c ntable) tg (car e))
14907 (if (member tg current)
14908 (setq current (delete tg current))
14909 (loop for g in groups do
14910 (if (member tg g)
14911 (mapc (lambda (x)
14912 (setq current (delete x current)))
14913 g)))
14914 (push tg current))
14915 (if exit-after-next (setq exit-after-next 'now))))
14917 ;; Create a sorted list
14918 (setq current
14919 (sort current
14920 (lambda (a b)
14921 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14922 (if (eq exit-after-next 'now) (throw 'exit t))
14923 (goto-char (point-min))
14924 (beginning-of-line 2)
14925 (delete-region (point) (point-at-eol))
14926 (org-fast-tag-insert "Current" current c-face)
14927 (org-set-current-tags-overlay current ov-prefix)
14928 (while (re-search-forward
14929 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14930 (setq tg (match-string 1))
14931 (add-text-properties
14932 (match-beginning 1) (match-end 1)
14933 (list 'face
14934 (cond
14935 ((member tg current) c-face)
14936 ((member tg inherited) i-face)
14937 (t (get-text-property (match-beginning 1) 'face))))))
14938 (goto-char (point-min)))))
14939 (org-detach-overlay org-tags-overlay)
14940 (if rtn
14941 (mapconcat 'identity current ":")
14942 nil))))
14944 (defun org-get-tags-string ()
14945 "Get the TAGS string in the current headline."
14946 (unless (org-at-heading-p t)
14947 (user-error "Not on a heading"))
14948 (save-excursion
14949 (beginning-of-line 1)
14950 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14951 (org-match-string-no-properties 1)
14952 "")))
14954 (defun org-get-tags ()
14955 "Get the list of tags specified in the current headline."
14956 (org-split-string (org-get-tags-string) ":"))
14958 (defun org-get-buffer-tags ()
14959 "Get a table of all tags used in the buffer, for completion."
14960 (let (tags)
14961 (save-excursion
14962 (goto-char (point-min))
14963 (while (re-search-forward
14964 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14965 (when (equal (char-after (point-at-bol 0)) ?*)
14966 (mapc (lambda (x) (add-to-list 'tags x))
14967 (org-split-string (org-match-string-no-properties 1) ":")))))
14968 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14969 (mapcar 'list tags)))
14971 ;;;; The mapping API
14973 (defun org-map-entries (func &optional match scope &rest skip)
14974 "Call FUNC at each headline selected by MATCH in SCOPE.
14976 FUNC is a function or a lisp form. The function will be called without
14977 arguments, with the cursor positioned at the beginning of the headline.
14978 The return values of all calls to the function will be collected and
14979 returned as a list.
14981 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14982 does not need to preserve point. After evaluation, the cursor will be
14983 moved to the end of the line (presumably of the headline of the
14984 processed entry) and search continues from there. Under some
14985 circumstances, this may not produce the wanted results. For example,
14986 if you have removed (e.g. archived) the current (sub)tree it could
14987 mean that the next entry will be skipped entirely. In such cases, you
14988 can specify the position from where search should continue by making
14989 FUNC set the variable `org-map-continue-from' to the desired buffer
14990 position.
14992 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14993 Only headlines that are matched by this query will be considered during
14994 the iteration. When MATCH is nil or t, all headlines will be
14995 visited by the iteration.
14997 SCOPE determines the scope of this command. It can be any of:
14999 nil The current buffer, respecting the restriction if any
15000 tree The subtree started with the entry at point
15001 region The entries within the active region, if any
15002 region-start-level
15003 The entries within the active region, but only those at
15004 the same level than the first one.
15005 file The current buffer, without restriction
15006 file-with-archives
15007 The current buffer, and any archives associated with it
15008 agenda All agenda files
15009 agenda-with-archives
15010 All agenda files with any archive files associated with them
15011 \(file1 file2 ...)
15012 If this is a list, all files in the list will be scanned
15014 The remaining args are treated as settings for the skipping facilities of
15015 the scanner. The following items can be given here:
15017 archive skip trees with the archive tag
15018 comment skip trees with the COMMENT keyword
15019 function or Emacs Lisp form:
15020 will be used as value for `org-agenda-skip-function', so
15021 whenever the function returns a position, FUNC will not be
15022 called for that entry and search will continue from the
15023 position returned
15025 If your function needs to retrieve the tags including inherited tags
15026 at the *current* entry, you can use the value of the variable
15027 `org-scanner-tags' which will be much faster than getting the value
15028 with `org-get-tags-at'. If your function gets properties with
15029 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15030 to t around the call to `org-entry-properties' to get the same speedup.
15031 Note that if your function moves around to retrieve tags and properties at
15032 a *different* entry, you cannot use these techniques."
15033 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15034 (not (org-region-active-p)))
15035 (let* ((org-agenda-archives-mode nil) ; just to make sure
15036 (org-agenda-skip-archived-trees (memq 'archive skip))
15037 (org-agenda-skip-comment-trees (memq 'comment skip))
15038 (org-agenda-skip-function
15039 (car (org-delete-all '(comment archive) skip)))
15040 (org-tags-match-list-sublevels t)
15041 (start-level (eq scope 'region-start-level))
15042 matcher file res
15043 org-todo-keywords-for-agenda
15044 org-done-keywords-for-agenda
15045 org-todo-keyword-alist-for-agenda
15046 org-tag-alist-for-agenda
15047 todo-only)
15049 (cond
15050 ((eq match t) (setq matcher t))
15051 ((eq match nil) (setq matcher t))
15052 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15054 (save-window-excursion
15055 (save-restriction
15056 (cond ((eq scope 'tree)
15057 (org-back-to-heading t)
15058 (org-narrow-to-subtree)
15059 (setq scope nil))
15060 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15061 (org-region-active-p))
15062 ;; If needed, set start-level to a string like "2"
15063 (when start-level
15064 (save-excursion
15065 (goto-char (region-beginning))
15066 (unless (org-at-heading-p) (outline-next-heading))
15067 (setq start-level (org-current-level))))
15068 (narrow-to-region (region-beginning)
15069 (save-excursion
15070 (goto-char (region-end))
15071 (unless (and (bolp) (org-at-heading-p))
15072 (outline-next-heading))
15073 (point)))
15074 (setq scope nil)))
15076 (if (not scope)
15077 (progn
15078 (org-agenda-prepare-buffers
15079 (list (buffer-file-name (current-buffer))))
15080 (setq res (org-scan-tags func matcher todo-only start-level)))
15081 ;; Get the right scope
15082 (cond
15083 ((and scope (listp scope) (symbolp (car scope)))
15084 (setq scope (eval scope)))
15085 ((eq scope 'agenda)
15086 (setq scope (org-agenda-files t)))
15087 ((eq scope 'agenda-with-archives)
15088 (setq scope (org-agenda-files t))
15089 (setq scope (org-add-archive-files scope)))
15090 ((eq scope 'file)
15091 (setq scope (list (buffer-file-name))))
15092 ((eq scope 'file-with-archives)
15093 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15094 (org-agenda-prepare-buffers scope)
15095 (while (setq file (pop scope))
15096 (with-current-buffer (org-find-base-buffer-visiting file)
15097 (save-excursion
15098 (save-restriction
15099 (widen)
15100 (goto-char (point-min))
15101 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
15102 res)))
15104 ;;;; Properties
15106 ;;; Setting and retrieving properties
15108 (defconst org-special-properties
15109 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
15110 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
15111 "The special properties valid in Org-mode.
15113 These are properties that are not defined in the property drawer,
15114 but in some other way.")
15116 (defconst org-default-properties
15117 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15118 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15119 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15120 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15121 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
15122 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15123 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15124 "Some properties that are used by Org-mode for various purposes.
15125 Being in this list makes sure that they are offered for completion.")
15127 (defun org-property-action ()
15128 "Do an action on properties."
15129 (interactive)
15130 (let (c)
15131 (org-at-property-p)
15132 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15133 (setq c (read-char-exclusive))
15134 (cond
15135 ((equal c ?s)
15136 (call-interactively 'org-set-property))
15137 ((equal c ?d)
15138 (call-interactively 'org-delete-property))
15139 ((equal c ?D)
15140 (call-interactively 'org-delete-property-globally))
15141 ((equal c ?c)
15142 (call-interactively 'org-compute-property-at-point))
15143 (t (user-error "No such property action %c" c)))))
15145 (defun org-inc-effort ()
15146 "Increment the value of the effort property in the current entry."
15147 (interactive)
15148 (org-set-effort nil t))
15150 (defvar org-clock-effort) ;; Defined in org-clock.el
15151 (defvar org-clock-current-task) ;; Defined in org-clock.el
15152 (defun org-set-effort (&optional value increment)
15153 "Set the effort property of the current entry.
15154 With numerical prefix arg, use the nth allowed value, 0 stands for the
15155 10th allowed value.
15157 When INCREMENT is non-nil, set the property to the next allowed value."
15158 (interactive "P")
15159 (if (equal value 0) (setq value 10))
15160 (let* ((completion-ignore-case t)
15161 (prop org-effort-property)
15162 (cur (org-entry-get nil prop))
15163 (allowed (org-property-get-allowed-values nil prop 'table))
15164 (existing (mapcar 'list (org-property-values prop)))
15165 (heading (nth 4 (org-heading-components)))
15167 (val (cond
15168 ((stringp value) value)
15169 ((and allowed (integerp value))
15170 (or (car (nth (1- value) allowed))
15171 (car (org-last allowed))))
15172 ((and allowed increment)
15173 (or (caadr (member (list cur) allowed))
15174 (user-error "Allowed effort values are not set")))
15175 (allowed
15176 (message "Select 1-9,0, [RET%s]: %s"
15177 (if cur (concat "=" cur) "")
15178 (mapconcat 'car allowed " "))
15179 (setq rpl (read-char-exclusive))
15180 (if (equal rpl ?\r)
15182 (setq rpl (- rpl ?0))
15183 (if (equal rpl 0) (setq rpl 10))
15184 (if (and (> rpl 0) (<= rpl (length allowed)))
15185 (car (nth (1- rpl) allowed))
15186 (org-completing-read "Effort: " allowed nil))))
15188 (let (org-completion-use-ido org-completion-use-iswitchb)
15189 (org-completing-read
15190 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15191 (concat "[" cur "]") "")
15192 ": ")
15193 existing nil nil "" nil cur))))))
15194 (unless (equal (org-entry-get nil prop) val)
15195 (org-entry-put nil prop val))
15196 (save-excursion
15197 (org-back-to-heading t)
15198 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
15199 (when (string= heading org-clock-current-task)
15200 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
15201 (org-clock-update-mode-line))
15202 (message "%s is now %s" prop val)))
15204 (defun org-at-property-p ()
15205 "Is cursor inside a property drawer?"
15206 (save-excursion
15207 (when (equal 'node-property (car (org-element-at-point)))
15208 (beginning-of-line 1)
15209 (looking-at org-property-re))))
15211 (defun org-get-property-block (&optional beg end force)
15212 "Return the (beg . end) range of the body of the property drawer.
15213 BEG and END are the beginning and end of the current subtree, or of
15214 the part before the first headline. If they are not given, they will
15215 be found. If the drawer does not exist and FORCE is non-nil, create
15216 the drawer."
15217 (catch 'exit
15218 (save-excursion
15219 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15220 (progn (org-back-to-heading t) (point))))
15221 (end (or end (and (not (outline-next-heading)) (point-max))
15222 (point))))
15223 (goto-char beg)
15224 (if (re-search-forward org-property-start-re end t)
15225 (setq beg (1+ (match-end 0)))
15226 (if force
15227 (save-excursion
15228 (org-insert-property-drawer)
15229 (setq end (progn (outline-next-heading) (point))))
15230 (throw 'exit nil))
15231 (goto-char beg)
15232 (if (re-search-forward org-property-start-re end t)
15233 (setq beg (1+ (match-end 0)))))
15234 (if (re-search-forward org-property-end-re end t)
15235 (setq end (match-beginning 0))
15236 (or force (throw 'exit nil))
15237 (goto-char beg)
15238 (setq end beg)
15239 (org-indent-line)
15240 (insert ":END:\n"))
15241 (cons beg end)))))
15243 (defun org-entry-properties (&optional pom which specific)
15244 "Get all properties of the entry at point-or-marker POM.
15245 This includes the TODO keyword, the tags, time strings for deadline,
15246 scheduled, and clocking, and any additional properties defined in the
15247 entry. The return value is an alist, keys may occur multiple times
15248 if the property key was used several times.
15249 POM may also be nil, in which case the current entry is used.
15250 If WHICH is nil or `all', get all properties. If WHICH is
15251 `special' or `standard', only get that subclass. If WHICH
15252 is a string only get exactly this property. SPECIFIC can be a string, the
15253 specific property we are interested in. Specifying it can speed
15254 things up because then unnecessary parsing is avoided."
15255 (setq which (or which 'all))
15256 (org-with-wide-buffer
15257 (org-with-point-at pom
15258 (let ((clockstr (substring org-clock-string 0 -1))
15259 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15260 (case-fold-search nil)
15261 beg end range props sum-props key key1 value string clocksum clocksumt)
15262 (when (and (derived-mode-p 'org-mode)
15263 (ignore-errors (org-back-to-heading t)))
15264 (setq beg (point))
15265 (setq sum-props (get-text-property (point) 'org-summaries))
15266 (setq clocksum (get-text-property (point) :org-clock-minutes)
15267 clocksumt (get-text-property (point) :org-clock-minutes-today))
15268 (outline-next-heading)
15269 (setq end (point))
15270 (when (memq which '(all special))
15271 ;; Get the special properties, like TODO and tags
15272 (goto-char beg)
15273 (when (and (or (not specific) (string= specific "TODO"))
15274 (looking-at org-todo-line-regexp) (match-end 2))
15275 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15276 (when (and (or (not specific) (string= specific "PRIORITY"))
15277 (looking-at org-priority-regexp))
15278 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15279 (when (or (not specific) (string= specific "FILE"))
15280 (push (cons "FILE" buffer-file-name) props))
15281 (when (and (or (not specific) (string= specific "TAGS"))
15282 (setq value (org-get-tags-string))
15283 (string-match "\\S-" value))
15284 (push (cons "TAGS" value) props))
15285 (when (and (or (not specific) (string= specific "ALLTAGS"))
15286 (setq value (org-get-tags-at)))
15287 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15288 ":"))
15289 props))
15290 (when (or (not specific) (string= specific "BLOCKED"))
15291 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15292 (when (or (not specific)
15293 (member specific
15294 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15295 "TIMESTAMP" "TIMESTAMP_IA")))
15296 (catch 'match
15297 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15298 (setq key (if (match-end 1)
15299 (substring (org-match-string-no-properties 1)
15300 0 -1))
15301 string (if (equal key clockstr)
15302 (org-trim
15303 (buffer-substring-no-properties
15304 (match-beginning 3) (goto-char
15305 (point-at-eol))))
15306 (substring (org-match-string-no-properties 3)
15307 1 -1)))
15308 ;; Get the correct property name from the key. This is
15309 ;; necessary if the user has configured time keywords.
15310 (setq key1 (concat key ":"))
15311 (cond
15312 ((not key)
15313 (setq key
15314 (if (= (char-after (match-beginning 3)) ?\[)
15315 "TIMESTAMP_IA" "TIMESTAMP")))
15316 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15317 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15318 ((equal key1 org-closed-string) (setq key "CLOSED"))
15319 ((equal key1 org-clock-string) (setq key "CLOCK")))
15320 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15321 (progn
15322 (push (cons key string) props)
15323 ;; no need to search further if match is found
15324 (throw 'match t))
15325 (when (or (equal key "CLOCK") (not (assoc key props)))
15326 (push (cons key string) props)))))))
15328 (when (memq which '(all standard))
15329 ;; Get the standard properties, like :PROP: ...
15330 (setq range (org-get-property-block beg end))
15331 (when range
15332 (goto-char (car range))
15333 (while (re-search-forward org-property-re
15334 (cdr range) t)
15335 (setq key (org-match-string-no-properties 2)
15336 value (org-trim (or (org-match-string-no-properties 3) "")))
15337 (unless (member key excluded)
15338 (push (cons key (or value "")) props)))))
15339 (if clocksum
15340 (push (cons "CLOCKSUM"
15341 (org-columns-number-to-string (/ (float clocksum) 60.)
15342 'add_times))
15343 props))
15344 (if clocksumt
15345 (push (cons "CLOCKSUM_T"
15346 (org-columns-number-to-string (/ (float clocksumt) 60.)
15347 'add_times))
15348 props))
15349 (unless (assoc "CATEGORY" props)
15350 (push (cons "CATEGORY" (org-get-category)) props))
15351 (append sum-props (nreverse props)))))))
15353 (defun org-entry-get (pom property &optional inherit literal-nil)
15354 "Get value of PROPERTY for entry or content at point-or-marker POM.
15355 If INHERIT is non-nil and the entry does not have the property,
15356 then also check higher levels of the hierarchy.
15357 If INHERIT is the symbol `selective', use inheritance only if the setting
15358 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15359 If the property is present but empty, the return value is the empty string.
15360 If the property is not present at all, nil is returned.
15362 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15363 do not interpret it as the list atom nil. This is used for inheritance
15364 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15365 (org-with-point-at pom
15366 (if (and inherit (if (eq inherit 'selective)
15367 (org-property-inherit-p property)
15369 (org-entry-get-with-inheritance property literal-nil)
15370 (if (member property org-special-properties)
15371 ;; We need a special property. Use `org-entry-properties'
15372 ;; to retrieve it, but specify the wanted property
15373 (cdr (assoc property (org-entry-properties nil 'special property)))
15374 (org-with-wide-buffer
15375 (let ((range (org-get-property-block)))
15376 (when (and range (not (eq (car range) (cdr range))))
15377 (let* ((props
15378 (list (or (assoc property org-file-properties)
15379 (assoc property org-global-properties)
15380 (assoc property org-global-properties-fixed))))
15381 (ap (lambda (key)
15382 (when (re-search-forward
15383 (org-re-property key) (cdr range) t)
15384 (setq props
15385 (org-update-property-plist
15387 (if (match-end 3)
15388 (org-match-string-no-properties 3) "")
15389 props)))))
15390 val)
15391 (goto-char (car range))
15392 (funcall ap property)
15393 (goto-char (car range))
15394 (while (funcall ap (concat property "+")))
15395 (setq val (cdr (assoc property props)))
15396 (when val (if literal-nil val (org-not-nil val)))))))))))
15398 (defun org-property-or-variable-value (var &optional inherit)
15399 "Check if there is a property fixing the value of VAR.
15400 If yes, return this value. If not, return the current value of the variable."
15401 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15402 (if (and prop (stringp prop) (string-match "\\S-" prop))
15403 (read prop)
15404 (symbol-value var))))
15406 (defun org-entry-delete (pom property)
15407 "Delete the property PROPERTY from entry at point-or-marker POM."
15408 (unless (member property org-special-properties)
15409 (org-with-point-at pom
15410 (let ((range (org-get-property-block)))
15411 (if (and range
15412 (goto-char (car range))
15413 (re-search-forward
15414 (org-re-property property)
15415 (cdr range) t))
15416 (progn
15417 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15418 (org-remove-empty-drawer-at (car range))
15420 nil)))))
15422 ;; Multi-values properties are properties that contain multiple values
15423 ;; These values are assumed to be single words, separated by whitespace.
15424 (defun org-entry-add-to-multivalued-property (pom property value)
15425 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15426 (let* ((old (org-entry-get pom property))
15427 (values (and old (org-split-string old "[ \t]"))))
15428 (setq value (org-entry-protect-space value))
15429 (unless (member value values)
15430 (setq values (append values (list value)))
15431 (org-entry-put pom property
15432 (mapconcat 'identity values " ")))))
15434 (defun org-entry-remove-from-multivalued-property (pom property value)
15435 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15436 (let* ((old (org-entry-get pom property))
15437 (values (and old (org-split-string old "[ \t]"))))
15438 (setq value (org-entry-protect-space value))
15439 (when (member value values)
15440 (setq values (delete value values))
15441 (org-entry-put pom property
15442 (mapconcat 'identity values " ")))))
15444 (defun org-entry-member-in-multivalued-property (pom property value)
15445 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15446 (let* ((old (org-entry-get pom property))
15447 (values (and old (org-split-string old "[ \t]"))))
15448 (setq value (org-entry-protect-space value))
15449 (member value values)))
15451 (defun org-entry-get-multivalued-property (pom property)
15452 "Return a list of values in a multivalued property."
15453 (let* ((value (org-entry-get pom property))
15454 (values (and value (org-split-string value "[ \t]"))))
15455 (mapcar 'org-entry-restore-space values)))
15457 (defun org-entry-put-multivalued-property (pom property &rest values)
15458 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15459 VALUES should be a list of strings. Spaces will be protected."
15460 (org-entry-put pom property
15461 (mapconcat 'org-entry-protect-space values " "))
15462 (let* ((value (org-entry-get pom property))
15463 (values (and value (org-split-string value "[ \t]"))))
15464 (mapcar 'org-entry-restore-space values)))
15466 (defun org-entry-protect-space (s)
15467 "Protect spaces and newline in string S."
15468 (while (string-match " " s)
15469 (setq s (replace-match "%20" t t s)))
15470 (while (string-match "\n" s)
15471 (setq s (replace-match "%0A" t t s)))
15474 (defun org-entry-restore-space (s)
15475 "Restore spaces and newline in string S."
15476 (while (string-match "%20" s)
15477 (setq s (replace-match " " t t s)))
15478 (while (string-match "%0A" s)
15479 (setq s (replace-match "\n" t t s)))
15482 (defvar org-entry-property-inherited-from (make-marker)
15483 "Marker pointing to the entry from where a property was inherited.
15484 Each call to `org-entry-get-with-inheritance' will set this marker to the
15485 location of the entry where the inheritance search matched. If there was
15486 no match, the marker will point nowhere.
15487 Note that also `org-entry-get' calls this function, if the INHERIT flag
15488 is set.")
15490 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15491 "Get PROPERTY of entry or content at point, search higher levels if needed.
15492 The search will stop at the first ancestor which has the property defined.
15493 If the value found is \"nil\", return nil to show that the property
15494 should be considered as undefined (this is the meaning of nil here).
15495 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15496 (move-marker org-entry-property-inherited-from nil)
15497 (let (tmp)
15498 (save-excursion
15499 (save-restriction
15500 (widen)
15501 (catch 'ex
15502 (while t
15503 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
15504 (or (ignore-errors (org-back-to-heading t))
15505 (goto-char (point-min)))
15506 (move-marker org-entry-property-inherited-from (point))
15507 (throw 'ex tmp))
15508 (or (ignore-errors (org-up-heading-safe))
15509 (throw 'ex nil))))))
15510 (setq tmp (or tmp
15511 (cdr (assoc property org-file-properties))
15512 (cdr (assoc property org-global-properties))
15513 (cdr (assoc property org-global-properties-fixed))))
15514 (if literal-nil tmp (org-not-nil tmp))))
15516 (defvar org-property-changed-functions nil
15517 "Hook called when the value of a property has changed.
15518 Each hook function should accept two arguments, the name of the property
15519 and the new value.")
15521 (defun org-entry-put (pom property value)
15522 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15523 (org-with-point-at pom
15524 (org-back-to-heading t)
15525 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15526 range)
15527 (cond
15528 ((equal property "TODO")
15529 (when (and (stringp value) (string-match "\\S-" value)
15530 (not (member value org-todo-keywords-1)))
15531 (user-error "\"%s\" is not a valid TODO state" value))
15532 (if (or (not value)
15533 (not (string-match "\\S-" value)))
15534 (setq value 'none))
15535 (org-todo value)
15536 (org-set-tags nil 'align))
15537 ((equal property "PRIORITY")
15538 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15539 (string-to-char value) ?\ ))
15540 (org-set-tags nil 'align))
15541 ((equal property "CLOCKSUM")
15542 (if (not (re-search-forward
15543 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15544 (error "Cannot find a clock log")
15545 (goto-char (- (match-end 1) 2))
15546 (cond
15547 ((eq value 'earlier) (org-timestamp-down))
15548 ((eq value 'later) (org-timestamp-up)))
15549 (org-clock-sum-current-item)))
15550 ((equal property "SCHEDULED")
15551 (if (re-search-forward org-scheduled-time-regexp end t)
15552 (cond
15553 ((eq value 'earlier) (org-timestamp-change -1 'day))
15554 ((eq value 'later) (org-timestamp-change 1 'day))
15555 (t (call-interactively 'org-schedule)))
15556 (call-interactively 'org-schedule)))
15557 ((equal property "DEADLINE")
15558 (if (re-search-forward org-deadline-time-regexp end t)
15559 (cond
15560 ((eq value 'earlier) (org-timestamp-change -1 'day))
15561 ((eq value 'later) (org-timestamp-change 1 'day))
15562 (t (call-interactively 'org-deadline)))
15563 (call-interactively 'org-deadline)))
15564 ((member property org-special-properties)
15565 (error "The %s property can not yet be set with `org-entry-put'"
15566 property))
15567 (t ; a non-special property
15568 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15569 (setq range (org-get-property-block beg end 'force))
15570 (goto-char (car range))
15571 (if (re-search-forward
15572 (org-re-property property) (cdr range) t)
15573 (progn
15574 (delete-region (match-beginning 0) (match-end 0))
15575 (goto-char (match-beginning 0)))
15576 (goto-char (cdr range))
15577 (insert "\n")
15578 (backward-char 1)
15579 (org-indent-line))
15580 (insert ":" property ":")
15581 (and value (insert " " value))
15582 (org-indent-line)))))
15583 (run-hook-with-args 'org-property-changed-functions property value)))
15585 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15586 "Get all property keys in the current buffer.
15587 With INCLUDE-SPECIALS, also list the special properties that reflect things
15588 like tags and TODO state.
15589 With INCLUDE-DEFAULTS, also include properties that has special meaning
15590 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15591 and others.
15592 With INCLUDE-COLUMNS, also include property names given in COLUMN
15593 formats in the current buffer."
15594 (let (rtn range cfmt s p)
15595 (save-excursion
15596 (save-restriction
15597 (widen)
15598 (goto-char (point-min))
15599 (while (re-search-forward org-property-start-re nil t)
15600 (setq range (org-get-property-block))
15601 (goto-char (car range))
15602 (while (re-search-forward org-property-re
15603 (cdr range) t)
15604 (add-to-list 'rtn (org-match-string-no-properties 2)))
15605 (outline-next-heading))))
15607 (when include-specials
15608 (setq rtn (append org-special-properties rtn)))
15610 (when include-defaults
15611 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15612 (add-to-list 'rtn org-effort-property))
15614 (when include-columns
15615 (save-excursion
15616 (save-restriction
15617 (widen)
15618 (goto-char (point-min))
15619 (while (re-search-forward
15620 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15621 nil t)
15622 (setq cfmt (match-string 2) s 0)
15623 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15624 cfmt s)
15625 (setq s (match-end 0)
15626 p (match-string 1 cfmt))
15627 (unless (or (equal p "ITEM")
15628 (member p org-special-properties))
15629 (add-to-list 'rtn (match-string 1 cfmt))))))))
15631 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15633 (defun org-property-values (key)
15634 "Return a list of all values of property KEY in the current buffer."
15635 (save-excursion
15636 (save-restriction
15637 (widen)
15638 (goto-char (point-min))
15639 (let ((re (org-re-property key))
15640 values)
15641 (while (re-search-forward re nil t)
15642 (add-to-list 'values (org-trim (match-string 3))))
15643 (delete "" values)))))
15645 (defun org-insert-property-drawer ()
15646 "Insert a property drawer into the current entry."
15647 (org-back-to-heading t)
15648 (looking-at org-outline-regexp)
15649 (let ((indent (if org-adapt-indentation
15650 (- (match-end 0) (match-beginning 0))
15652 (beg (point))
15653 (re (concat "^[ \t]*" org-keyword-time-regexp))
15654 end hiddenp)
15655 (outline-next-heading)
15656 (setq end (point))
15657 (goto-char beg)
15658 (while (re-search-forward re end t))
15659 (setq hiddenp (outline-invisible-p))
15660 (end-of-line 1)
15661 (and (equal (char-after) ?\n) (forward-char 1))
15662 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15663 (if (member (match-string 1) '("CLOCK:" ":END:"))
15664 ;; just skip this line
15665 (beginning-of-line 2)
15666 ;; Drawer start, find the end
15667 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15668 (beginning-of-line 1)))
15669 (org-skip-over-state-notes)
15670 (skip-chars-backward " \t\n\r")
15671 (if (and (eq (char-before) ?*) (not (eq (char-after) ?\n)))
15672 (forward-char 1))
15673 (goto-char (point-at-eol))
15674 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15675 (beginning-of-line 0)
15676 (org-indent-to-column indent)
15677 (beginning-of-line 2)
15678 (org-indent-to-column indent)
15679 (beginning-of-line 0)
15680 (if hiddenp
15681 (save-excursion
15682 (org-back-to-heading t)
15683 (hide-entry))
15684 (org-flag-drawer t))))
15686 (defun org-insert-drawer (&optional arg drawer)
15687 "Insert a drawer at point.
15689 Optional argument DRAWER, when non-nil, is a string representing
15690 drawer's name. Otherwise, the user is prompted for a name.
15692 If a region is active, insert the drawer around that region
15693 instead.
15695 Point is left between drawer's boundaries."
15696 (interactive "P")
15697 (let* ((drawer (if arg "PROPERTIES"
15698 (or drawer (read-from-minibuffer "Drawer: ")))))
15699 (cond
15700 ;; With C-u, fall back on `org-insert-property-drawer'
15701 (arg (org-insert-property-drawer))
15703 ((not (org-string-match-p org-drawer-regexp (format ":%s:" drawer)))
15704 (user-error "Invalid drawer name"))
15705 ;; With an active region, insert a drawer at point.
15706 ((not (org-region-active-p))
15707 (progn
15708 (unless (bolp) (insert "\n"))
15709 (insert (format ":%s:\n\n:END:\n" drawer))
15710 (forward-line -2)))
15711 ;; Otherwise, insert the drawer at point
15713 (let ((rbeg (region-beginning))
15714 (rend (copy-marker (region-end))))
15715 (unwind-protect
15716 (progn
15717 (goto-char rbeg)
15718 (beginning-of-line)
15719 (when (save-excursion
15720 (re-search-forward org-outline-regexp-bol rend t))
15721 (user-error "Drawers cannot contain headlines"))
15722 ;; Position point at the beginning of the first
15723 ;; non-blank line in region. Insert drawer's opening
15724 ;; there, then indent it.
15725 (org-skip-whitespace)
15726 (beginning-of-line)
15727 (insert ":" drawer ":\n")
15728 (forward-line -1)
15729 (indent-for-tab-command)
15730 ;; Move point to the beginning of the first blank line
15731 ;; after the last non-blank line in region. Insert
15732 ;; drawer's closing, then indent it.
15733 (goto-char rend)
15734 (skip-chars-backward " \r\t\n")
15735 (insert "\n:END:")
15736 (deactivate-mark t)
15737 (indent-for-tab-command)
15738 (unless (eolp) (insert "\n")))
15739 ;; Clear marker, whatever the outcome of insertion is.
15740 (set-marker rend nil)))))))
15742 (defvar org-property-set-functions-alist nil
15743 "Property set function alist.
15744 Each entry should have the following format:
15746 (PROPERTY . READ-FUNCTION)
15748 The read function will be called with the same argument as
15749 `org-completing-read'.")
15751 (defun org-set-property-function (property)
15752 "Get the function that should be used to set PROPERTY.
15753 This is computed according to `org-property-set-functions-alist'."
15754 (or (cdr (assoc property org-property-set-functions-alist))
15755 'org-completing-read))
15757 (defun org-read-property-value (property)
15758 "Read PROPERTY value from user."
15759 (let* ((completion-ignore-case t)
15760 (allowed (org-property-get-allowed-values nil property 'table))
15761 (cur (org-entry-get nil property))
15762 (prompt (concat property " value"
15763 (if (and cur (string-match "\\S-" cur))
15764 (concat " [" cur "]") "") ": "))
15765 (set-function (org-set-property-function property))
15766 (val (if allowed
15767 (funcall set-function prompt allowed nil
15768 (not (get-text-property 0 'org-unrestricted
15769 (caar allowed))))
15770 (let (org-completion-use-ido org-completion-use-iswitchb)
15771 (funcall set-function prompt
15772 (mapcar 'list (org-property-values property))
15773 nil nil "" nil cur)))))
15774 (if (equal val "")
15776 val)))
15778 (defvar org-last-set-property nil)
15779 (defvar org-last-set-property-value nil)
15780 (defun org-read-property-name ()
15781 "Read a property name."
15782 (let* ((completion-ignore-case t)
15783 (keys (org-buffer-property-keys nil t t))
15784 (default-prop (or (save-excursion
15785 (save-match-data
15786 (beginning-of-line)
15787 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15788 (null (string= (match-string 1) "END"))
15789 (match-string 1))))
15790 org-last-set-property))
15791 (property (org-icompleting-read
15792 (concat "Property"
15793 (if default-prop (concat " [" default-prop "]") "")
15794 ": ")
15795 (mapcar 'list keys)
15796 nil nil nil nil
15797 default-prop)))
15798 (if (member property keys)
15799 property
15800 (or (cdr (assoc (downcase property)
15801 (mapcar (lambda (x) (cons (downcase x) x))
15802 keys)))
15803 property))))
15805 (defun org-set-property-and-value (use-last)
15806 "Allow to set [PROPERTY]: [value] direction from prompt.
15807 When use-default, don't even ask, just use the last
15808 \"[PROPERTY]: [value]\" string from the history."
15809 (interactive "P")
15810 (let* ((completion-ignore-case t)
15811 (pv (or (and use-last org-last-set-property-value)
15812 (org-completing-read
15813 "Enter a \"[Property]: [value]\" pair: "
15814 nil nil nil nil nil
15815 org-last-set-property-value)))
15816 prop val)
15817 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15818 (setq prop (match-string 1 pv)
15819 val (match-string 2 pv))
15820 (org-set-property prop val))))
15822 (defun org-set-property (property value)
15823 "In the current entry, set PROPERTY to VALUE.
15824 When called interactively, this will prompt for a property name, offering
15825 completion on existing and default properties. And then it will prompt
15826 for a value, offering completion either on allowed values (via an inherited
15827 xxx_ALL property) or on existing values in other instances of this property
15828 in the current file."
15829 (interactive (list nil nil))
15830 (let* ((property (or property (org-read-property-name)))
15831 (value (or value (org-read-property-value property)))
15832 (fn (cdr (assoc property org-properties-postprocess-alist))))
15833 (setq org-last-set-property property)
15834 (setq org-last-set-property-value (concat property ": " value))
15835 ;; Possibly postprocess the inserted value:
15836 (when fn (setq value (funcall fn value)))
15837 (unless (equal (org-entry-get nil property) value)
15838 (org-entry-put nil property value))))
15840 (defun org-delete-property (property)
15841 "In the current entry, delete PROPERTY."
15842 (interactive
15843 (let* ((completion-ignore-case t)
15844 (prop (org-icompleting-read "Property: "
15845 (org-entry-properties nil 'standard))))
15846 (list prop)))
15847 (message "Property %s %s" property
15848 (if (org-entry-delete nil property)
15849 "deleted"
15850 "was not present in the entry")))
15852 (defun org-delete-property-globally (property)
15853 "Remove PROPERTY globally, from all entries."
15854 (interactive
15855 (let* ((completion-ignore-case t)
15856 (prop (org-icompleting-read
15857 "Globally remove property: "
15858 (mapcar 'list (org-buffer-property-keys)))))
15859 (list prop)))
15860 (save-excursion
15861 (save-restriction
15862 (widen)
15863 (goto-char (point-min))
15864 (let ((cnt 0))
15865 (while (re-search-forward
15866 (org-re-property property)
15867 nil t)
15868 (setq cnt (1+ cnt))
15869 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15870 (message "Property \"%s\" removed from %d entries" property cnt)))))
15872 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15874 (defun org-compute-property-at-point ()
15875 "Compute the property at point.
15876 This looks for an enclosing column format, extracts the operator and
15877 then applies it to the property in the column format's scope."
15878 (interactive)
15879 (unless (org-at-property-p)
15880 (user-error "Not at a property"))
15881 (let ((prop (org-match-string-no-properties 2)))
15882 (org-columns-get-format-and-top-level)
15883 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15884 (user-error "No operator defined for property %s" prop))
15885 (org-columns-compute prop)))
15887 (defvar org-property-allowed-value-functions nil
15888 "Hook for functions supplying allowed values for a specific property.
15889 The functions must take a single argument, the name of the property, and
15890 return a flat list of allowed values. If \":ETC\" is one of
15891 the values, this means that these values are intended as defaults for
15892 completion, but that other values should be allowed too.
15893 The functions must return nil if they are not responsible for this
15894 property.")
15896 (defun org-property-get-allowed-values (pom property &optional table)
15897 "Get allowed values for the property PROPERTY.
15898 When TABLE is non-nil, return an alist that can directly be used for
15899 completion."
15900 (let (vals)
15901 (cond
15902 ((equal property "TODO")
15903 (setq vals (org-with-point-at pom
15904 (append org-todo-keywords-1 '("")))))
15905 ((equal property "PRIORITY")
15906 (let ((n org-lowest-priority))
15907 (while (>= n org-highest-priority)
15908 (push (char-to-string n) vals)
15909 (setq n (1- n)))))
15910 ((member property org-special-properties))
15911 ((setq vals (run-hook-with-args-until-success
15912 'org-property-allowed-value-functions property)))
15914 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15915 (when (and vals (string-match "\\S-" vals))
15916 (setq vals (car (read-from-string (concat "(" vals ")"))))
15917 (setq vals (mapcar (lambda (x)
15918 (cond ((stringp x) x)
15919 ((numberp x) (number-to-string x))
15920 ((symbolp x) (symbol-name x))
15921 (t "???")))
15922 vals)))))
15923 (when (member ":ETC" vals)
15924 (setq vals (remove ":ETC" vals))
15925 (org-add-props (car vals) '(org-unrestricted t)))
15926 (if table (mapcar 'list vals) vals)))
15928 (defun org-property-previous-allowed-value (&optional previous)
15929 "Switch to the next allowed value for this property."
15930 (interactive)
15931 (org-property-next-allowed-value t))
15933 (defun org-property-next-allowed-value (&optional previous)
15934 "Switch to the next allowed value for this property."
15935 (interactive)
15936 (unless (org-at-property-p)
15937 (user-error "Not at a property"))
15938 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15939 (key (match-string 2))
15940 (value (match-string 3))
15941 (allowed (or (org-property-get-allowed-values (point) key)
15942 (and (member value '("[ ]" "[-]" "[X]"))
15943 '("[ ]" "[X]"))))
15944 (heading (save-match-data (nth 4 (org-heading-components))))
15945 nval)
15946 (unless allowed
15947 (user-error "Allowed values for this property have not been defined"))
15948 (if previous (setq allowed (reverse allowed)))
15949 (if (member value allowed)
15950 (setq nval (car (cdr (member value allowed)))))
15951 (setq nval (or nval (car allowed)))
15952 (if (equal nval value)
15953 (user-error "Only one allowed value for this property"))
15954 (org-at-property-p)
15955 (replace-match (concat " :" key ": " nval) t t)
15956 (org-indent-line)
15957 (beginning-of-line 1)
15958 (skip-chars-forward " \t")
15959 (when (equal prop org-effort-property)
15960 (save-excursion
15961 (org-back-to-heading t)
15962 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
15963 (when (string= org-clock-current-task heading)
15964 (setq org-clock-effort nval)
15965 (org-clock-update-mode-line)))
15966 (run-hook-with-args 'org-property-changed-functions key nval)))
15968 (defun org-find-olp (path &optional this-buffer)
15969 "Return a marker pointing to the entry at outline path OLP.
15970 If anything goes wrong, throw an error.
15971 You can wrap this call to catch the error like this:
15973 (condition-case msg
15974 (org-mobile-locate-entry (match-string 4))
15975 (error (nth 1 msg)))
15977 The return value will then be either a string with the error message,
15978 or a marker if everything is OK.
15980 If THIS-BUFFER is set, the outline path does not contain a file,
15981 only headings."
15982 (let* ((file (if this-buffer buffer-file-name (pop path)))
15983 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15984 (level 1)
15985 (lmin 1)
15986 (lmax 1)
15987 limit re end found pos heading cnt flevel)
15988 (unless buffer (error "File not found :%s" file))
15989 (with-current-buffer buffer
15990 (save-excursion
15991 (save-restriction
15992 (widen)
15993 (setq limit (point-max))
15994 (goto-char (point-min))
15995 (while (setq heading (pop path))
15996 (setq re (format org-complex-heading-regexp-format
15997 (regexp-quote heading)))
15998 (setq cnt 0 pos (point))
15999 (while (re-search-forward re end t)
16000 (setq level (- (match-end 1) (match-beginning 1)))
16001 (if (and (>= level lmin) (<= level lmax))
16002 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16003 (when (= cnt 0) (error "Heading not found on level %d: %s"
16004 lmax heading))
16005 (when (> cnt 1) (error "Heading not unique on level %d: %s"
16006 lmax heading))
16007 (goto-char found)
16008 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16009 (setq end (save-excursion (org-end-of-subtree t t))))
16010 (when (org-at-heading-p)
16011 (point-marker)))))))
16013 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16014 "Find node HEADING in BUFFER.
16015 Return a marker to the heading if it was found, or nil if not.
16016 If POS-ONLY is set, return just the position instead of a marker.
16018 The heading text must match exact, but it may have a TODO keyword,
16019 a priority cookie and tags in the standard locations."
16020 (with-current-buffer (or buffer (current-buffer))
16021 (save-excursion
16022 (save-restriction
16023 (widen)
16024 (goto-char (point-min))
16025 (let (case-fold-search)
16026 (if (re-search-forward
16027 (format org-complex-heading-regexp-format
16028 (regexp-quote heading)) nil t)
16029 (if pos-only
16030 (match-beginning 0)
16031 (move-marker (make-marker) (match-beginning 0)))))))))
16033 (defun org-find-exact-heading-in-directory (heading &optional dir)
16034 "Find Org node headline HEADING in all .org files in directory DIR.
16035 When the target headline is found, return a marker to this location."
16036 (let ((files (directory-files (or dir default-directory)
16037 nil "\\`[^.#].*\\.org\\'"))
16038 file visiting m buffer)
16039 (catch 'found
16040 (while (setq file (pop files))
16041 (message "trying %s" file)
16042 (setq visiting (org-find-base-buffer-visiting file))
16043 (setq buffer (or visiting (find-file-noselect file)))
16044 (setq m (org-find-exact-headline-in-buffer
16045 heading buffer))
16046 (when (and (not m) (not visiting)) (kill-buffer buffer))
16047 (and m (throw 'found m))))))
16049 (defun org-find-entry-with-id (ident)
16050 "Locate the entry that contains the ID property with exact value IDENT.
16051 IDENT can be a string, a symbol or a number, this function will search for
16052 the string representation of it.
16053 Return the position where this entry starts, or nil if there is no such entry."
16054 (interactive "sID: ")
16055 (let ((id (cond
16056 ((stringp ident) ident)
16057 ((symbol-name ident) (symbol-name ident))
16058 ((numberp ident) (number-to-string ident))
16059 (t (error "IDENT %s must be a string, symbol or number" ident))))
16060 (case-fold-search nil))
16061 (save-excursion
16062 (save-restriction
16063 (widen)
16064 (goto-char (point-min))
16065 (when (re-search-forward
16066 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16067 nil t)
16068 (org-back-to-heading t)
16069 (point))))))
16071 ;;;; Timestamps
16073 (defvar org-last-changed-timestamp nil)
16074 (defvar org-last-inserted-timestamp nil
16075 "The last time stamp inserted with `org-insert-time-stamp'.")
16076 (defvar org-ts-what) ; dynamically scoped parameter
16078 (defun org-time-stamp (arg &optional inactive)
16079 "Prompt for a date/time and insert a time stamp.
16080 If the user specifies a time like HH:MM or if this command is
16081 called with at least one prefix argument, the time stamp contains
16082 the date and the time. Otherwise, only the date is be included.
16084 All parts of a date not specified by the user is filled in from
16085 the current date/time. So if you just press return without
16086 typing anything, the time stamp will represent the current
16087 date/time.
16089 If there is already a timestamp at the cursor, it will be
16090 modified.
16092 With two universal prefix arguments, insert an active timestamp
16093 with the current time without prompting the user.
16095 When called from lisp, the timestamp is inactive if INACTIVE is
16096 non-nil."
16097 (interactive "P")
16098 (let* ((ts nil)
16099 (default-time
16100 ;; Default time is either today, or, when entering a range,
16101 ;; the range start.
16102 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16103 (save-excursion
16104 (re-search-backward
16105 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16106 (- (point) 20) t)))
16107 (apply 'encode-time (org-parse-time-string (match-string 1)))
16108 (current-time)))
16109 (default-input (and ts (org-get-compact-tod ts)))
16110 (repeater (save-excursion
16111 (save-match-data
16112 (beginning-of-line)
16113 (when (re-search-forward
16114 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16115 (save-excursion (progn (end-of-line) (point))) t)
16116 (match-string 0)))))
16117 org-time-was-given org-end-time-was-given time)
16118 (cond
16119 ((and (org-at-timestamp-p t)
16120 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16121 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16122 (insert "--")
16123 (setq time (let ((this-command this-command))
16124 (org-read-date arg 'totime nil nil
16125 default-time default-input inactive)))
16126 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16127 ((org-at-timestamp-p t)
16128 (setq time (let ((this-command this-command))
16129 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16130 (when (org-at-timestamp-p t) ; just to get the match data
16131 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16132 (replace-match "")
16133 (setq org-last-changed-timestamp
16134 (org-insert-time-stamp
16135 time (or org-time-was-given arg)
16136 inactive nil nil (list org-end-time-was-given)))
16137 (when repeater (goto-char (1- (point))) (insert " " repeater)
16138 (setq org-last-changed-timestamp
16139 (concat (substring org-last-inserted-timestamp 0 -1)
16140 " " repeater ">"))))
16141 (message "Timestamp updated"))
16142 ((equal arg '(16))
16143 (org-insert-time-stamp (current-time) t inactive))
16145 (setq time (let ((this-command this-command))
16146 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16147 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16148 nil nil (list org-end-time-was-given))))))
16150 ;; FIXME: can we use this for something else, like computing time differences?
16151 (defun org-get-compact-tod (s)
16152 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16153 (let* ((t1 (match-string 1 s))
16154 (h1 (string-to-number (match-string 2 s)))
16155 (m1 (string-to-number (match-string 3 s)))
16156 (t2 (and (match-end 4) (match-string 5 s)))
16157 (h2 (and t2 (string-to-number (match-string 6 s))))
16158 (m2 (and t2 (string-to-number (match-string 7 s))))
16159 dh dm)
16160 (if (not t2)
16162 (setq dh (- h2 h1) dm (- m2 m1))
16163 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16164 (concat t1 "+" (number-to-string dh)
16165 (and (/= 0 dm) (format ":%02d" dm)))))))
16167 (defun org-time-stamp-inactive (&optional arg)
16168 "Insert an inactive time stamp.
16169 An inactive time stamp is enclosed in square brackets instead of angle
16170 brackets. It is inactive in the sense that it does not trigger agenda entries,
16171 does not link to the calendar and cannot be changed with the S-cursor keys.
16172 So these are more for recording a certain time/date."
16173 (interactive "P")
16174 (org-time-stamp arg 'inactive))
16176 (defvar org-date-ovl (make-overlay 1 1))
16177 (overlay-put org-date-ovl 'face 'org-date-selected)
16178 (org-detach-overlay org-date-ovl)
16180 (defvar org-ans1) ; dynamically scoped parameter
16181 (defvar org-ans2) ; dynamically scoped parameter
16183 (defvar org-plain-time-of-day-regexp) ; defined below
16185 (defvar org-overriding-default-time nil) ; dynamically scoped
16186 (defvar org-read-date-overlay nil)
16187 (defvar org-dcst nil) ; dynamically scoped
16188 (defvar org-read-date-history nil)
16189 (defvar org-read-date-final-answer nil)
16190 (defvar org-read-date-analyze-futurep nil)
16191 (defvar org-read-date-analyze-forced-year nil)
16192 (defvar org-read-date-inactive)
16194 (defvar org-read-date-minibuffer-local-map
16195 (let* ((org-replace-disputed-keys nil)
16196 (map (make-sparse-keymap)))
16197 (set-keymap-parent map minibuffer-local-map)
16198 (org-defkey map (kbd ".")
16199 (lambda () (interactive)
16200 ;; Are we at the beginning of the prompt?
16201 (if (looking-back "^[^:]+: ")
16202 (org-eval-in-calendar '(calendar-goto-today))
16203 (insert "."))))
16204 (org-defkey map (kbd "C-.")
16205 (lambda () (interactive)
16206 (org-eval-in-calendar '(calendar-goto-today))))
16207 (org-defkey map [(meta shift left)]
16208 (lambda () (interactive)
16209 (org-eval-in-calendar '(calendar-backward-month 1))))
16210 (org-defkey map [(meta shift right)]
16211 (lambda () (interactive)
16212 (org-eval-in-calendar '(calendar-forward-month 1))))
16213 (org-defkey map [(meta shift up)]
16214 (lambda () (interactive)
16215 (org-eval-in-calendar '(calendar-backward-year 1))))
16216 (org-defkey map [(meta shift down)]
16217 (lambda () (interactive)
16218 (org-eval-in-calendar '(calendar-forward-year 1))))
16219 (org-defkey map [?\e (shift left)]
16220 (lambda () (interactive)
16221 (org-eval-in-calendar '(calendar-backward-month 1))))
16222 (org-defkey map [?\e (shift right)]
16223 (lambda () (interactive)
16224 (org-eval-in-calendar '(calendar-forward-month 1))))
16225 (org-defkey map [?\e (shift up)]
16226 (lambda () (interactive)
16227 (org-eval-in-calendar '(calendar-backward-year 1))))
16228 (org-defkey map [?\e (shift down)]
16229 (lambda () (interactive)
16230 (org-eval-in-calendar '(calendar-forward-year 1))))
16231 (org-defkey map [(shift up)]
16232 (lambda () (interactive)
16233 (org-eval-in-calendar '(calendar-backward-week 1))))
16234 (org-defkey map [(shift down)]
16235 (lambda () (interactive)
16236 (org-eval-in-calendar '(calendar-forward-week 1))))
16237 (org-defkey map [(shift left)]
16238 (lambda () (interactive)
16239 (org-eval-in-calendar '(calendar-backward-day 1))))
16240 (org-defkey map [(shift right)]
16241 (lambda () (interactive)
16242 (org-eval-in-calendar '(calendar-forward-day 1))))
16243 (org-defkey map "!"
16244 (lambda () (interactive)
16245 (org-eval-in-calendar '(diary-view-entries))
16246 (message "")))
16247 (org-defkey map ">"
16248 (lambda () (interactive)
16249 (org-eval-in-calendar '(scroll-calendar-left 1))))
16250 (org-defkey map "<"
16251 (lambda () (interactive)
16252 (org-eval-in-calendar '(scroll-calendar-right 1))))
16253 (org-defkey map "\C-v"
16254 (lambda () (interactive)
16255 (org-eval-in-calendar
16256 '(calendar-scroll-left-three-months 1))))
16257 (org-defkey map "\M-v"
16258 (lambda () (interactive)
16259 (org-eval-in-calendar
16260 '(calendar-scroll-right-three-months 1))))
16261 map)
16262 "Keymap for minibuffer commands when using `org-read-date'.")
16264 (defvar org-def)
16265 (defvar org-defdecode)
16266 (defvar org-with-time)
16268 (defun org-read-date (&optional org-with-time to-time from-string prompt
16269 default-time default-input inactive)
16270 "Read a date, possibly a time, and make things smooth for the user.
16271 The prompt will suggest to enter an ISO date, but you can also enter anything
16272 which will at least partially be understood by `parse-time-string'.
16273 Unrecognized parts of the date will default to the current day, month, year,
16274 hour and minute. If this command is called to replace a timestamp at point,
16275 or to enter the second timestamp of a range, the default time is taken
16276 from the existing stamp. Furthermore, the command prefers the future,
16277 so if you are giving a date where the year is not given, and the day-month
16278 combination is already past in the current year, it will assume you
16279 mean next year. For details, see the manual. A few examples:
16281 3-2-5 --> 2003-02-05
16282 feb 15 --> currentyear-02-15
16283 2/15 --> currentyear-02-15
16284 sep 12 9 --> 2009-09-12
16285 12:45 --> today 12:45
16286 22 sept 0:34 --> currentyear-09-22 0:34
16287 12 --> currentyear-currentmonth-12
16288 Fri --> nearest Friday after today
16289 -Tue --> last Tuesday
16290 etc.
16292 Furthermore you can specify a relative date by giving, as the *first* thing
16293 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16294 change in days weeks, months, years.
16295 With a single plus or minus, the date is relative to today. With a double
16296 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16297 +4d --> four days from today
16298 +4 --> same as above
16299 +2w --> two weeks from today
16300 ++5 --> five days from default date
16302 The function understands only English month and weekday abbreviations.
16304 While prompting, a calendar is popped up - you can also select the
16305 date with the mouse (button 1). The calendar shows a period of three
16306 months. To scroll it to other months, use the keys `>' and `<'.
16307 If you don't like the calendar, turn it off with
16308 \(setq org-read-date-popup-calendar nil)
16310 With optional argument TO-TIME, the date will immediately be converted
16311 to an internal time.
16312 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16313 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16314 still enter a time, and this function will inform the calling routine
16315 about this change. The calling routine may then choose to change the
16316 format used to insert the time stamp into the buffer to include the time.
16317 With optional argument FROM-STRING, read from this string instead from
16318 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16319 the time/date that is used for everything that is not specified by the
16320 user."
16321 (require 'parse-time)
16322 (let* ((org-time-stamp-rounding-minutes
16323 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16324 (org-dcst org-display-custom-times)
16325 (ct (org-current-time))
16326 (org-def (or org-overriding-default-time default-time ct))
16327 (org-defdecode (decode-time org-def))
16328 (dummy (progn
16329 (when (< (nth 2 org-defdecode) org-extend-today-until)
16330 (setcar (nthcdr 2 org-defdecode) -1)
16331 (setcar (nthcdr 1 org-defdecode) 59)
16332 (setq org-def (apply 'encode-time org-defdecode)
16333 org-defdecode (decode-time org-def)))))
16334 (mouse-autoselect-window nil) ; Don't let the mouse jump
16335 (calendar-frame-setup nil)
16336 (calendar-setup nil)
16337 (calendar-move-hook nil)
16338 (calendar-view-diary-initially-flag nil)
16339 (calendar-view-holidays-initially-flag nil)
16340 (timestr (format-time-string
16341 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16342 (prompt (concat (if prompt (concat prompt " ") "")
16343 (format "Date+time [%s]: " timestr)))
16344 ans (org-ans0 "") org-ans1 org-ans2 final)
16346 (cond
16347 (from-string (setq ans from-string))
16348 (org-read-date-popup-calendar
16349 (save-excursion
16350 (save-window-excursion
16351 (calendar)
16352 (org-eval-in-calendar '(setq cursor-type nil) t)
16353 (unwind-protect
16354 (progn
16355 (calendar-forward-day (- (time-to-days org-def)
16356 (calendar-absolute-from-gregorian
16357 (calendar-current-date))))
16358 (org-eval-in-calendar nil t)
16359 (let* ((old-map (current-local-map))
16360 (map (copy-keymap calendar-mode-map))
16361 (minibuffer-local-map
16362 (copy-keymap org-read-date-minibuffer-local-map)))
16363 (org-defkey map (kbd "RET") 'org-calendar-select)
16364 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16365 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16366 (unwind-protect
16367 (progn
16368 (use-local-map map)
16369 (setq org-read-date-inactive inactive)
16370 (add-hook 'post-command-hook 'org-read-date-display)
16371 (setq org-ans0 (read-string prompt default-input
16372 'org-read-date-history nil))
16373 ;; org-ans0: from prompt
16374 ;; org-ans1: from mouse click
16375 ;; org-ans2: from calendar motion
16376 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16377 (remove-hook 'post-command-hook 'org-read-date-display)
16378 (use-local-map old-map)
16379 (when org-read-date-overlay
16380 (delete-overlay org-read-date-overlay)
16381 (setq org-read-date-overlay nil)))))
16382 (bury-buffer "*Calendar*")))))
16384 (t ; Naked prompt only
16385 (unwind-protect
16386 (setq ans (read-string prompt default-input
16387 'org-read-date-history timestr))
16388 (when org-read-date-overlay
16389 (delete-overlay org-read-date-overlay)
16390 (setq org-read-date-overlay nil)))))
16392 (setq final (org-read-date-analyze ans org-def org-defdecode))
16394 (when org-read-date-analyze-forced-year
16395 (message "Year was forced into %s"
16396 (if org-read-date-force-compatible-dates
16397 "compatible range (1970-2037)"
16398 "range representable on this machine"))
16399 (ding))
16401 ;; One round trip to get rid of 34th of August and stuff like that....
16402 (setq final (decode-time (apply 'encode-time final)))
16404 (setq org-read-date-final-answer ans)
16406 (if to-time
16407 (apply 'encode-time final)
16408 (if (and (boundp 'org-time-was-given) org-time-was-given)
16409 (format "%04d-%02d-%02d %02d:%02d"
16410 (nth 5 final) (nth 4 final) (nth 3 final)
16411 (nth 2 final) (nth 1 final))
16412 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16414 (defun org-read-date-display ()
16415 "Display the current date prompt interpretation in the minibuffer."
16416 (when org-read-date-display-live
16417 (when org-read-date-overlay
16418 (delete-overlay org-read-date-overlay))
16419 (when (minibufferp (current-buffer))
16420 (save-excursion
16421 (end-of-line 1)
16422 (while (not (equal (buffer-substring
16423 (max (point-min) (- (point) 4)) (point))
16424 " "))
16425 (insert " ")))
16426 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16427 " " (or org-ans1 org-ans2)))
16428 (org-end-time-was-given nil)
16429 (f (org-read-date-analyze ans org-def org-defdecode))
16430 (fmts (if org-dcst
16431 org-time-stamp-custom-formats
16432 org-time-stamp-formats))
16433 (fmt (if (or org-with-time
16434 (and (boundp 'org-time-was-given) org-time-was-given))
16435 (cdr fmts)
16436 (car fmts)))
16437 (txt (format-time-string fmt (apply 'encode-time f)))
16438 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16439 (txt (concat "=> " txt)))
16440 (when (and org-end-time-was-given
16441 (string-match org-plain-time-of-day-regexp txt))
16442 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16443 org-end-time-was-given
16444 (substring txt (match-end 0)))))
16445 (when org-read-date-analyze-futurep
16446 (setq txt (concat txt " (=>F)")))
16447 (setq org-read-date-overlay
16448 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16449 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16451 (defun org-read-date-analyze (ans org-def org-defdecode)
16452 "Analyze the combined answer of the date prompt."
16453 ;; FIXME: cleanup and comment
16454 (let ((nowdecode (decode-time (current-time)))
16455 delta deltan deltaw deltadef year month day
16456 hour minute second wday pm h2 m2 tl wday1
16457 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16458 (setq org-read-date-analyze-futurep nil
16459 org-read-date-analyze-forced-year nil)
16460 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16461 (setq ans "+0"))
16463 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16464 (setq ans (replace-match "" t t ans)
16465 deltan (car delta)
16466 deltaw (nth 1 delta)
16467 deltadef (nth 2 delta)))
16469 ;; Check if there is an iso week date in there. If yes, store the
16470 ;; info and postpone interpreting it until the rest of the parsing
16471 ;; is done.
16472 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16473 (setq iso-year (if (match-end 1)
16474 (org-small-year-to-year
16475 (string-to-number (match-string 1 ans))))
16476 iso-weekday (if (match-end 3)
16477 (string-to-number (match-string 3 ans)))
16478 iso-week (string-to-number (match-string 2 ans)))
16479 (setq ans (replace-match "" t t ans)))
16481 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16482 (when (string-match
16483 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16484 (setq year (if (match-end 2)
16485 (string-to-number (match-string 2 ans))
16486 (progn (setq kill-year t)
16487 (string-to-number (format-time-string "%Y"))))
16488 month (string-to-number (match-string 3 ans))
16489 day (string-to-number (match-string 4 ans)))
16490 (if (< year 100) (setq year (+ 2000 year)))
16491 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16492 t nil ans)))
16494 ;; Help matching dotted european dates
16495 (when (string-match
16496 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16497 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16498 (setq kill-year t)
16499 (string-to-number (format-time-string "%Y")))
16500 day (string-to-number (match-string 1 ans))
16501 month (string-to-number (match-string 2 ans))
16502 ans (replace-match (format "%04d-%02d-%02d" year month day)
16503 t nil ans)))
16505 ;; Help matching american dates, like 5/30 or 5/30/7
16506 (when (string-match
16507 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16508 (setq year (if (match-end 4)
16509 (string-to-number (match-string 4 ans))
16510 (progn (setq kill-year t)
16511 (string-to-number (format-time-string "%Y"))))
16512 month (string-to-number (match-string 1 ans))
16513 day (string-to-number (match-string 2 ans)))
16514 (if (< year 100) (setq year (+ 2000 year)))
16515 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16516 t nil ans)))
16517 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16518 ;; If there is a time with am/pm, and *no* time without it, we convert
16519 ;; so that matching will be successful.
16520 (loop for i from 1 to 2 do ; twice, for end time as well
16521 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16522 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16523 (setq hour (string-to-number (match-string 1 ans))
16524 minute (if (match-end 3)
16525 (string-to-number (match-string 3 ans))
16527 pm (equal ?p
16528 (string-to-char (downcase (match-string 4 ans)))))
16529 (if (and (= hour 12) (not pm))
16530 (setq hour 0)
16531 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16532 (setq ans (replace-match (format "%02d:%02d" hour minute)
16533 t t ans))))
16535 ;; Check if a time range is given as a duration
16536 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16537 (setq hour (string-to-number (match-string 1 ans))
16538 h2 (+ hour (string-to-number (match-string 3 ans)))
16539 minute (string-to-number (match-string 2 ans))
16540 m2 (+ minute (if (match-end 5) (string-to-number
16541 (match-string 5 ans))0)))
16542 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16543 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16544 t t ans)))
16546 ;; Check if there is a time range
16547 (when (boundp 'org-end-time-was-given)
16548 (setq org-time-was-given nil)
16549 (when (and (string-match org-plain-time-of-day-regexp ans)
16550 (match-end 8))
16551 (setq org-end-time-was-given (match-string 8 ans))
16552 (setq ans (concat (substring ans 0 (match-beginning 7))
16553 (substring ans (match-end 7))))))
16555 (setq tl (parse-time-string ans)
16556 day (or (nth 3 tl) (nth 3 org-defdecode))
16557 month (or (nth 4 tl)
16558 (if (and org-read-date-prefer-future
16559 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16560 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16561 (nth 4 org-defdecode)))
16562 year (or (and (not kill-year) (nth 5 tl))
16563 (if (and org-read-date-prefer-future
16564 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16565 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16566 (nth 5 org-defdecode)))
16567 hour (or (nth 2 tl) (nth 2 org-defdecode))
16568 minute (or (nth 1 tl) (nth 1 org-defdecode))
16569 second (or (nth 0 tl) 0)
16570 wday (nth 6 tl))
16572 (when (and (eq org-read-date-prefer-future 'time)
16573 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16574 (equal day (nth 3 nowdecode))
16575 (equal month (nth 4 nowdecode))
16576 (equal year (nth 5 nowdecode))
16577 (nth 2 tl)
16578 (or (< (nth 2 tl) (nth 2 nowdecode))
16579 (and (= (nth 2 tl) (nth 2 nowdecode))
16580 (nth 1 tl)
16581 (< (nth 1 tl) (nth 1 nowdecode)))))
16582 (setq day (1+ day)
16583 futurep t))
16585 ;; Special date definitions below
16586 (cond
16587 (iso-week
16588 ;; There was an iso week
16589 (require 'cal-iso)
16590 (setq futurep nil)
16591 (setq year (or iso-year year)
16592 day (or iso-weekday wday 1)
16593 wday nil ; to make sure that the trigger below does not match
16594 iso-date (calendar-gregorian-from-absolute
16595 (calendar-absolute-from-iso
16596 (list iso-week day year))))
16597 ; FIXME: Should we also push ISO weeks into the future?
16598 ; (when (and org-read-date-prefer-future
16599 ; (not iso-year)
16600 ; (< (calendar-absolute-from-gregorian iso-date)
16601 ; (time-to-days (current-time))))
16602 ; (setq year (1+ year)
16603 ; iso-date (calendar-gregorian-from-absolute
16604 ; (calendar-absolute-from-iso
16605 ; (list iso-week day year)))))
16606 (setq month (car iso-date)
16607 year (nth 2 iso-date)
16608 day (nth 1 iso-date)))
16609 (deltan
16610 (setq futurep nil)
16611 (unless deltadef
16612 (let ((now (decode-time (current-time))))
16613 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16614 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16615 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16616 ((equal deltaw "m") (setq month (+ month deltan)))
16617 ((equal deltaw "y") (setq year (+ year deltan)))))
16618 ((and wday (not (nth 3 tl)))
16619 ;; Weekday was given, but no day, so pick that day in the week
16620 ;; on or after the derived date.
16621 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16622 (unless (equal wday wday1)
16623 (setq day (+ day (% (- wday wday1 -7) 7))))))
16624 (if (and (boundp 'org-time-was-given)
16625 (nth 2 tl))
16626 (setq org-time-was-given t))
16627 (if (< year 100) (setq year (+ 2000 year)))
16628 ;; Check of the date is representable
16629 (if org-read-date-force-compatible-dates
16630 (progn
16631 (if (< year 1970)
16632 (setq year 1970 org-read-date-analyze-forced-year t))
16633 (if (> year 2037)
16634 (setq year 2037 org-read-date-analyze-forced-year t)))
16635 (condition-case nil
16636 (ignore (encode-time second minute hour day month year))
16637 (error
16638 (setq year (nth 5 org-defdecode))
16639 (setq org-read-date-analyze-forced-year t))))
16640 (setq org-read-date-analyze-futurep futurep)
16641 (list second minute hour day month year)))
16643 (defvar parse-time-weekdays)
16644 (defun org-read-date-get-relative (s today default)
16645 "Check string S for special relative date string.
16646 TODAY and DEFAULT are internal times, for today and for a default.
16647 Return shift list (N what def-flag)
16648 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16649 N is the number of WHATs to shift.
16650 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16651 the DEFAULT date rather than TODAY."
16652 (require 'parse-time)
16653 (when (and
16654 (string-match
16655 (concat
16656 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16657 "\\([0-9]+\\)?"
16658 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16659 "\\([ \t]\\|$\\)") s)
16660 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16661 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16662 (string-to-char (substring (match-string 1 s) -1))
16663 ?+))
16664 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16665 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16666 (what (if (match-end 3) (match-string 3 s) "d"))
16667 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16668 (date (if rel default today))
16669 (wday (nth 6 (decode-time date)))
16670 delta)
16671 (if wday1
16672 (progn
16673 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16674 (if (= delta 0) (setq delta 7))
16675 (if (= dir ?-)
16676 (progn
16677 (setq delta (- delta 7))
16678 (if (= delta 0) (setq delta -7))))
16679 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16680 (list delta "d" rel))
16681 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16683 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16684 "Turn a user-specified date into the internal representation.
16685 The internal representation needed by the calendar is (month day year).
16686 This is a wrapper to handle the brain-dead convention in calendar that
16687 user function argument order change dependent on argument order."
16688 (if (boundp 'calendar-date-style)
16689 (cond
16690 ((eq calendar-date-style 'american)
16691 (list arg1 arg2 arg3))
16692 ((eq calendar-date-style 'european)
16693 (list arg2 arg1 arg3))
16694 ((eq calendar-date-style 'iso)
16695 (list arg2 arg3 arg1)))
16696 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16697 (if (org-bound-and-true-p european-calendar-style)
16698 (list arg2 arg1 arg3)
16699 (list arg1 arg2 arg3)))))
16701 (defun org-eval-in-calendar (form &optional keepdate)
16702 "Eval FORM in the calendar window and return to current window.
16703 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16704 otherwise stick to the current value of `org-ans2'."
16705 (let ((sf (selected-frame))
16706 (sw (selected-window)))
16707 (select-window (get-buffer-window "*Calendar*" t))
16708 (eval form)
16709 (when (and (not keepdate) (calendar-cursor-to-date))
16710 (let* ((date (calendar-cursor-to-date))
16711 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16712 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16713 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16714 (select-window sw)
16715 (org-select-frame-set-input-focus sf)))
16717 (defun org-calendar-select ()
16718 "Return to `org-read-date' with the date currently selected.
16719 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16720 (interactive)
16721 (when (calendar-cursor-to-date)
16722 (let* ((date (calendar-cursor-to-date))
16723 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16724 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16725 (if (active-minibuffer-window) (exit-minibuffer))))
16727 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16728 "Insert a date stamp for the date given by the internal TIME.
16729 WITH-HM means use the stamp format that includes the time of the day.
16730 INACTIVE means use square brackets instead of angular ones, so that the
16731 stamp will not contribute to the agenda.
16732 PRE and POST are optional strings to be inserted before and after the
16733 stamp.
16734 The command returns the inserted time stamp."
16735 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16736 stamp)
16737 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16738 (insert-before-markers (or pre ""))
16739 (when (listp extra)
16740 (setq extra (car extra))
16741 (if (and (stringp extra)
16742 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16743 (setq extra (format "-%02d:%02d"
16744 (string-to-number (match-string 1 extra))
16745 (string-to-number (match-string 2 extra))))
16746 (setq extra nil)))
16747 (when extra
16748 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16749 (insert-before-markers (setq stamp (format-time-string fmt time)))
16750 (insert-before-markers (or post ""))
16751 (setq org-last-inserted-timestamp stamp)))
16753 (defun org-toggle-time-stamp-overlays ()
16754 "Toggle the use of custom time stamp formats."
16755 (interactive)
16756 (setq org-display-custom-times (not org-display-custom-times))
16757 (unless org-display-custom-times
16758 (let ((p (point-min)) (bmp (buffer-modified-p)))
16759 (while (setq p (next-single-property-change p 'display))
16760 (if (and (get-text-property p 'display)
16761 (eq (get-text-property p 'face) 'org-date))
16762 (remove-text-properties
16763 p (setq p (next-single-property-change p 'display))
16764 '(display t))))
16765 (set-buffer-modified-p bmp)))
16766 (if (featurep 'xemacs)
16767 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16768 (org-restart-font-lock)
16769 (setq org-table-may-need-update t)
16770 (if org-display-custom-times
16771 (message "Time stamps are overlaid with custom format")
16772 (message "Time stamp overlays removed")))
16774 (defun org-display-custom-time (beg end)
16775 "Overlay modified time stamp format over timestamp between BEG and END."
16776 (let* ((ts (buffer-substring beg end))
16777 t1 w1 with-hm tf time str w2 (off 0))
16778 (save-match-data
16779 (setq t1 (org-parse-time-string ts t))
16780 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16781 (setq off (- (match-end 0) (match-beginning 0)))))
16782 (setq end (- end off))
16783 (setq w1 (- end beg)
16784 with-hm (and (nth 1 t1) (nth 2 t1))
16785 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16786 time (org-fix-decoded-time t1)
16787 str (org-add-props
16788 (format-time-string
16789 (substring tf 1 -1) (apply 'encode-time time))
16790 nil 'mouse-face 'highlight)
16791 w2 (length str))
16792 (if (not (= w2 w1))
16793 (add-text-properties (1+ beg) (+ 2 beg)
16794 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16795 (if (featurep 'xemacs)
16796 (progn
16797 (put-text-property beg end 'invisible t)
16798 (put-text-property beg end 'end-glyph (make-glyph str)))
16799 (put-text-property beg end 'display str))))
16801 (defun org-translate-time (string)
16802 "Translate all timestamps in STRING to custom format.
16803 But do this only if the variable `org-display-custom-times' is set."
16804 (when org-display-custom-times
16805 (save-match-data
16806 (let* ((start 0)
16807 (re org-ts-regexp-both)
16808 t1 with-hm inactive tf time str beg end)
16809 (while (setq start (string-match re string start))
16810 (setq beg (match-beginning 0)
16811 end (match-end 0)
16812 t1 (save-match-data
16813 (org-parse-time-string (substring string beg end) t))
16814 with-hm (and (nth 1 t1) (nth 2 t1))
16815 inactive (equal (substring string beg (1+ beg)) "[")
16816 tf (funcall (if with-hm 'cdr 'car)
16817 org-time-stamp-custom-formats)
16818 time (org-fix-decoded-time t1)
16819 str (format-time-string
16820 (concat
16821 (if inactive "[" "<") (substring tf 1 -1)
16822 (if inactive "]" ">"))
16823 (apply 'encode-time time))
16824 string (replace-match str t t string)
16825 start (+ start (length str)))))))
16826 string)
16828 (defun org-fix-decoded-time (time)
16829 "Set 0 instead of nil for the first 6 elements of time.
16830 Don't touch the rest."
16831 (let ((n 0))
16832 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16834 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16836 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16837 "Difference between TIMESTAMP-STRING and now in days.
16838 If SECONDS is non-nil, return the difference in seconds."
16839 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16840 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16841 (funcall fdiff (current-time)))))
16843 (defun org-deadline-close (timestamp-string &optional ndays)
16844 "Is the time in TIMESTAMP-STRING close to the current date?"
16845 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16846 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16847 (not (org-entry-is-done-p))))
16849 (defun org-get-wdays (ts &optional delay zero-delay)
16850 "Get the deadline lead time appropriate for timestring TS.
16851 When DELAY is non-nil, get the delay time for scheduled items
16852 instead of the deadline lead time. When ZERO-DELAY is non-nil
16853 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16854 don't try to find the delay cookie in the scheduled timestamp."
16855 (let ((tv (if delay org-scheduled-delay-days
16856 org-deadline-warning-days)))
16857 (cond
16858 ((or (and delay (< tv 0))
16859 (and delay zero-delay (<= tv 0))
16860 (and (not delay) (<= tv 0)))
16861 ;; Enforce this value no matter what
16862 (- tv))
16863 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16864 ;; lead time is specified.
16865 (floor (* (string-to-number (match-string 1 ts))
16866 (cdr (assoc (match-string 2 ts)
16867 '(("d" . 1) ("w" . 7)
16868 ("m" . 30.4) ("y" . 365.25)
16869 ("h" . 0.041667)))))))
16870 ;; go for the default.
16871 (t tv))))
16873 (defun org-calendar-select-mouse (ev)
16874 "Return to `org-read-date' with the date currently selected.
16875 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16876 (interactive "e")
16877 (mouse-set-point ev)
16878 (when (calendar-cursor-to-date)
16879 (let* ((date (calendar-cursor-to-date))
16880 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16881 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16882 (if (active-minibuffer-window) (exit-minibuffer))))
16884 (defun org-check-deadlines (ndays)
16885 "Check if there are any deadlines due or past due.
16886 A deadline is considered due if it happens within `org-deadline-warning-days'
16887 days from today's date. If the deadline appears in an entry marked DONE,
16888 it is not shown. The prefix arg NDAYS can be used to test that many
16889 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16890 (interactive "P")
16891 (let* ((org-warn-days
16892 (cond
16893 ((equal ndays '(4)) 100000)
16894 (ndays (prefix-numeric-value ndays))
16895 (t (abs org-deadline-warning-days))))
16896 (case-fold-search nil)
16897 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16898 (callback
16899 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16901 (message "%d deadlines past-due or due within %d days"
16902 (org-occur regexp nil callback)
16903 org-warn-days)))
16905 (defsubst org-re-timestamp (type)
16906 "Return a regexp for timestamp TYPE.
16907 Allowed values for TYPE are:
16909 all: all timestamps
16910 active: only active timestamps (<...>)
16911 inactive: only inactive timestamps ([...])
16912 scheduled: only scheduled timestamps
16913 deadline: only deadline timestamps
16914 closed: only closed time-stamps
16916 When TYPE is nil, fall back on returning a regexp that matches
16917 both scheduled and deadline timestamps."
16918 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16919 ((eq type 'active) org-ts-regexp)
16920 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16921 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16922 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16923 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
16924 ((eq type 'scheduled-or-deadline)
16925 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16927 (defun org-check-before-date (date)
16928 "Check if there are deadlines or scheduled entries before DATE."
16929 (interactive (list (org-read-date)))
16930 (let ((case-fold-search nil)
16931 (regexp (org-re-timestamp org-ts-type))
16932 (callback
16933 (lambda () (time-less-p
16934 (org-time-string-to-time (match-string 1))
16935 (org-time-string-to-time date)))))
16936 (message "%d entries before %s"
16937 (org-occur regexp nil callback) date)))
16939 (defun org-check-after-date (date)
16940 "Check if there are deadlines or scheduled entries after DATE."
16941 (interactive (list (org-read-date)))
16942 (let ((case-fold-search nil)
16943 (regexp (org-re-timestamp org-ts-type))
16944 (callback
16945 (lambda () (not
16946 (time-less-p
16947 (org-time-string-to-time (match-string 1))
16948 (org-time-string-to-time date))))))
16949 (message "%d entries after %s"
16950 (org-occur regexp nil callback) date)))
16952 (defun org-check-dates-range (start-date end-date)
16953 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16954 (interactive (list (org-read-date nil nil nil "Range starts")
16955 (org-read-date nil nil nil "Range end")))
16956 (let ((case-fold-search nil)
16957 (regexp (org-re-timestamp org-ts-type))
16958 (callback
16959 (lambda ()
16960 (let ((match (match-string 1)))
16961 (and
16962 (not (time-less-p
16963 (org-time-string-to-time match)
16964 (org-time-string-to-time start-date)))
16965 (time-less-p
16966 (org-time-string-to-time match)
16967 (org-time-string-to-time end-date)))))))
16968 (message "%d entries between %s and %s"
16969 (org-occur regexp nil callback) start-date end-date)))
16971 (defun org-evaluate-time-range (&optional to-buffer)
16972 "Evaluate a time range by computing the difference between start and end.
16973 Normally the result is just printed in the echo area, but with prefix arg
16974 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16975 If the time range is actually in a table, the result is inserted into the
16976 next column.
16977 For time difference computation, a year is assumed to be exactly 365
16978 days in order to avoid rounding problems."
16979 (interactive "P")
16981 (org-clock-update-time-maybe)
16982 (save-excursion
16983 (unless (org-at-date-range-p t)
16984 (goto-char (point-at-bol))
16985 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16986 (if (not (org-at-date-range-p t))
16987 (user-error "Not at a time-stamp range, and none found in current line")))
16988 (let* ((ts1 (match-string 1))
16989 (ts2 (match-string 2))
16990 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16991 (match-end (match-end 0))
16992 (time1 (org-time-string-to-time ts1))
16993 (time2 (org-time-string-to-time ts2))
16994 (t1 (org-float-time time1))
16995 (t2 (org-float-time time2))
16996 (diff (abs (- t2 t1)))
16997 (negative (< (- t2 t1) 0))
16998 ;; (ys (floor (* 365 24 60 60)))
16999 (ds (* 24 60 60))
17000 (hs (* 60 60))
17001 (fy "%dy %dd %02d:%02d")
17002 (fy1 "%dy %dd")
17003 (fd "%dd %02d:%02d")
17004 (fd1 "%dd")
17005 (fh "%02d:%02d")
17006 y d h m align)
17007 (if havetime
17008 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17010 d (floor (/ diff ds)) diff (mod diff ds)
17011 h (floor (/ diff hs)) diff (mod diff hs)
17012 m (floor (/ diff 60)))
17013 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17015 d (floor (+ (/ diff ds) 0.5))
17016 h 0 m 0))
17017 (if (not to-buffer)
17018 (message "%s" (org-make-tdiff-string y d h m))
17019 (if (org-at-table-p)
17020 (progn
17021 (goto-char match-end)
17022 (setq align t)
17023 (and (looking-at " *|") (goto-char (match-end 0))))
17024 (goto-char match-end))
17025 (if (looking-at
17026 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17027 (replace-match ""))
17028 (if negative (insert " -"))
17029 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17030 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17031 (insert " " (format fh h m))))
17032 (if align (org-table-align))
17033 (message "Time difference inserted")))))
17035 (defun org-make-tdiff-string (y d h m)
17036 (let ((fmt "")
17037 (l nil))
17038 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
17039 l (push y l)))
17040 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
17041 l (push d l)))
17042 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
17043 l (push h l)))
17044 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
17045 l (push m l)))
17046 (apply 'format fmt (nreverse l))))
17048 (defun org-time-string-to-time (s &optional buffer pos)
17049 "Convert a timestamp string into internal time."
17050 (condition-case errdata
17051 (apply 'encode-time (org-parse-time-string s))
17052 (error (error "Bad timestamp `%s'%s\nError was: %s"
17053 s (if (not (and buffer pos))
17055 (format " at %d in buffer `%s'" pos buffer))
17056 (cdr errdata)))))
17058 (defun org-time-string-to-seconds (s)
17059 "Convert a timestamp string to a number of seconds."
17060 (org-float-time (org-time-string-to-time s)))
17062 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17063 "Convert a time stamp to an absolute day number.
17064 If there is a specifier for a cyclic time stamp, get the closest
17065 date to DAYNR.
17066 PREFER and SHOW-ALL are passed through to `org-closest-date'.
17067 The variable `date' is bound by the calendar when this is called."
17068 (cond
17069 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17070 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17071 daynr
17072 (+ daynr 1000)))
17073 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
17074 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17075 (time-to-days (current-time))) (match-string 0 s)
17076 prefer show-all))
17077 (t (time-to-days
17078 (condition-case errdata
17079 (apply 'encode-time (org-parse-time-string s))
17080 (error (error "Bad timestamp `%s'%s\nError was: %s"
17081 s (if (not (and buffer pos))
17083 (format " at %d in buffer `%s'" pos buffer))
17084 (cdr errdata))))))))
17086 (defun org-days-to-iso-week (days)
17087 "Return the iso week number."
17088 (require 'cal-iso)
17089 (car (calendar-iso-from-absolute days)))
17091 (defun org-small-year-to-year (year)
17092 "Convert 2-digit years into 4-digit years.
17093 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
17094 The year 2000 cannot be abbreviated. Any year larger than 99
17095 is returned unchanged."
17096 (if (< year 38)
17097 (setq year (+ 2000 year))
17098 (if (< year 100)
17099 (setq year (+ 1900 year))))
17100 year)
17102 (defun org-time-from-absolute (d)
17103 "Return the time corresponding to date D.
17104 D may be an absolute day number, or a calendar-type list (month day year)."
17105 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17106 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17108 (defun org-calendar-holiday ()
17109 "List of holidays, for Diary display in Org-mode."
17110 (require 'holidays)
17111 (let ((hl (funcall
17112 (if (fboundp 'calendar-check-holidays)
17113 'calendar-check-holidays 'check-calendar-holidays) date)))
17114 (if hl (mapconcat 'identity hl "; "))))
17116 (defun org-diary-sexp-entry (sexp entry date)
17117 "Process a SEXP diary ENTRY for DATE."
17118 (require 'diary-lib)
17119 (let ((result (if calendar-debug-sexp
17120 (let ((stack-trace-on-error t))
17121 (eval (car (read-from-string sexp))))
17122 (condition-case nil
17123 (eval (car (read-from-string sexp)))
17124 (error
17125 (beep)
17126 (message "Bad sexp at line %d in %s: %s"
17127 (org-current-line)
17128 (buffer-file-name) sexp)
17129 (sleep-for 2))))))
17130 (cond ((stringp result) (split-string result "; "))
17131 ((and (consp result)
17132 (not (consp (cdr result)))
17133 (stringp (cdr result))) (cdr result))
17134 ((and (consp result)
17135 (stringp (car result))) result)
17136 (result entry))))
17138 (defun org-diary-to-ical-string (frombuf)
17139 "Get iCalendar entries from diary entries in buffer FROMBUF.
17140 This uses the icalendar.el library."
17141 (let* ((tmpdir (if (featurep 'xemacs)
17142 (temp-directory)
17143 temporary-file-directory))
17144 (tmpfile (make-temp-name
17145 (expand-file-name "orgics" tmpdir)))
17146 buf rtn b e)
17147 (with-current-buffer frombuf
17148 (icalendar-export-region (point-min) (point-max) tmpfile)
17149 (setq buf (find-buffer-visiting tmpfile))
17150 (set-buffer buf)
17151 (goto-char (point-min))
17152 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17153 (setq b (match-beginning 0)))
17154 (goto-char (point-max))
17155 (if (re-search-backward "^END:VEVENT" nil t)
17156 (setq e (match-end 0)))
17157 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17158 (kill-buffer buf)
17159 (delete-file tmpfile)
17160 rtn))
17162 (defun org-closest-date (start current change prefer show-all)
17163 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17164 When PREFER is `past', return a date that is either CURRENT or past.
17165 When PREFER is `future', return a date that is either CURRENT or future.
17166 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17167 ;; Make the proper lists from the dates
17168 (catch 'exit
17169 (let ((a1 '(("h" . hour)
17170 ("d" . day)
17171 ("w" . week)
17172 ("m" . month)
17173 ("y" . year)))
17174 (shour (nth 2 (org-parse-time-string start)))
17175 dn dw sday cday n1 n2 n0
17176 d m y y1 y2 date1 date2 nmonths nm ny m2)
17178 (setq start (org-date-to-gregorian start)
17179 current (org-date-to-gregorian
17180 (if show-all
17181 current
17182 (time-to-days (current-time))))
17183 sday (calendar-absolute-from-gregorian start)
17184 cday (calendar-absolute-from-gregorian current))
17186 (if (<= cday sday) (throw 'exit sday))
17188 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17189 (setq dn (string-to-number (match-string 1 change))
17190 dw (cdr (assoc (match-string 2 change) a1)))
17191 (user-error "Invalid change specifier: %s" change))
17192 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17193 (cond
17194 ((eq dw 'hour)
17195 (let ((missing-hours
17196 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17197 dn)))
17198 (setq n1 (if (zerop missing-hours) cday
17199 (- cday (1+ (floor (/ missing-hours 24)))))
17200 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17201 ((eq dw 'day)
17202 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17203 n2 (+ n1 dn)))
17204 ((eq dw 'year)
17205 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17206 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17207 (setq date1 (list m d y1)
17208 n1 (calendar-absolute-from-gregorian date1)
17209 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17210 n2 (calendar-absolute-from-gregorian date2)))
17211 ((eq dw 'month)
17212 ;; approx number of month between the two dates
17213 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17214 ;; How often does dn fit in there?
17215 (setq d (nth 1 start) m (car start) y (nth 2 start)
17216 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17217 m (+ m nm)
17218 ny (floor (/ m 12))
17219 y (+ y ny)
17220 m (- m (* ny 12)))
17221 (while (> m 12) (setq m (- m 12) y (1+ y)))
17222 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17223 (setq m2 (+ m dn) y2 y)
17224 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17225 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17226 (while (<= n2 cday)
17227 (setq n1 n2 m m2 y y2)
17228 (setq m2 (+ m dn) y2 y)
17229 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17230 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17231 ;; Make sure n1 is the earlier date
17232 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17233 (if show-all
17234 (cond
17235 ((eq prefer 'past) (if (= cday n2) n2 n1))
17236 ((eq prefer 'future) (if (= cday n1) n1 n2))
17237 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17238 (cond
17239 ((eq prefer 'past) (if (= cday n2) n2 n1))
17240 ((eq prefer 'future) (if (= cday n1) n1 n2))
17241 (t (if (= cday n1) n1 n2)))))))
17243 (defun org-date-to-gregorian (date)
17244 "Turn any specification of DATE into a Gregorian date for the calendar."
17245 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17246 ((and (listp date) (= (length date) 3)) date)
17247 ((stringp date)
17248 (setq date (org-parse-time-string date))
17249 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17250 ((listp date)
17251 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17253 (defun org-parse-time-string (s &optional nodefault)
17254 "Parse the standard Org-mode time string.
17255 This should be a lot faster than the normal `parse-time-string'.
17256 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17257 hour and minute fields will be nil if not given."
17258 (cond ((string-match org-ts-regexp0 s)
17259 (list 0
17260 (if (or (match-beginning 8) (not nodefault))
17261 (string-to-number (or (match-string 8 s) "0")))
17262 (if (or (match-beginning 7) (not nodefault))
17263 (string-to-number (or (match-string 7 s) "0")))
17264 (string-to-number (match-string 4 s))
17265 (string-to-number (match-string 3 s))
17266 (string-to-number (match-string 2 s))
17267 nil nil nil))
17268 ((string-match "^<[^>]+>$" s)
17269 (decode-time (seconds-to-time (org-matcher-time s))))
17270 (t (error "Not a standard Org-mode time string: %s" s))))
17272 (defun org-timestamp-up (&optional arg)
17273 "Increase the date item at the cursor by one.
17274 If the cursor is on the year, change the year. If it is on the month,
17275 the day or the time, change that.
17276 With prefix ARG, change by that many units."
17277 (interactive "p")
17278 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17280 (defun org-timestamp-down (&optional arg)
17281 "Decrease the date item at the cursor by one.
17282 If the cursor is on the year, change the year. If it is on the month,
17283 the day or the time, change that.
17284 With prefix ARG, change by that many units."
17285 (interactive "p")
17286 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17288 (defun org-timestamp-up-day (&optional arg)
17289 "Increase the date in the time stamp by one day.
17290 With prefix ARG, change that many days."
17291 (interactive "p")
17292 (if (and (not (org-at-timestamp-p t))
17293 (org-at-heading-p))
17294 (org-todo 'up)
17295 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17297 (defun org-timestamp-down-day (&optional arg)
17298 "Decrease the date in the time stamp by one day.
17299 With prefix ARG, change that many days."
17300 (interactive "p")
17301 (if (and (not (org-at-timestamp-p t))
17302 (org-at-heading-p))
17303 (org-todo 'down)
17304 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17306 (defun org-at-timestamp-p (&optional inactive-ok)
17307 "Determine if the cursor is in or at a timestamp."
17308 (interactive)
17309 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17310 (pos (point))
17311 (ans (or (looking-at tsr)
17312 (save-excursion
17313 (skip-chars-backward "^[<\n\r\t")
17314 (if (> (point) (point-min)) (backward-char 1))
17315 (and (looking-at tsr)
17316 (> (- (match-end 0) pos) -1))))))
17317 (and ans
17318 (boundp 'org-ts-what)
17319 (setq org-ts-what
17320 (cond
17321 ((= pos (match-beginning 0)) 'bracket)
17322 ;; Point is considered to be "on the bracket" whether
17323 ;; it's really on it or right after it.
17324 ((= pos (1- (match-end 0))) 'bracket)
17325 ((= pos (match-end 0)) 'after)
17326 ((org-pos-in-match-range pos 2) 'year)
17327 ((org-pos-in-match-range pos 3) 'month)
17328 ((org-pos-in-match-range pos 7) 'hour)
17329 ((org-pos-in-match-range pos 8) 'minute)
17330 ((or (org-pos-in-match-range pos 4)
17331 (org-pos-in-match-range pos 5)) 'day)
17332 ((and (> pos (or (match-end 8) (match-end 5)))
17333 (< pos (match-end 0)))
17334 (- pos (or (match-end 8) (match-end 5))))
17335 (t 'day))))
17336 ans))
17338 (defun org-toggle-timestamp-type ()
17339 "Toggle the type (<active> or [inactive]) of a time stamp."
17340 (interactive)
17341 (when (org-at-timestamp-p t)
17342 (let ((beg (match-beginning 0)) (end (match-end 0))
17343 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17344 (save-excursion
17345 (goto-char beg)
17346 (while (re-search-forward "[][<>]" end t)
17347 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17348 t t)))
17349 (message "Timestamp is now %sactive"
17350 (if (equal (char-after beg) ?<) "" "in")))))
17352 (defun org-at-clock-log-p nil
17353 "Is the cursor on the clock log line?"
17354 (save-excursion
17355 (move-beginning-of-line 1)
17356 (looking-at "^[ \t]*CLOCK:")))
17358 (defvar org-clock-history) ; defined in org-clock.el
17359 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17360 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17361 "Change the date in the time stamp at point.
17362 The date will be changed by N times WHAT. WHAT can be `day', `month',
17363 `year', `minute', `second'. If WHAT is not given, the cursor position
17364 in the timestamp determines what will be changed.
17365 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17366 (let ((origin (point)) origin-cat
17367 with-hm inactive
17368 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17369 org-ts-what
17370 extra rem
17371 ts time time0 fixnext clrgx)
17372 (if (not (org-at-timestamp-p t))
17373 (user-error "Not at a timestamp"))
17374 (if (and (not what) (eq org-ts-what 'bracket))
17375 (org-toggle-timestamp-type)
17376 ;; Point isn't on brackets. Remember the part of the time-stamp
17377 ;; the point was in. Indeed, size of time-stamps may change,
17378 ;; but point must be kept in the same category nonetheless.
17379 (setq origin-cat org-ts-what)
17380 (if (and (not what) (not (eq org-ts-what 'day))
17381 org-display-custom-times
17382 (get-text-property (point) 'display)
17383 (not (get-text-property (1- (point)) 'display)))
17384 (setq org-ts-what 'day))
17385 (setq org-ts-what (or what org-ts-what)
17386 inactive (= (char-after (match-beginning 0)) ?\[)
17387 ts (match-string 0))
17388 (replace-match "")
17389 (when (string-match
17390 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17392 (setq extra (match-string 1 ts))
17393 (if suppress-tmp-delay
17394 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17395 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17396 (setq with-hm t))
17397 (setq time0 (org-parse-time-string ts))
17398 (when (and updown
17399 (eq org-ts-what 'minute)
17400 (not current-prefix-arg))
17401 ;; This looks like s-up and s-down. Change by one rounding step.
17402 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17403 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17404 (setcar (cdr time0) (+ (nth 1 time0)
17405 (if (> n 0) (- rem) (- dm rem))))))
17406 (setq time
17407 (encode-time (or (car time0) 0)
17408 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17409 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17410 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17411 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17412 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17413 (nthcdr 6 time0)))
17414 (when (and (member org-ts-what '(hour minute))
17415 extra
17416 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17417 (setq extra (org-modify-ts-extra
17418 extra
17419 (if (eq org-ts-what 'hour) 2 5)
17420 n dm)))
17421 (when (integerp org-ts-what)
17422 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17423 (if (eq what 'calendar)
17424 (let ((cal-date (org-get-date-from-calendar)))
17425 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17426 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17427 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17428 (setcar time0 (or (car time0) 0))
17429 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17430 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17431 (setq time (apply 'encode-time time0))))
17432 ;; Insert the new time-stamp, and ensure point stays in the same
17433 ;; category as before (i.e. not after the last position in that
17434 ;; category).
17435 (let ((pos (point)))
17436 ;; Stay before inserted string. `save-excursion' is of no use.
17437 (setq org-last-changed-timestamp
17438 (org-insert-time-stamp time with-hm inactive nil nil extra))
17439 (goto-char pos))
17440 (save-match-data
17441 (looking-at org-ts-regexp3)
17442 (goto-char (cond
17443 ;; `day' category ends before `hour' if any, or at
17444 ;; the end of the day name.
17445 ((eq origin-cat 'day)
17446 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17447 ((eq origin-cat 'hour) (min (match-end 7) origin))
17448 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17449 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17450 ;; `year' and `month' have both fixed size: point
17451 ;; couldn't have moved into another part.
17452 (t origin))))
17453 ;; Update clock if on a CLOCK line.
17454 (org-clock-update-time-maybe)
17455 ;; Maybe adjust the closest clock in `org-clock-history'
17456 (when org-clock-adjust-closest
17457 (if (not (and (org-at-clock-log-p)
17458 (< 1 (length (delq nil (mapcar 'marker-position
17459 org-clock-history))))))
17460 (message "No clock to adjust")
17461 (cond ((save-excursion ; fix previous clock?
17462 (re-search-backward org-ts-regexp0 nil t)
17463 (org-looking-back (concat org-clock-string " \\[")))
17464 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17465 ((save-excursion ; fix next clock?
17466 (re-search-backward org-ts-regexp0 nil t)
17467 (looking-at (concat org-ts-regexp0 "\\] =>")))
17468 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17469 (save-window-excursion
17470 ;; Find closest clock to point, adjust the previous/next one in history
17471 (let* ((p (save-excursion (org-back-to-heading t)))
17472 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17473 (clfixnth
17474 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17475 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17476 (if (not clfixpos)
17477 (message "No clock to adjust")
17478 (save-excursion
17479 (org-goto-marker-or-bmk clfixpos)
17480 (org-show-subtree)
17481 (when (re-search-forward clrgx nil t)
17482 (goto-char (match-beginning 1))
17483 (let (org-clock-adjust-closest)
17484 (org-timestamp-change n org-ts-what updown))
17485 (message "Clock adjusted in %s for heading: %s"
17486 (file-name-nondirectory (buffer-file-name))
17487 (org-get-heading t t)))))))))
17488 ;; Try to recenter the calendar window, if any.
17489 (if (and org-calendar-follow-timestamp-change
17490 (get-buffer-window "*Calendar*" t)
17491 (memq org-ts-what '(day month year)))
17492 (org-recenter-calendar (time-to-days time))))))
17494 (defun org-modify-ts-extra (s pos n dm)
17495 "Change the different parts of the lead-time and repeat fields in timestamp."
17496 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17497 ng h m new rem)
17498 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17499 (cond
17500 ((or (org-pos-in-match-range pos 2)
17501 (org-pos-in-match-range pos 3))
17502 (setq m (string-to-number (match-string 3 s))
17503 h (string-to-number (match-string 2 s)))
17504 (if (org-pos-in-match-range pos 2)
17505 (setq h (+ h n))
17506 (setq n (* dm (org-no-warnings (signum n))))
17507 (when (not (= 0 (setq rem (% m dm))))
17508 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17509 (setq m (+ m n)))
17510 (if (< m 0) (setq m (+ m 60) h (1- h)))
17511 (if (> m 59) (setq m (- m 60) h (1+ h)))
17512 (setq h (min 24 (max 0 h)))
17513 (setq ng 1 new (format "-%02d:%02d" h m)))
17514 ((org-pos-in-match-range pos 6)
17515 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17516 ((org-pos-in-match-range pos 5)
17517 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17519 ((org-pos-in-match-range pos 9)
17520 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17521 ((org-pos-in-match-range pos 8)
17522 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17524 (when ng
17525 (setq s (concat
17526 (substring s 0 (match-beginning ng))
17528 (substring s (match-end ng))))))
17531 (defun org-recenter-calendar (date)
17532 "If the calendar is visible, recenter it to DATE."
17533 (let ((cwin (get-buffer-window "*Calendar*" t)))
17534 (when cwin
17535 (let ((calendar-move-hook nil))
17536 (with-selected-window cwin
17537 (calendar-goto-date (if (listp date) date
17538 (calendar-gregorian-from-absolute date))))))))
17540 (defun org-goto-calendar (&optional arg)
17541 "Go to the Emacs calendar at the current date.
17542 If there is a time stamp in the current line, go to that date.
17543 A prefix ARG can be used to force the current date."
17544 (interactive "P")
17545 (let ((tsr org-ts-regexp) diff
17546 (calendar-move-hook nil)
17547 (calendar-view-holidays-initially-flag nil)
17548 (calendar-view-diary-initially-flag nil))
17549 (if (or (org-at-timestamp-p)
17550 (save-excursion
17551 (beginning-of-line 1)
17552 (looking-at (concat ".*" tsr))))
17553 (let ((d1 (time-to-days (current-time)))
17554 (d2 (time-to-days
17555 (org-time-string-to-time (match-string 1)))))
17556 (setq diff (- d2 d1))))
17557 (calendar)
17558 (calendar-goto-today)
17559 (if (and diff (not arg)) (calendar-forward-day diff))))
17561 (defun org-get-date-from-calendar ()
17562 "Return a list (month day year) of date at point in calendar."
17563 (with-current-buffer "*Calendar*"
17564 (save-match-data
17565 (calendar-cursor-to-date))))
17567 (defun org-date-from-calendar ()
17568 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17569 If there is already a time stamp at the cursor position, update it."
17570 (interactive)
17571 (if (org-at-timestamp-p t)
17572 (org-timestamp-change 0 'calendar)
17573 (let ((cal-date (org-get-date-from-calendar)))
17574 (org-insert-time-stamp
17575 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17577 (defcustom org-effort-durations
17578 `(("h" . 60)
17579 ("d" . ,(* 60 8))
17580 ("w" . ,(* 60 8 5))
17581 ("m" . ,(* 60 8 5 4))
17582 ("y" . ,(* 60 8 5 40)))
17583 "Conversion factor to minutes for an effort modifier.
17585 Each entry has the form (MODIFIER . MINUTES).
17587 In an effort string, a number followed by MODIFIER is multiplied
17588 by the specified number of MINUTES to obtain an effort in
17589 minutes.
17591 For example, if the value of this variable is ((\"hours\" . 60)), then an
17592 effort string \"2hours\" is equivalent to 120 minutes."
17593 :group 'org-agenda
17594 :version "24.1"
17595 :type '(alist :key-type (string :tag "Modifier")
17596 :value-type (number :tag "Minutes")))
17598 (defun org-minutes-to-clocksum-string (m)
17599 "Format number of minutes as a clocksum string.
17600 The format is determined by `org-time-clocksum-format',
17601 `org-time-clocksum-use-fractional' and
17602 `org-time-clocksum-fractional-format' and
17603 `org-time-clocksum-use-effort-durations'."
17604 (let ((clocksum "")
17605 (m (round m)) ; Don't allow fractions of minutes
17606 h d w mo y fmt n)
17607 (setq h (if org-time-clocksum-use-effort-durations
17608 (cdr (assoc "h" org-effort-durations)) 60)
17609 d (if org-time-clocksum-use-effort-durations
17610 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17611 w (if org-time-clocksum-use-effort-durations
17612 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17613 mo (if org-time-clocksum-use-effort-durations
17614 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17615 y (if org-time-clocksum-use-effort-durations
17616 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17617 ;; fractional format
17618 (if org-time-clocksum-use-fractional
17619 (cond
17620 ;; single format string
17621 ((stringp org-time-clocksum-fractional-format)
17622 (format org-time-clocksum-fractional-format (/ m (float h))))
17623 ;; choice of fractional formats for different time units
17624 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17625 (> (/ (truncate m) (* y d h)) 0))
17626 (format fmt (/ m (* y d (float h)))))
17627 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17628 (> (/ (truncate m) (* mo d h)) 0))
17629 (format fmt (/ m (* mo d (float h)))))
17630 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17631 (> (/ (truncate m) (* w d h)) 0))
17632 (format fmt (/ m (* w d (float h)))))
17633 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17634 (> (/ (truncate m) (* d h)) 0))
17635 (format fmt (/ m (* d (float h)))))
17636 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17637 (> (/ (truncate m) h) 0))
17638 (format fmt (/ m (float h))))
17639 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17640 (format fmt m))
17641 ;; fall back to smallest time unit with a format
17642 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17643 (format fmt (/ m (float h))))
17644 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17645 (format fmt (/ m (* d (float h)))))
17646 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17647 (format fmt (/ m (* w d (float h)))))
17648 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17649 (format fmt (/ m (* mo d (float h)))))
17650 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17651 (format fmt (/ m (* y d (float h))))))
17652 ;; standard (non-fractional) format, with single format string
17653 (if (stringp org-time-clocksum-format)
17654 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17655 ;; separate formats components
17656 (and (setq fmt (plist-get org-time-clocksum-format :years))
17657 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17658 (plist-get org-time-clocksum-format :require-years))
17659 (setq clocksum (concat clocksum (format fmt n))
17660 m (- m (* n y d h))))
17661 (and (setq fmt (plist-get org-time-clocksum-format :months))
17662 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17663 (plist-get org-time-clocksum-format :require-months))
17664 (setq clocksum (concat clocksum (format fmt n))
17665 m (- m (* n mo d h))))
17666 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17667 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17668 (plist-get org-time-clocksum-format :require-weeks))
17669 (setq clocksum (concat clocksum (format fmt n))
17670 m (- m (* n w d h))))
17671 (and (setq fmt (plist-get org-time-clocksum-format :days))
17672 (or (> (setq n (/ (truncate m) (* d h))) 0)
17673 (plist-get org-time-clocksum-format :require-days))
17674 (setq clocksum (concat clocksum (format fmt n))
17675 m (- m (* n d h))))
17676 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17677 (or (> (setq n (/ (truncate m) h)) 0)
17678 (plist-get org-time-clocksum-format :require-hours))
17679 (setq clocksum (concat clocksum (format fmt n))
17680 m (- m (* n h))))
17681 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17682 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17683 (setq clocksum (concat clocksum (format fmt m))))
17684 ;; return formatted time duration
17685 clocksum))))
17687 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17688 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17689 "Org mode version 8.0")
17691 (defun org-hours-to-clocksum-string (n)
17692 (org-minutes-to-clocksum-string (* n 60)))
17694 (defun org-hh:mm-string-to-minutes (s)
17695 "Convert a string H:MM to a number of minutes.
17696 If the string is just a number, interpret it as minutes.
17697 In fact, the first hh:mm or number in the string will be taken,
17698 there can be extra stuff in the string.
17699 If no number is found, the return value is 0."
17700 (cond
17701 ((integerp s) s)
17702 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17703 (+ (* (string-to-number (match-string 1 s)) 60)
17704 (string-to-number (match-string 2 s))))
17705 ((string-match "\\([0-9]+\\)" s)
17706 (string-to-number (match-string 1 s)))
17707 (t 0)))
17709 (defcustom org-image-actual-width t
17710 "Should we use the actual width of images when inlining them?
17712 When set to `t', always use the image width.
17714 When set to a number, use imagemagick (when available) to set
17715 the image's width to this value.
17717 When set to a number in a list, try to get the width from any
17718 #+ATTR.* keyword if it matches a width specification like
17720 #+ATTR_HTML: :width 300px
17722 and fall back on that number if none is found.
17724 When set to nil, try to get the width from an #+ATTR.* keyword
17725 and fall back on the original width if none is found.
17727 This requires Emacs >= 24.1, build with imagemagick support."
17728 :group 'org-appearance
17729 :version "24.4"
17730 :package-version '(Org . "8.0")
17731 :type '(choice
17732 (const :tag "Use the image width" t)
17733 (integer :tag "Use a number of pixels")
17734 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17735 (const :tag "Use #+ATTR* or don't resize" nil)))
17737 (defcustom org-agenda-inhibit-startup nil
17738 "Inhibit startup when preparing agenda buffers.
17739 When this variable is `t' (the default), the initialization of
17740 the Org agenda buffers is inhibited: e.g. the visibility state
17741 is not set, the tables are not re-aligned, etc."
17742 :type 'boolean
17743 :version "24.3"
17744 :group 'org-agenda)
17746 (defcustom org-agenda-ignore-drawer-properties nil
17747 "Avoid updating text properties when building the agenda.
17748 Properties are used to prepare buffers for effort estimates, appointments,
17749 and subtree-local categories.
17750 If you don't use these in the agenda, you can add them to this list and
17751 agenda building will be a bit faster.
17752 The value is a list, with zero or more of the symbols `effort', `appt',
17753 or `category'."
17754 :type '(set :greedy t
17755 (const effort)
17756 (const appt)
17757 (const category))
17758 :version "24.3"
17759 :group 'org-agenda)
17761 (defun org-duration-string-to-minutes (s &optional output-to-string)
17762 "Convert a duration string S to minutes.
17764 A bare number is interpreted as minutes, modifiers can be set by
17765 customizing `org-effort-durations' (which see).
17767 Entries containing a colon are interpreted as H:MM by
17768 `org-hh:mm-string-to-minutes'."
17769 (let ((result 0)
17770 (re (concat "\\([0-9.]+\\) *\\("
17771 (regexp-opt (mapcar 'car org-effort-durations))
17772 "\\)")))
17773 (while (string-match re s)
17774 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17775 (string-to-number (match-string 1 s))))
17776 (setq s (replace-match "" nil t s)))
17777 (setq result (floor result))
17778 (incf result (org-hh:mm-string-to-minutes s))
17779 (if output-to-string (number-to-string result) result)))
17781 ;;;; Files
17783 (defun org-save-all-org-buffers ()
17784 "Save all Org-mode buffers without user confirmation."
17785 (interactive)
17786 (message "Saving all Org-mode buffers...")
17787 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17788 (when (featurep 'org-id) (org-id-locations-save))
17789 (message "Saving all Org-mode buffers... done"))
17791 (defun org-revert-all-org-buffers ()
17792 "Revert all Org-mode buffers.
17793 Prompt for confirmation when there are unsaved changes.
17794 Be sure you know what you are doing before letting this function
17795 overwrite your changes.
17797 This function is useful in a setup where one tracks org files
17798 with a version control system, to revert on one machine after pulling
17799 changes from another. I believe the procedure must be like this:
17801 1. M-x org-save-all-org-buffers
17802 2. Pull changes from the other machine, resolve conflicts
17803 3. M-x org-revert-all-org-buffers"
17804 (interactive)
17805 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17806 (user-error "Abort"))
17807 (save-excursion
17808 (save-window-excursion
17809 (mapc
17810 (lambda (b)
17811 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17812 (with-current-buffer b buffer-file-name))
17813 (org-pop-to-buffer-same-window b)
17814 (revert-buffer t 'no-confirm)))
17815 (buffer-list))
17816 (when (and (featurep 'org-id) org-id-track-globally)
17817 (org-id-locations-load)))))
17819 ;;;; Agenda files
17821 ;;;###autoload
17822 (defun org-switchb (&optional arg)
17823 "Switch between Org buffers.
17824 With one prefix argument, restrict available buffers to files.
17825 With two prefix arguments, restrict available buffers to agenda files.
17827 Defaults to `iswitchb' for buffer name completion.
17828 Set `org-completion-use-ido' to make it use ido instead."
17829 (interactive "P")
17830 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17831 ((equal arg '(16)) (org-buffer-list 'agenda))
17832 (t (org-buffer-list))))
17833 (org-completion-use-iswitchb org-completion-use-iswitchb)
17834 (org-completion-use-ido org-completion-use-ido))
17835 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17836 (setq org-completion-use-iswitchb t))
17837 (org-pop-to-buffer-same-window
17838 (org-icompleting-read "Org buffer: "
17839 (mapcar 'list (mapcar 'buffer-name blist))
17840 nil t))))
17842 ;;; Define some older names previously used for this functionality
17843 ;;;###autoload
17844 (defalias 'org-ido-switchb 'org-switchb)
17845 ;;;###autoload
17846 (defalias 'org-iswitchb 'org-switchb)
17848 (defun org-buffer-list (&optional predicate exclude-tmp)
17849 "Return a list of Org buffers.
17850 PREDICATE can be `export', `files' or `agenda'.
17852 export restrict the list to Export buffers.
17853 files restrict the list to buffers visiting Org files.
17854 agenda restrict the list to buffers visiting agenda files.
17856 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17857 (let* ((bfn nil)
17858 (agenda-files (and (eq predicate 'agenda)
17859 (mapcar 'file-truename (org-agenda-files t))))
17860 (filter
17861 (cond
17862 ((eq predicate 'files)
17863 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17864 ((eq predicate 'export)
17865 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17866 ((eq predicate 'agenda)
17867 (lambda (b)
17868 (with-current-buffer b
17869 (and (derived-mode-p 'org-mode)
17870 (setq bfn (buffer-file-name b))
17871 (member (file-truename bfn) agenda-files)))))
17872 (t (lambda (b) (with-current-buffer b
17873 (or (derived-mode-p 'org-mode)
17874 (string-match "\*Org .*Export"
17875 (buffer-name b)))))))))
17876 (delq nil
17877 (mapcar
17878 (lambda(b)
17879 (if (and (funcall filter b)
17880 (or (not exclude-tmp)
17881 (not (string-match "tmp" (buffer-name b)))))
17883 nil))
17884 (buffer-list)))))
17886 (defun org-agenda-files (&optional unrestricted archives)
17887 "Get the list of agenda files.
17888 Optional UNRESTRICTED means return the full list even if a restriction
17889 is currently in place.
17890 When ARCHIVES is t, include all archive files that are really being
17891 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17892 `org-agenda-archives-mode' is t."
17893 (let ((files
17894 (cond
17895 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17896 ((stringp org-agenda-files) (org-read-agenda-file-list))
17897 ((listp org-agenda-files) org-agenda-files)
17898 (t (error "Invalid value of `org-agenda-files'")))))
17899 (setq files (apply 'append
17900 (mapcar (lambda (f)
17901 (if (file-directory-p f)
17902 (directory-files
17903 f t org-agenda-file-regexp)
17904 (list f)))
17905 files)))
17906 (when org-agenda-skip-unavailable-files
17907 (setq files (delq nil
17908 (mapcar (function
17909 (lambda (file)
17910 (and (file-readable-p file) file)))
17911 files))))
17912 (when (or (eq archives t)
17913 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17914 (setq files (org-add-archive-files files)))
17915 files))
17917 (defun org-agenda-file-p (&optional file)
17918 "Return non-nil, if FILE is an agenda file.
17919 If FILE is omitted, use the file associated with the current
17920 buffer."
17921 (member (or file (buffer-file-name))
17922 (org-agenda-files t)))
17924 (defun org-edit-agenda-file-list ()
17925 "Edit the list of agenda files.
17926 Depending on setup, this either uses customize to edit the variable
17927 `org-agenda-files', or it visits the file that is holding the list. In the
17928 latter case, the buffer is set up in a way that saving it automatically kills
17929 the buffer and restores the previous window configuration."
17930 (interactive)
17931 (if (stringp org-agenda-files)
17932 (let ((cw (current-window-configuration)))
17933 (find-file org-agenda-files)
17934 (org-set-local 'org-window-configuration cw)
17935 (org-add-hook 'after-save-hook
17936 (lambda ()
17937 (set-window-configuration
17938 (prog1 org-window-configuration
17939 (kill-buffer (current-buffer))))
17940 (org-install-agenda-files-menu)
17941 (message "New agenda file list installed"))
17942 nil 'local)
17943 (message "%s" (substitute-command-keys
17944 "Edit list and finish with \\[save-buffer]")))
17945 (customize-variable 'org-agenda-files)))
17947 (defun org-store-new-agenda-file-list (list)
17948 "Set new value for the agenda file list and save it correctly."
17949 (if (stringp org-agenda-files)
17950 (let ((fe (org-read-agenda-file-list t)) b u)
17951 (while (setq b (find-buffer-visiting org-agenda-files))
17952 (kill-buffer b))
17953 (with-temp-file org-agenda-files
17954 (insert
17955 (mapconcat
17956 (lambda (f) ;; Keep un-expanded entries.
17957 (if (setq u (assoc f fe))
17958 (cdr u)
17960 list "\n")
17961 "\n")))
17962 (let ((org-mode-hook nil) (org-inhibit-startup t)
17963 (org-insert-mode-line-in-empty-file nil))
17964 (setq org-agenda-files list)
17965 (customize-save-variable 'org-agenda-files org-agenda-files))))
17967 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17968 "Read the list of agenda files from a file.
17969 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17970 filenames, used by `org-store-new-agenda-file-list' to write back
17971 un-expanded file names."
17972 (when (file-directory-p org-agenda-files)
17973 (error "`org-agenda-files' cannot be a single directory"))
17974 (when (stringp org-agenda-files)
17975 (with-temp-buffer
17976 (insert-file-contents org-agenda-files)
17977 (mapcar
17978 (lambda (f)
17979 (let ((e (expand-file-name (substitute-in-file-name f)
17980 org-directory)))
17981 (if pair-with-expansion
17982 (cons e f)
17983 e)))
17984 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17986 ;;;###autoload
17987 (defun org-cycle-agenda-files ()
17988 "Cycle through the files in `org-agenda-files'.
17989 If the current buffer visits an agenda file, find the next one in the list.
17990 If the current buffer does not, find the first agenda file."
17991 (interactive)
17992 (let* ((fs (org-agenda-files t))
17993 (files (append fs (list (car fs))))
17994 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17995 file)
17996 (unless files (user-error "No agenda files"))
17997 (catch 'exit
17998 (while (setq file (pop files))
17999 (if (equal (file-truename file) tcf)
18000 (when (car files)
18001 (find-file (car files))
18002 (throw 'exit t))))
18003 (find-file (car fs)))
18004 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
18006 (defun org-agenda-file-to-front (&optional to-end)
18007 "Move/add the current file to the top of the agenda file list.
18008 If the file is not present in the list, it is added to the front. If it is
18009 present, it is moved there. With optional argument TO-END, add/move to the
18010 end of the list."
18011 (interactive "P")
18012 (let ((org-agenda-skip-unavailable-files nil)
18013 (file-alist (mapcar (lambda (x)
18014 (cons (file-truename x) x))
18015 (org-agenda-files t)))
18016 (ctf (file-truename
18017 (or buffer-file-name
18018 (user-error "Please save the current buffer to a file"))))
18019 x had)
18020 (setq x (assoc ctf file-alist) had x)
18022 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18023 (if to-end
18024 (setq file-alist (append (delq x file-alist) (list x)))
18025 (setq file-alist (cons x (delq x file-alist))))
18026 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18027 (org-install-agenda-files-menu)
18028 (message "File %s to %s of agenda file list"
18029 (if had "moved" "added") (if to-end "end" "front"))))
18031 (defun org-remove-file (&optional file)
18032 "Remove current file from the list of files in variable `org-agenda-files'.
18033 These are the files which are being checked for agenda entries.
18034 Optional argument FILE means use this file instead of the current."
18035 (interactive)
18036 (let* ((org-agenda-skip-unavailable-files nil)
18037 (file (or file buffer-file-name
18038 (user-error "Current buffer does not visit a file")))
18039 (true-file (file-truename file))
18040 (afile (abbreviate-file-name file))
18041 (files (delq nil (mapcar
18042 (lambda (x)
18043 (if (equal true-file
18044 (file-truename x))
18045 nil x))
18046 (org-agenda-files t)))))
18047 (if (not (= (length files) (length (org-agenda-files t))))
18048 (progn
18049 (org-store-new-agenda-file-list files)
18050 (org-install-agenda-files-menu)
18051 (message "Removed file: %s" afile))
18052 (message "File was not in list: %s (not removed)" afile))))
18054 (defun org-file-menu-entry (file)
18055 (vector file (list 'find-file file) t))
18057 (defun org-check-agenda-file (file)
18058 "Make sure FILE exists. If not, ask user what to do."
18059 (when (not (file-exists-p file))
18060 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18061 (abbreviate-file-name file))
18062 (let ((r (downcase (read-char-exclusive))))
18063 (cond
18064 ((equal r ?r)
18065 (org-remove-file file)
18066 (throw 'nextfile t))
18067 (t (error "Abort"))))))
18069 (defun org-get-agenda-file-buffer (file)
18070 "Get a buffer visiting FILE. If the buffer needs to be created, add
18071 it to the list of buffers which might be released later."
18072 (let ((buf (org-find-base-buffer-visiting file)))
18073 (if buf
18074 buf ; just return it
18075 ;; Make a new buffer and remember it
18076 (setq buf (find-file-noselect file))
18077 (if buf (push buf org-agenda-new-buffers))
18078 buf)))
18080 (defun org-release-buffers (blist)
18081 "Release all buffers in list, asking the user for confirmation when needed.
18082 When a buffer is unmodified, it is just killed. When modified, it is saved
18083 \(if the user agrees) and then killed."
18084 (let (buf file)
18085 (while (setq buf (pop blist))
18086 (setq file (buffer-file-name buf))
18087 (when (and (buffer-modified-p buf)
18088 file
18089 (y-or-n-p (format "Save file %s? " file)))
18090 (with-current-buffer buf (save-buffer)))
18091 (kill-buffer buf))))
18093 (defun org-agenda-prepare-buffers (files)
18094 "Create buffers for all agenda files, protect archived trees and comments."
18095 (interactive)
18096 (let ((pa '(:org-archived t))
18097 (pc '(:org-comment t))
18098 (pall '(:org-archived t :org-comment t))
18099 (inhibit-read-only t)
18100 (org-inhibit-startup org-agenda-inhibit-startup)
18101 (rea (concat ":" org-archive-tag ":"))
18102 file re pos)
18103 (setq org-tag-alist-for-agenda nil
18104 org-tag-groups-alist-for-agenda nil)
18105 (save-window-excursion
18106 (save-restriction
18107 (while (setq file (pop files))
18108 (catch 'nextfile
18109 (if (bufferp file)
18110 (set-buffer file)
18111 (org-check-agenda-file file)
18112 (set-buffer (org-get-agenda-file-buffer file)))
18113 (widen)
18114 (org-set-regexps-and-options-for-tags)
18115 (setq pos (point))
18116 (goto-char (point-min))
18117 (let ((case-fold-search t))
18118 (when (search-forward "#+setupfile" nil t)
18119 ;; Don't set all regexps and options systematically as
18120 ;; this is only run for setting agenda tags from setup
18121 ;; file
18122 (org-set-regexps-and-options)))
18123 (or (memq 'category org-agenda-ignore-drawer-properties)
18124 (org-refresh-category-properties))
18125 (or (memq 'effort org-agenda-ignore-drawer-properties)
18126 (org-refresh-properties org-effort-property 'org-effort))
18127 (or (memq 'appt org-agenda-ignore-drawer-properties)
18128 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18129 (setq org-todo-keywords-for-agenda
18130 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18131 (setq org-done-keywords-for-agenda
18132 (append org-done-keywords-for-agenda org-done-keywords))
18133 (setq org-todo-keyword-alist-for-agenda
18134 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18135 (setq org-tag-alist-for-agenda
18136 (org-uniquify
18137 (append org-tag-alist-for-agenda
18138 org-tag-alist
18139 org-tag-persistent-alist)))
18140 (if org-group-tags
18141 (setq org-tag-groups-alist-for-agenda
18142 (org-uniquify-alist
18143 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18144 (org-with-silent-modifications
18145 (save-excursion
18146 (remove-text-properties (point-min) (point-max) pall)
18147 (when org-agenda-skip-archived-trees
18148 (goto-char (point-min))
18149 (while (re-search-forward rea nil t)
18150 (if (org-at-heading-p t)
18151 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18152 (goto-char (point-min))
18153 (setq re (format org-heading-keyword-regexp-format
18154 org-comment-string))
18155 (while (re-search-forward re nil t)
18156 (add-text-properties
18157 (match-beginning 0) (org-end-of-subtree t) pc))))
18158 (goto-char pos)))))
18159 (setq org-todo-keywords-for-agenda
18160 (org-uniquify org-todo-keywords-for-agenda))
18161 (setq org-todo-keyword-alist-for-agenda
18162 (org-uniquify org-todo-keyword-alist-for-agenda))))
18165 ;;;; CDLaTeX minor mode
18167 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18168 "Keymap for the minor `org-cdlatex-mode'.")
18170 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18171 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18172 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18173 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18174 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
18176 (defvar org-cdlatex-texmathp-advice-is-done nil
18177 "Flag remembering if we have applied the advice to texmathp already.")
18179 (define-minor-mode org-cdlatex-mode
18180 "Toggle the minor `org-cdlatex-mode'.
18181 This mode supports entering LaTeX environment and math in LaTeX fragments
18182 in Org-mode.
18183 \\{org-cdlatex-mode-map}"
18184 nil " OCDL" nil
18185 (when org-cdlatex-mode
18186 (require 'cdlatex)
18187 (run-hooks 'cdlatex-mode-hook)
18188 (cdlatex-compute-tables))
18189 (unless org-cdlatex-texmathp-advice-is-done
18190 (setq org-cdlatex-texmathp-advice-is-done t)
18191 (defadvice texmathp (around org-math-always-on activate)
18192 "Always return t in org-mode buffers.
18193 This is because we want to insert math symbols without dollars even outside
18194 the LaTeX math segments. If Orgmode thinks that point is actually inside
18195 an embedded LaTeX fragment, let texmathp do its job.
18196 \\[org-cdlatex-mode-map]"
18197 (interactive)
18198 (let (p)
18199 (cond
18200 ((not (derived-mode-p 'org-mode)) ad-do-it)
18201 ((eq this-command 'cdlatex-math-symbol)
18202 (setq ad-return-value t
18203 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18205 (let ((p (org-inside-LaTeX-fragment-p)))
18206 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18207 (setq ad-return-value t
18208 texmathp-why '("Org-mode embedded math" . 0))
18209 (if p ad-do-it)))))))))
18211 (defun turn-on-org-cdlatex ()
18212 "Unconditionally turn on `org-cdlatex-mode'."
18213 (org-cdlatex-mode 1))
18215 (defun org-try-cdlatex-tab ()
18216 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18217 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18218 - inside a LaTeX fragment, or
18219 - after the first word in a line, where an abbreviation expansion could
18220 insert a LaTeX environment."
18221 (when org-cdlatex-mode
18222 (cond
18223 ;; Before any word on the line: No expansion possible.
18224 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18225 ;; Just after first word on the line: Expand it. Make sure it
18226 ;; cannot happen on headlines, though.
18227 ((save-excursion
18228 (skip-chars-backward "a-zA-Z0-9*")
18229 (skip-chars-backward " \t")
18230 (and (bolp) (not (org-at-heading-p))))
18231 (cdlatex-tab) t)
18232 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18234 (defun org-cdlatex-underscore-caret (&optional arg)
18235 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18236 Revert to the normal definition outside of these fragments."
18237 (interactive "P")
18238 (if (org-inside-LaTeX-fragment-p)
18239 (call-interactively 'cdlatex-sub-superscript)
18240 (let (org-cdlatex-mode)
18241 (call-interactively (key-binding (vector last-input-event))))))
18243 (defun org-cdlatex-math-modify (&optional arg)
18244 "Execute `cdlatex-math-modify' in LaTeX fragments.
18245 Revert to the normal definition outside of these fragments."
18246 (interactive "P")
18247 (if (org-inside-LaTeX-fragment-p)
18248 (call-interactively 'cdlatex-math-modify)
18249 (let (org-cdlatex-mode)
18250 (call-interactively (key-binding (vector last-input-event))))))
18254 ;;;; LaTeX fragments
18256 (defun org-inside-LaTeX-fragment-p ()
18257 "Test if point is inside a LaTeX fragment.
18258 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18259 sequence appearing also before point.
18260 Even though the matchers for math are configurable, this function assumes
18261 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18262 delimiters are skipped when they have been removed by customization.
18263 The return value is nil, or a cons cell with the delimiter and the
18264 position of this delimiter.
18266 This function does a reasonably good job, but can locally be fooled by
18267 for example currency specifications. For example it will assume being in
18268 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18269 fragments that are properly closed, but during editing, we have to live
18270 with the uncertainty caused by missing closing delimiters. This function
18271 looks only before point, not after."
18272 (catch 'exit
18273 (let ((pos (point))
18274 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18275 (lim (progn
18276 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18277 (point)))
18278 dd-on str (start 0) m re)
18279 (goto-char pos)
18280 (when dodollar
18281 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18282 re (nth 1 (assoc "$" org-latex-regexps)))
18283 (while (string-match re str start)
18284 (cond
18285 ((= (match-end 0) (length str))
18286 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18287 ((= (match-end 0) (- (length str) 5))
18288 (throw 'exit nil))
18289 (t (setq start (match-end 0))))))
18290 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18291 (goto-char pos)
18292 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18293 (and (match-beginning 2) (throw 'exit nil))
18294 ;; count $$
18295 (while (re-search-backward "\\$\\$" lim t)
18296 (setq dd-on (not dd-on)))
18297 (goto-char pos)
18298 (if dd-on (cons "$$" m))))))
18300 (defun org-inside-latex-macro-p ()
18301 "Is point inside a LaTeX macro or its arguments?"
18302 (save-match-data
18303 (org-in-regexp
18304 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18306 (defvar org-latex-fragment-image-overlays nil
18307 "List of overlays carrying the images of latex fragments.")
18308 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18310 (defun org-remove-latex-fragment-image-overlays ()
18311 "Remove all overlays with LaTeX fragment images in current buffer."
18312 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18313 (setq org-latex-fragment-image-overlays nil))
18315 (defun org-preview-latex-fragment (&optional subtree)
18316 "Preview the LaTeX fragment at point, or all locally or globally.
18317 If the cursor is in a LaTeX fragment, create the image and overlay
18318 it over the source code. If there is no fragment at point, display
18319 all fragments in the current text, from one headline to the next. With
18320 prefix SUBTREE, display all fragments in the current subtree. With a
18321 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18322 the cursor is before the first headline,
18323 display all fragments in the buffer.
18324 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18325 (interactive "P")
18326 (unless buffer-file-name
18327 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18328 (when (display-graphic-p)
18329 (org-remove-latex-fragment-image-overlays)
18330 (save-excursion
18331 (save-restriction
18332 (let (beg end at msg)
18333 (cond
18334 ((or (equal subtree '(16))
18335 (not (save-excursion
18336 (re-search-backward org-outline-regexp-bol nil t))))
18337 (setq beg (point-min) end (point-max)
18338 msg "Creating images for buffer...%s"))
18339 ((equal subtree '(4))
18340 (org-back-to-heading)
18341 (setq beg (point) end (org-end-of-subtree t)
18342 msg "Creating images for subtree...%s"))
18344 (if (setq at (org-inside-LaTeX-fragment-p))
18345 (goto-char (max (point-min) (- (cdr at) 2)))
18346 (org-back-to-heading))
18347 (setq beg (point) end (progn (outline-next-heading) (point))
18348 msg (if at "Creating image...%s"
18349 "Creating images for entry...%s"))))
18350 (message msg "")
18351 (narrow-to-region beg end)
18352 (goto-char beg)
18353 (org-format-latex
18354 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18355 (file-name-nondirectory
18356 buffer-file-name)))
18357 default-directory 'overlays msg at 'forbuffer
18358 org-latex-create-formula-image-program)
18359 (message msg "done. Use `C-c C-c' to remove images."))))))
18361 (defun org-format-latex (prefix &optional dir overlays msg at
18362 forbuffer processing-type)
18363 "Replace LaTeX fragments with links to an image, and produce images.
18364 Some of the options can be changed using the variable
18365 `org-format-latex-options'."
18366 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18367 (let* ((prefixnodir (file-name-nondirectory prefix))
18368 (absprefix (expand-file-name prefix dir))
18369 (todir (file-name-directory absprefix))
18370 (opt org-format-latex-options)
18371 (optnew org-format-latex-options)
18372 (matchers (plist-get opt :matchers))
18373 (re-list org-latex-regexps)
18374 (cnt 0) txt hash link beg end re e checkdir
18375 string
18376 m n block-type block linkfile movefile ov)
18377 ;; Check the different regular expressions
18378 (while (setq e (pop re-list))
18379 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18380 block (if block-type "\n\n" ""))
18381 (when (member m matchers)
18382 (goto-char (point-min))
18383 (while (re-search-forward re nil t)
18384 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18385 (or (not overlays)
18386 (not (eq (get-char-property (match-beginning n)
18387 'org-overlay-type)
18388 'org-latex-overlay))))
18389 (cond
18390 ((eq processing-type 'verbatim))
18391 ((eq processing-type 'mathjax)
18392 ;; Prepare for MathJax processing.
18393 (setq string (match-string n))
18394 (when (member m '("$" "$1"))
18395 (save-excursion
18396 (delete-region (match-beginning n) (match-end n))
18397 (goto-char (match-beginning n))
18398 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18399 ((or (eq processing-type 'dvipng)
18400 (eq processing-type 'imagemagick))
18401 ;; Process to an image.
18402 (setq txt (match-string n)
18403 beg (match-beginning n) end (match-end n)
18404 cnt (1+ cnt))
18405 (let ((face (face-at-point))
18406 (fg (plist-get opt :foreground))
18407 (bg (plist-get opt :background))
18408 ;; Ensure full list is printed.
18409 print-length print-level)
18410 (when forbuffer
18411 ;; Get the colors from the face at point.
18412 (goto-char beg)
18413 (when (eq fg 'auto)
18414 (setq fg (face-attribute face :foreground nil 'default)))
18415 (when (eq bg 'auto)
18416 (setq bg (face-attribute face :background nil 'default)))
18417 (setq optnew (copy-sequence opt))
18418 (plist-put optnew :foreground fg)
18419 (plist-put optnew :background bg))
18420 (setq hash (sha1 (prin1-to-string
18421 (list org-format-latex-header
18422 org-latex-default-packages-alist
18423 org-latex-packages-alist
18424 org-format-latex-options
18425 forbuffer txt fg bg)))
18426 linkfile (format "%s_%s.png" prefix hash)
18427 movefile (format "%s_%s.png" absprefix hash)))
18428 (setq link (concat block "[[file:" linkfile "]]" block))
18429 (if msg (message msg cnt))
18430 (goto-char beg)
18431 (unless checkdir ; Ensure the directory exists.
18432 (setq checkdir t)
18433 (or (file-directory-p todir) (make-directory todir t)))
18434 (unless (file-exists-p movefile)
18435 (org-create-formula-image
18436 txt movefile optnew forbuffer processing-type))
18437 (if overlays
18438 (progn
18439 (mapc (lambda (o)
18440 (if (eq (overlay-get o 'org-overlay-type)
18441 'org-latex-overlay)
18442 (delete-overlay o)))
18443 (overlays-in beg end))
18444 (setq ov (make-overlay beg end))
18445 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18446 (if (featurep 'xemacs)
18447 (progn
18448 (overlay-put ov 'invisible t)
18449 (overlay-put
18450 ov 'end-glyph
18451 (make-glyph (vector 'png :file movefile))))
18452 (overlay-put
18453 ov 'display
18454 (list 'image :type 'png :file movefile :ascent 'center)))
18455 (push ov org-latex-fragment-image-overlays)
18456 (goto-char end))
18457 (delete-region beg end)
18458 (insert (org-add-props link
18459 (list 'org-latex-src
18460 (replace-regexp-in-string
18461 "\"" "" txt)
18462 'org-latex-src-embed-type
18463 (if block-type 'paragraph 'character))))))
18464 ((eq processing-type 'mathml)
18465 ;; Process to MathML
18466 (unless (save-match-data (org-format-latex-mathml-available-p))
18467 (user-error "LaTeX to MathML converter not configured"))
18468 (setq txt (match-string n)
18469 beg (match-beginning n) end (match-end n)
18470 cnt (1+ cnt))
18471 (if msg (message msg cnt))
18472 (goto-char beg)
18473 (delete-region beg end)
18474 (insert (org-format-latex-as-mathml
18475 txt block-type prefix dir)))
18477 (error "Unknown conversion type %s for LaTeX fragments"
18478 processing-type)))))))))
18480 (defun org-create-math-formula (latex-frag &optional mathml-file)
18481 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18482 Use `org-latex-to-mathml-convert-command'. If the conversion is
18483 sucessful, return the portion between \"<math...> </math>\"
18484 elements otherwise return nil. When MATHML-FILE is specified,
18485 write the results in to that file. When invoked as an
18486 interactive command, prompt for LATEX-FRAG, with initial value
18487 set to the current active region and echo the results for user
18488 inspection."
18489 (interactive (list (let ((frag (when (org-region-active-p)
18490 (buffer-substring-no-properties
18491 (region-beginning) (region-end)))))
18492 (read-string "LaTeX Fragment: " frag nil frag))))
18493 (unless latex-frag (error "Invalid LaTeX fragment"))
18494 (let* ((tmp-in-file (file-relative-name
18495 (make-temp-name (expand-file-name "ltxmathml-in"))))
18496 (ignore (write-region latex-frag nil tmp-in-file))
18497 (tmp-out-file (file-relative-name
18498 (make-temp-name (expand-file-name "ltxmathml-out"))))
18499 (cmd (format-spec
18500 org-latex-to-mathml-convert-command
18501 `((?j . ,(shell-quote-argument
18502 (expand-file-name org-latex-to-mathml-jar-file)))
18503 (?I . ,(shell-quote-argument tmp-in-file))
18504 (?o . ,(shell-quote-argument tmp-out-file)))))
18505 mathml shell-command-output)
18506 (when (org-called-interactively-p 'any)
18507 (unless (org-format-latex-mathml-available-p)
18508 (user-error "LaTeX to MathML converter not configured")))
18509 (message "Running %s" cmd)
18510 (setq shell-command-output (shell-command-to-string cmd))
18511 (setq mathml
18512 (when (file-readable-p tmp-out-file)
18513 (with-current-buffer (find-file-noselect tmp-out-file t)
18514 (goto-char (point-min))
18515 (when (re-search-forward
18516 (concat
18517 (regexp-quote
18518 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18519 "\\(.\\|\n\\)*"
18520 (regexp-quote "</math>")) nil t)
18521 (prog1 (match-string 0) (kill-buffer))))))
18522 (cond
18523 (mathml
18524 (setq mathml
18525 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18526 (when mathml-file
18527 (write-region mathml nil mathml-file))
18528 (when (org-called-interactively-p 'any)
18529 (message mathml)))
18530 ((message "LaTeX to MathML conversion failed")
18531 (message shell-command-output)))
18532 (delete-file tmp-in-file)
18533 (when (file-exists-p tmp-out-file)
18534 (delete-file tmp-out-file))
18535 mathml))
18537 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18538 prefix &optional dir)
18539 "Use `org-create-math-formula' but check local cache first."
18540 (let* ((absprefix (expand-file-name prefix dir))
18541 (print-length nil) (print-level nil)
18542 (formula-id (concat
18543 "formula-"
18544 (sha1
18545 (prin1-to-string
18546 (list latex-frag
18547 org-latex-to-mathml-convert-command)))))
18548 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18549 (formula-cache-dir (file-name-directory formula-cache)))
18551 (unless (file-directory-p formula-cache-dir)
18552 (make-directory formula-cache-dir t))
18554 (unless (file-exists-p formula-cache)
18555 (org-create-math-formula latex-frag formula-cache))
18557 (if (file-exists-p formula-cache)
18558 ;; Successful conversion. Return the link to MathML file.
18559 (org-add-props
18560 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18561 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18562 'org-latex-src-embed-type (if latex-frag-type
18563 'paragraph 'character)))
18564 ;; Failed conversion. Return the LaTeX fragment verbatim
18565 latex-frag)))
18567 (defun org-create-formula-image (string tofile options buffer &optional type)
18568 "Create an image from LaTeX source using dvipng or convert.
18569 This function calls either `org-create-formula-image-with-dvipng'
18570 or `org-create-formula-image-with-imagemagick' depending on the
18571 value of `org-latex-create-formula-image-program' or on the value
18572 of the optional TYPE variable.
18574 Note: ultimately these two function should be combined as they
18575 share a good deal of logic."
18576 (org-check-external-command
18577 "latex" "needed to convert LaTeX fragments to images")
18578 (funcall
18579 (case (or type org-latex-create-formula-image-program)
18580 ('dvipng
18581 (org-check-external-command
18582 "dvipng" "needed to convert LaTeX fragments to images")
18583 #'org-create-formula-image-with-dvipng)
18584 ('imagemagick
18585 (org-check-external-command
18586 "convert" "you need to install imagemagick")
18587 #'org-create-formula-image-with-imagemagick)
18588 (t (error
18589 "Invalid value of `org-latex-create-formula-image-program'")))
18590 string tofile options buffer))
18592 (declare-function org-export-get-backend "ox" (name))
18593 (declare-function org-export--get-global-options "ox" (&optional backend))
18594 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18595 (declare-function org-latex-guess-inputenc "ox-latex" (header))
18596 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
18597 (defun org-create-formula--latex-header ()
18598 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18599 (let ((info (org-combine-plists (org-export--get-global-options
18600 (org-export-get-backend 'latex))
18601 (org-export--get-inbuffer-options
18602 (org-export-get-backend 'latex)))))
18603 (org-latex-guess-babel-language
18604 (org-latex-guess-inputenc
18605 (org-splice-latex-header
18606 org-format-latex-header
18607 org-latex-default-packages-alist
18608 org-latex-packages-alist t
18609 (plist-get info :latex-header)))
18610 info)))
18612 ;; This function borrows from Ganesh Swami's latex2png.el
18613 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18614 "This calls dvipng."
18615 (require 'ox-latex)
18616 (let* ((tmpdir (if (featurep 'xemacs)
18617 (temp-directory)
18618 temporary-file-directory))
18619 (texfilebase (make-temp-name
18620 (expand-file-name "orgtex" tmpdir)))
18621 (texfile (concat texfilebase ".tex"))
18622 (dvifile (concat texfilebase ".dvi"))
18623 (pngfile (concat texfilebase ".png"))
18624 (fnh (if (featurep 'xemacs)
18625 (font-height (face-font 'default))
18626 (face-attribute 'default :height nil)))
18627 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18628 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18629 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18630 "Black"))
18631 (bg (or (plist-get options (if buffer :background :html-background))
18632 "Transparent")))
18633 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18634 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18635 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18636 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18637 (let ((latex-header (org-create-formula--latex-header)))
18638 (with-temp-file texfile
18639 (insert latex-header)
18640 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18641 (let ((dir default-directory))
18642 (condition-case nil
18643 (progn
18644 (cd tmpdir)
18645 (call-process "latex" nil nil nil texfile))
18646 (error nil))
18647 (cd dir))
18648 (if (not (file-exists-p dvifile))
18649 (progn (message "Failed to create dvi file from %s" texfile) nil)
18650 (condition-case nil
18651 (if (featurep 'xemacs)
18652 (call-process "dvipng" nil nil nil
18653 "-fg" fg "-bg" bg
18654 "-T" "tight"
18655 "-o" pngfile
18656 dvifile)
18657 (call-process "dvipng" nil nil nil
18658 "-fg" fg "-bg" bg
18659 "-D" dpi
18660 ;;"-x" scale "-y" scale
18661 "-T" "tight"
18662 "-o" pngfile
18663 dvifile))
18664 (error nil))
18665 (if (not (file-exists-p pngfile))
18666 (if org-format-latex-signal-error
18667 (error "Failed to create png file from %s" texfile)
18668 (message "Failed to create png file from %s" texfile)
18669 nil)
18670 ;; Use the requested file name and clean up
18671 (copy-file pngfile tofile 'replace)
18672 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18673 (if (file-exists-p (concat texfilebase e))
18674 (delete-file (concat texfilebase e))))
18675 pngfile))))
18677 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18678 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18679 "This calls convert, which is included into imagemagick."
18680 (require 'ox-latex)
18681 (let* ((tmpdir (if (featurep 'xemacs)
18682 (temp-directory)
18683 temporary-file-directory))
18684 (texfilebase (make-temp-name
18685 (expand-file-name "orgtex" tmpdir)))
18686 (texfile (concat texfilebase ".tex"))
18687 (pdffile (concat texfilebase ".pdf"))
18688 (pngfile (concat texfilebase ".png"))
18689 (fnh (if (featurep 'xemacs)
18690 (font-height (face-font 'default))
18691 (face-attribute 'default :height nil)))
18692 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18693 (dpi (number-to-string (* scale (floor (if buffer fnh 120.)))))
18694 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18695 "black"))
18696 (bg (or (plist-get options (if buffer :background :html-background))
18697 "white")))
18698 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18699 (setq fg (org-latex-color-format fg)))
18700 (if (eq bg 'default) (setq bg (org-latex-color :background))
18701 (setq bg (org-latex-color-format
18702 (if (string= bg "Transparent") "white" bg))))
18703 (let ((latex-header (org-create-formula--latex-header)))
18704 (with-temp-file texfile
18705 (insert latex-header)
18706 (insert "\n\\begin{document}\n"
18707 "\\definecolor{fg}{rgb}{" fg "}\n"
18708 "\\definecolor{bg}{rgb}{" bg "}\n"
18709 "\n\\pagecolor{bg}\n"
18710 "\n{\\color{fg}\n"
18711 string
18712 "\n}\n"
18713 "\n\\end{document}\n")))
18714 (org-latex-compile texfile t)
18715 (if (not (file-exists-p pdffile))
18716 (progn (message "Failed to create pdf file from %s" texfile) nil)
18717 (condition-case nil
18718 (if (featurep 'xemacs)
18719 (call-process "convert" nil nil nil
18720 "-density" "96"
18721 "-trim"
18722 "-antialias"
18723 pdffile
18724 "-quality" "100"
18725 ;; "-sharpen" "0x1.0"
18726 pngfile)
18727 (call-process "convert" nil nil nil
18728 "-density" dpi
18729 "-trim"
18730 "-antialias"
18731 pdffile
18732 "-quality" "100"
18733 ;; "-sharpen" "0x1.0"
18734 pngfile))
18735 (error nil))
18736 (if (not (file-exists-p pngfile))
18737 (if org-format-latex-signal-error
18738 (error "Failed to create png file from %s" texfile)
18739 (message "Failed to create png file from %s" texfile)
18740 nil)
18741 ;; Use the requested file name and clean up
18742 (copy-file pngfile tofile 'replace)
18743 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18744 (if (file-exists-p (concat texfilebase e))
18745 (delete-file (concat texfilebase e))))
18746 pngfile))))
18748 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18749 "Fill a LaTeX header template TPL.
18750 In the template, the following place holders will be recognized:
18752 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18753 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18754 [PACKAGES] \\usepackage statements for PKG
18755 [NO-PACKAGES] do not include PKG
18756 [EXTRA] the string EXTRA
18757 [NO-EXTRA] do not include EXTRA
18759 For backward compatibility, if both the positive and the negative place
18760 holder is missing, the positive one (without the \"NO-\") will be
18761 assumed to be present at the end of the template.
18762 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18763 EXTRA is a string.
18764 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18765 (let (rpl (end ""))
18766 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18767 (setq rpl (if (or (match-end 1) (not def-pkg))
18768 "" (org-latex-packages-to-string def-pkg snippets-p t))
18769 tpl (replace-match rpl t t tpl))
18770 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18772 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18773 (setq rpl (if (or (match-end 1) (not pkg))
18774 "" (org-latex-packages-to-string pkg snippets-p t))
18775 tpl (replace-match rpl t t tpl))
18776 (if pkg (setq end
18777 (concat end "\n"
18778 (org-latex-packages-to-string pkg snippets-p)))))
18780 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18781 (setq rpl (if (or (match-end 1) (not extra))
18782 "" (concat extra "\n"))
18783 tpl (replace-match rpl t t tpl))
18784 (if (and extra (string-match "\\S-" extra))
18785 (setq end (concat end "\n" extra))))
18787 (if (string-match "\\S-" end)
18788 (concat tpl "\n" end)
18789 tpl)))
18791 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18792 "Turn an alist of packages into a string with the \\usepackage macros."
18793 (setq pkg (mapconcat (lambda(p)
18794 (cond
18795 ((stringp p) p)
18796 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18797 (format "%% Package %s omitted" (cadr p)))
18798 ((equal "" (car p))
18799 (format "\\usepackage{%s}" (cadr p)))
18801 (format "\\usepackage[%s]{%s}"
18802 (car p) (cadr p)))))
18804 "\n"))
18805 (if newline (concat pkg "\n") pkg))
18807 (defun org-dvipng-color (attr)
18808 "Return a RGB color specification for dvipng."
18809 (apply 'format "rgb %s %s %s"
18810 (mapcar 'org-normalize-color
18811 (if (featurep 'xemacs)
18812 (color-rgb-components
18813 (face-property 'default
18814 (cond ((eq attr :foreground) 'foreground)
18815 ((eq attr :background) 'background))))
18816 (color-values (face-attribute 'default attr nil))))))
18818 (defun org-dvipng-color-format (color-name)
18819 "Convert COLOR-NAME to a RGB color value for dvipng."
18820 (apply 'format "rgb %s %s %s"
18821 (mapcar 'org-normalize-color
18822 (color-values color-name))))
18824 (defun org-latex-color (attr)
18825 "Return a RGB color for the LaTeX color package."
18826 (apply 'format "%s,%s,%s"
18827 (mapcar 'org-normalize-color
18828 (if (featurep 'xemacs)
18829 (color-rgb-components
18830 (face-property 'default
18831 (cond ((eq attr :foreground) 'foreground)
18832 ((eq attr :background) 'background))))
18833 (color-values (face-attribute 'default attr nil))))))
18835 (defun org-latex-color-format (color-name)
18836 "Convert COLOR-NAME to a RGB color value."
18837 (apply 'format "%s,%s,%s"
18838 (mapcar 'org-normalize-color
18839 (color-values color-name))))
18841 (defun org-normalize-color (value)
18842 "Return string to be used as color value for an RGB component."
18843 (format "%g" (/ value 65535.0)))
18847 ;; Image display
18849 (defvar org-inline-image-overlays nil)
18850 (make-variable-buffer-local 'org-inline-image-overlays)
18852 (defun org-toggle-inline-images (&optional include-linked)
18853 "Toggle the display of inline images.
18854 INCLUDE-LINKED is passed to `org-display-inline-images'."
18855 (interactive "P")
18856 (if org-inline-image-overlays
18857 (progn
18858 (org-remove-inline-images)
18859 (message "Inline image display turned off"))
18860 (org-display-inline-images include-linked)
18861 (if (and (org-called-interactively-p)
18862 org-inline-image-overlays)
18863 (message "%d images displayed inline"
18864 (length org-inline-image-overlays))
18865 (message "No images to display inline"))))
18867 (defun org-redisplay-inline-images ()
18868 "Refresh the display of inline images."
18869 (interactive)
18870 (if (not org-inline-image-overlays)
18871 (org-toggle-inline-images)
18872 (org-toggle-inline-images)
18873 (org-toggle-inline-images)))
18875 (defun org-display-inline-images (&optional include-linked refresh beg end)
18876 "Display inline images.
18878 An inline image is a link which follows either of these
18879 conventions:
18881 1. Its path is a file with an extension matching return value
18882 from `image-file-name-regexp' and it has no contents.
18884 2. Its description consists in a single link of the previous
18885 type.
18887 When optional argument INCLUDE-LINKED is non-nil, also links with
18888 a text description part will be inlined. This can be nice for
18889 a quick look at those images, but it does not reflect what
18890 exported files will look like.
18892 When optional argument REFRESH is non-nil, refresh existing
18893 images between BEG and END. This will create new image displays
18894 only if necessary. BEG and END default to the buffer
18895 boundaries."
18896 (interactive "P")
18897 (when (display-graphic-p)
18898 (unless refresh
18899 (org-remove-inline-images)
18900 (when (fboundp 'clear-image-cache) (clear-image-cache)))
18901 (org-with-wide-buffer
18902 (goto-char (or beg (point-min)))
18903 (let ((case-fold-search t)
18904 (file-extension-re (org-image-file-name-regexp)))
18905 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
18906 (let ((link (save-match-data (org-element-context))))
18907 ;; Check if we're at an inline image.
18908 (when (and (equal (org-element-property :type link) "file")
18909 (or include-linked
18910 (not (org-element-property :contents-begin link)))
18911 (let ((parent (org-element-property :parent link)))
18912 (or (not (eq (org-element-type parent) 'link))
18913 (not (cdr (org-element-contents parent)))))
18914 (org-string-match-p file-extension-re
18915 (org-element-property :path link)))
18916 (let ((file (expand-file-name (org-element-property :path link))))
18917 (when (file-exists-p file)
18918 (let ((width
18919 ;; Apply `org-image-actual-width' specifications.
18920 (cond
18921 ((not (image-type-available-p 'imagemagick)) nil)
18922 ((eq org-image-actual-width t) nil)
18923 ((listp org-image-actual-width)
18925 ;; First try to find a width among
18926 ;; attributes associated to the paragraph
18927 ;; containing link.
18928 (let ((paragraph
18929 (let ((e link))
18930 (while (and (setq e (org-element-property
18931 :parent e))
18932 (not (eq (org-element-type e)
18933 'paragraph))))
18934 e)))
18935 (when paragraph
18936 (save-excursion
18937 (goto-char (org-element-property :begin paragraph))
18938 (when (save-match-data
18939 (re-search-forward
18940 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
18941 (org-element-property
18942 :post-affiliated paragraph)
18944 (string-to-number (match-string 1))))))
18945 ;; Otherwise, fall-back to provided number.
18946 (car org-image-actual-width)))
18947 ((numberp org-image-actual-width)
18948 org-image-actual-width)))
18949 (old (get-char-property-and-overlay
18950 (org-element-property :begin link)
18951 'org-image-overlay)))
18952 (if (and (car-safe old) refresh)
18953 (image-refresh (overlay-get (cdr old) 'display))
18954 (let ((image (save-match-data
18955 (create-image file
18956 (and width 'imagemagick)
18958 :width width))))
18959 (when image
18960 (let* ((link
18961 ;; If inline image is the description
18962 ;; of another link, be sure to
18963 ;; consider the latter as the one to
18964 ;; apply the overlay on.
18965 (let ((parent
18966 (org-element-property :parent link)))
18967 (if (eq (org-element-type parent) 'link)
18968 parent
18969 link)))
18970 (ov (make-overlay
18971 (org-element-property :begin link)
18972 (progn
18973 (goto-char
18974 (org-element-property :end link))
18975 (skip-chars-backward " \t")
18976 (point)))))
18977 (overlay-put ov 'display image)
18978 (overlay-put ov 'face 'default)
18979 (overlay-put ov 'org-image-overlay t)
18980 (overlay-put
18981 ov 'modification-hooks
18982 (list 'org-display-inline-remove-overlay))
18983 (push ov org-inline-image-overlays)))))))))))))))
18985 (define-obsolete-function-alias
18986 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18988 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18989 "Remove inline-display overlay if a corresponding region is modified."
18990 (let ((inhibit-modification-hooks t))
18991 (when (and ov after)
18992 (delete ov org-inline-image-overlays)
18993 (delete-overlay ov))))
18995 (defun org-remove-inline-images ()
18996 "Remove inline display of images."
18997 (interactive)
18998 (mapc 'delete-overlay org-inline-image-overlays)
18999 (setq org-inline-image-overlays nil))
19001 ;;;; Key bindings
19003 ;; Outline functions from `outline-mode-prefix-map'
19004 ;; that can be remapped in Org:
19005 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19006 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
19007 (define-key org-mode-map [remap outline-forward-same-level]
19008 'org-forward-heading-same-level)
19009 (define-key org-mode-map [remap outline-backward-same-level]
19010 'org-backward-heading-same-level)
19011 (define-key org-mode-map [remap show-branches]
19012 'org-kill-note-or-show-branches)
19013 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19014 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19015 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19017 ;; Outline functions from `outline-mode-prefix-map' that can not
19018 ;; be remapped in Org:
19020 ;; - the column "key binding" shows whether the Outline function is still
19021 ;; available in Org mode on the same key that it has been bound to in
19022 ;; Outline mode:
19023 ;; - "overridden": key used for a different functionality in Org mode
19024 ;; - else: key still bound to the same Outline function in Org mode
19026 ;; | Outline function | key binding | Org replacement |
19027 ;; |------------------------------------+-------------+-----------------------|
19028 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
19029 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
19030 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19031 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19032 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19033 ;; | `show-entry' | overridden | no replacement |
19034 ;; | `show-children' | `C-c C-i' | visibility cycling |
19035 ;; | `show-branches' | `C-c C-k' | still same function |
19036 ;; | `show-subtree' | overridden | visibility cycling |
19037 ;; | `show-all' | overridden | no replacement |
19038 ;; | `hide-subtree' | overridden | visibility cycling |
19039 ;; | `hide-body' | overridden | no replacement |
19040 ;; | `hide-entry' | overridden | visibility cycling |
19041 ;; | `hide-leaves' | overridden | no replacement |
19042 ;; | `hide-sublevels' | overridden | no replacement |
19043 ;; | `hide-other' | overridden | no replacement |
19045 ;; Make `C-c C-x' a prefix key
19046 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19048 ;; TAB key with modifiers
19049 (org-defkey org-mode-map "\C-i" 'org-cycle)
19050 (org-defkey org-mode-map [(tab)] 'org-cycle)
19051 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19052 (org-defkey org-mode-map "\M-\t" 'pcomplete)
19053 ;; The following line is necessary under Suse GNU/Linux
19054 (unless (featurep 'xemacs)
19055 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
19056 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19057 (define-key org-mode-map [backtab] 'org-shifttab)
19059 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19060 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19061 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19063 ;; Cursor keys with modifiers
19064 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19065 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19066 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19067 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19069 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19070 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19071 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19072 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19074 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19075 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19076 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19077 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19079 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19080 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19081 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19082 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19084 ;; Babel keys
19085 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19086 (mapc (lambda (pair)
19087 (define-key org-babel-map (car pair) (cdr pair)))
19088 org-babel-key-bindings)
19090 ;;; Extra keys for tty access.
19091 ;; We only set them when really needed because otherwise the
19092 ;; menus don't show the simple keys
19094 (when (or org-use-extra-keys
19095 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19096 (not window-system))
19097 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19098 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19099 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19100 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19101 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19102 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19103 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19104 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19105 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19106 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19107 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19108 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19109 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19110 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19111 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19112 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19113 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19114 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19115 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19116 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19117 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19118 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19119 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
19120 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19121 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19122 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19123 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19124 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19126 ;; All the other keys
19128 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
19129 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19130 (if (boundp 'narrow-map)
19131 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19132 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19133 (if (boundp 'narrow-map)
19134 (org-defkey narrow-map "b" 'org-narrow-to-block)
19135 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19136 (if (boundp 'narrow-map)
19137 (org-defkey narrow-map "e" 'org-narrow-to-element)
19138 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19139 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19140 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19141 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19142 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19143 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19144 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19145 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19146 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19147 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19148 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19149 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
19150 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19151 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19152 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19153 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19154 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19155 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19156 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19157 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19158 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19159 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19160 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19161 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19162 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19163 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19164 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19165 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19166 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19167 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19168 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19169 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19170 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19171 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19172 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19173 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19174 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19175 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19176 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19177 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19178 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19179 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19180 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19181 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19182 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19183 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19184 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19185 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19186 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19187 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19188 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19189 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19190 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19191 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19192 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19193 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19194 (org-defkey org-mode-map "\C-c^" 'org-sort)
19195 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19196 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19197 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19198 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19199 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19200 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19201 (org-defkey org-mode-map "\C-m" 'org-return)
19202 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19203 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19204 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19205 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19206 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19207 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19208 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19209 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19210 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19211 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19212 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19213 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19214 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19215 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19216 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
19217 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19218 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19219 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19220 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19221 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19222 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19223 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19224 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19226 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19227 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19228 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19230 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19231 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19232 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19233 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19234 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19235 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19236 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19237 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19238 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19239 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19240 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
19241 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19242 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19243 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19244 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19245 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19246 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19247 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19248 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19249 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19250 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19251 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19252 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19254 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19255 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19256 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19257 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19258 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19260 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19262 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19264 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19265 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19267 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19270 (when (featurep 'xemacs)
19271 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19274 (defconst org-speed-commands-default
19276 ("Outline Navigation")
19277 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19278 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19279 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19280 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19281 ("F" . org-next-block)
19282 ("B" . org-previous-block)
19283 ("u" . (org-speed-move-safe 'outline-up-heading))
19284 ("j" . org-goto)
19285 ("g" . (org-refile t))
19286 ("Outline Visibility")
19287 ("c" . org-cycle)
19288 ("C" . org-shifttab)
19289 (" " . org-display-outline-path)
19290 ("s" . org-narrow-to-subtree)
19291 ("=" . org-columns)
19292 ("Outline Structure Editing")
19293 ("U" . org-shiftmetaup)
19294 ("D" . org-shiftmetadown)
19295 ("r" . org-metaright)
19296 ("l" . org-metaleft)
19297 ("R" . org-shiftmetaright)
19298 ("L" . org-shiftmetaleft)
19299 ("i" . (progn (forward-char 1) (call-interactively
19300 'org-insert-heading-respect-content)))
19301 ("^" . org-sort)
19302 ("w" . org-refile)
19303 ("a" . org-archive-subtree-default-with-confirmation)
19304 ("@" . org-mark-subtree)
19305 ("#" . org-toggle-comment)
19306 ("Clock Commands")
19307 ("I" . org-clock-in)
19308 ("O" . org-clock-out)
19309 ("Meta Data Editing")
19310 ("t" . org-todo)
19311 ("," . (org-priority))
19312 ("0" . (org-priority ?\ ))
19313 ("1" . (org-priority ?A))
19314 ("2" . (org-priority ?B))
19315 ("3" . (org-priority ?C))
19316 (":" . org-set-tags-command)
19317 ("e" . org-set-effort)
19318 ("E" . org-inc-effort)
19319 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19320 (org-entry-put (point) "APPT_WARNTIME" m)))
19321 ("Agenda Views etc")
19322 ("v" . org-agenda)
19323 ("/" . org-sparse-tree)
19324 ("Misc")
19325 ("o" . org-open-at-point)
19326 ("?" . org-speed-command-help)
19327 ("<" . (org-agenda-set-restriction-lock 'subtree))
19328 (">" . (org-agenda-remove-restriction-lock))
19330 "The default speed commands.")
19332 (defun org-print-speed-command (e)
19333 (if (> (length (car e)) 1)
19334 (progn
19335 (princ "\n")
19336 (princ (car e))
19337 (princ "\n")
19338 (princ (make-string (length (car e)) ?-))
19339 (princ "\n"))
19340 (princ (car e))
19341 (princ " ")
19342 (if (symbolp (cdr e))
19343 (princ (symbol-name (cdr e)))
19344 (prin1 (cdr e)))
19345 (princ "\n")))
19347 (defun org-speed-command-help ()
19348 "Show the available speed commands."
19349 (interactive)
19350 (if (not org-use-speed-commands)
19351 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19352 (with-output-to-temp-buffer "*Help*"
19353 (princ "User-defined Speed commands\n===========================\n")
19354 (mapc 'org-print-speed-command org-speed-commands-user)
19355 (princ "\n")
19356 (princ "Built-in Speed commands\n=======================\n")
19357 (mapc 'org-print-speed-command org-speed-commands-default))
19358 (with-current-buffer "*Help*"
19359 (setq truncate-lines t))))
19361 (defun org-speed-move-safe (cmd)
19362 "Execute CMD, but make sure that the cursor always ends up in a headline.
19363 If not, return to the original position and throw an error."
19364 (interactive)
19365 (let ((pos (point)))
19366 (call-interactively cmd)
19367 (unless (and (bolp) (org-at-heading-p))
19368 (goto-char pos)
19369 (error "Boundary reached while executing %s" cmd))))
19371 (defvar org-self-insert-command-undo-counter 0)
19373 (defvar org-table-auto-blank-field) ; defined in org-table.el
19374 (defvar org-speed-command nil)
19376 (define-obsolete-function-alias
19377 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19379 (defun org-speed-command-activate (keys)
19380 "Hook for activating single-letter speed commands.
19381 `org-speed-commands-default' specifies a minimal command set.
19382 Use `org-speed-commands-user' for further customization."
19383 (when (or (and (bolp) (looking-at org-outline-regexp))
19384 (and (functionp org-use-speed-commands)
19385 (funcall org-use-speed-commands)))
19386 (cdr (assoc keys (append org-speed-commands-user
19387 org-speed-commands-default)))))
19389 (define-obsolete-function-alias
19390 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19392 (defun org-babel-speed-command-activate (keys)
19393 "Hook for activating single-letter code block commands."
19394 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19395 (cdr (assoc keys org-babel-key-bindings))))
19397 (defcustom org-speed-command-hook
19398 '(org-speed-command-default-hook org-babel-speed-command-hook)
19399 "Hook for activating speed commands at strategic locations.
19400 Hook functions are called in sequence until a valid handler is
19401 found.
19403 Each hook takes a single argument, a user-pressed command key
19404 which is also a `self-insert-command' from the global map.
19406 Within the hook, examine the cursor position and the command key
19407 and return nil or a valid handler as appropriate. Handler could
19408 be one of an interactive command, a function, or a form.
19410 Set `org-use-speed-commands' to non-nil value to enable this
19411 hook. The default setting is `org-speed-command-activate'."
19412 :group 'org-structure
19413 :version "24.1"
19414 :type 'hook)
19416 (defun org-self-insert-command (N)
19417 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19418 If the cursor is in a table looking at whitespace, the whitespace is
19419 overwritten, and the table is not marked as requiring realignment."
19420 (interactive "p")
19421 (org-check-before-invisible-edit 'insert)
19422 (cond
19423 ((and org-use-speed-commands
19424 (setq org-speed-command
19425 (run-hook-with-args-until-success
19426 'org-speed-command-hook (this-command-keys))))
19427 (cond
19428 ((commandp org-speed-command)
19429 (setq this-command org-speed-command)
19430 (call-interactively org-speed-command))
19431 ((functionp org-speed-command)
19432 (funcall org-speed-command))
19433 ((and org-speed-command (listp org-speed-command))
19434 (eval org-speed-command))
19435 (t (let (org-use-speed-commands)
19436 (call-interactively 'org-self-insert-command)))))
19437 ((and
19438 (org-table-p)
19439 (progn
19440 ;; check if we blank the field, and if that triggers align
19441 (and (featurep 'org-table) org-table-auto-blank-field
19442 (member last-command
19443 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19444 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19445 ;; got extra space, this field does not determine column width
19446 (let (org-table-may-need-update) (org-table-blank-field))
19447 ;; no extra space, this field may determine column width
19448 (org-table-blank-field)))
19450 (eq N 1)
19451 (looking-at "[^|\n]* |"))
19452 (let (org-table-may-need-update)
19453 (goto-char (1- (match-end 0)))
19454 (backward-delete-char 1)
19455 (goto-char (match-beginning 0))
19456 (self-insert-command N)))
19458 (setq org-table-may-need-update t)
19459 (self-insert-command N)
19460 (org-fix-tags-on-the-fly)
19461 (if org-self-insert-cluster-for-undo
19462 (if (not (eq last-command 'org-self-insert-command))
19463 (setq org-self-insert-command-undo-counter 1)
19464 (if (>= org-self-insert-command-undo-counter 20)
19465 (setq org-self-insert-command-undo-counter 1)
19466 (and (> org-self-insert-command-undo-counter 0)
19467 buffer-undo-list (listp buffer-undo-list)
19468 (not (cadr buffer-undo-list)) ; remove nil entry
19469 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19470 (setq org-self-insert-command-undo-counter
19471 (1+ org-self-insert-command-undo-counter))))))))
19473 (defun org-check-before-invisible-edit (kind)
19474 "Check is editing if kind KIND would be dangerous with invisible text around.
19475 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19476 ;; First, try to get out of here as quickly as possible, to reduce overhead
19477 (if (and org-catch-invisible-edits
19478 (or (not (boundp 'visible-mode)) (not visible-mode))
19479 (or (get-char-property (point) 'invisible)
19480 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19481 ;; OK, we need to take a closer look
19482 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19483 (invisible-before-point (if (bobp) nil (get-char-property
19484 (1- (point)) 'invisible)))
19485 (border-and-ok-direction
19487 ;; Check if we are acting predictably before invisible text
19488 (and invisible-at-point (not invisible-before-point)
19489 (memq kind '(insert delete-backward)))
19490 ;; Check if we are acting predictably after invisible text
19491 ;; This works not well, and I have turned it off. It seems
19492 ;; better to always show and stop after invisible text.
19493 ;; (and (not invisible-at-point) invisible-before-point
19494 ;; (memq kind '(insert delete)))
19496 (when (or (memq invisible-at-point '(outline org-hide-block t))
19497 (memq invisible-before-point '(outline org-hide-block t)))
19498 (if (eq org-catch-invisible-edits 'error)
19499 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19500 (if (and org-custom-properties-overlays
19501 (y-or-n-p "Display invisible properties in this buffer? "))
19502 (org-toggle-custom-properties-visibility)
19503 ;; Make the area visible
19504 (save-excursion
19505 (if invisible-before-point
19506 (goto-char (previous-single-char-property-change
19507 (point) 'invisible)))
19508 (org-cycle))
19509 (cond
19510 ((eq org-catch-invisible-edits 'show)
19511 ;; That's it, we do the edit after showing
19512 (message
19513 "Unfolding invisible region around point before editing")
19514 (sit-for 1))
19515 ((and (eq org-catch-invisible-edits 'smart)
19516 border-and-ok-direction)
19517 (message "Unfolding invisible region around point before editing"))
19519 ;; Don't do the edit, make the user repeat it in full visibility
19520 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19522 (defun org-fix-tags-on-the-fly ()
19523 (when (and (equal (char-after (point-at-bol)) ?*)
19524 (org-at-heading-p))
19525 (org-align-tags-here org-tags-column)))
19527 (defun org-delete-backward-char (N)
19528 "Like `delete-backward-char', insert whitespace at field end in tables.
19529 When deleting backwards, in tables this function will insert whitespace in
19530 front of the next \"|\" separator, to keep the table aligned. The table will
19531 still be marked for re-alignment if the field did fill the entire column,
19532 because, in this case the deletion might narrow the column."
19533 (interactive "p")
19534 (save-match-data
19535 (org-check-before-invisible-edit 'delete-backward)
19536 (if (and (org-table-p)
19537 (eq N 1)
19538 (string-match "|" (buffer-substring (point-at-bol) (point)))
19539 (looking-at ".*?|"))
19540 (let ((pos (point))
19541 (noalign (looking-at "[^|\n\r]* |"))
19542 (c org-table-may-need-update))
19543 (backward-delete-char N)
19544 (if (not overwrite-mode)
19545 (progn
19546 (skip-chars-forward "^|")
19547 (insert " ")
19548 (goto-char (1- pos))))
19549 ;; noalign: if there were two spaces at the end, this field
19550 ;; does not determine the width of the column.
19551 (if noalign (setq org-table-may-need-update c)))
19552 (backward-delete-char N)
19553 (org-fix-tags-on-the-fly))))
19555 (defun org-delete-char (N)
19556 "Like `delete-char', but insert whitespace at field end in tables.
19557 When deleting characters, in tables this function will insert whitespace in
19558 front of the next \"|\" separator, to keep the table aligned. The table will
19559 still be marked for re-alignment if the field did fill the entire column,
19560 because, in this case the deletion might narrow the column."
19561 (interactive "p")
19562 (save-match-data
19563 (org-check-before-invisible-edit 'delete)
19564 (if (and (org-table-p)
19565 (not (bolp))
19566 (not (= (char-after) ?|))
19567 (eq N 1))
19568 (if (looking-at ".*?|")
19569 (let ((pos (point))
19570 (noalign (looking-at "[^|\n\r]* |"))
19571 (c org-table-may-need-update))
19572 (replace-match
19573 (concat (substring (match-string 0) 1 -1) " |") nil t)
19574 (goto-char pos)
19575 ;; noalign: if there were two spaces at the end, this field
19576 ;; does not determine the width of the column.
19577 (if noalign (setq org-table-may-need-update c)))
19578 (delete-char N))
19579 (delete-char N)
19580 (org-fix-tags-on-the-fly))))
19582 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19583 (put 'org-self-insert-command 'delete-selection t)
19584 (put 'orgtbl-self-insert-command 'delete-selection t)
19585 (put 'org-delete-char 'delete-selection 'supersede)
19586 (put 'org-delete-backward-char 'delete-selection 'supersede)
19587 (put 'org-yank 'delete-selection 'yank)
19589 ;; Make `flyspell-mode' delay after some commands
19590 (put 'org-self-insert-command 'flyspell-delayed t)
19591 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19592 (put 'org-delete-char 'flyspell-delayed t)
19593 (put 'org-delete-backward-char 'flyspell-delayed t)
19595 ;; Make pabbrev-mode expand after org-mode commands
19596 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19597 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19599 (defun org-remap (map &rest commands)
19600 "In MAP, remap the functions given in COMMANDS.
19601 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19602 (let (new old)
19603 (while commands
19604 (setq old (pop commands) new (pop commands))
19605 (if (fboundp 'command-remapping)
19606 (org-defkey map (vector 'remap old) new)
19607 (substitute-key-definition old new map global-map)))))
19609 (defun org-transpose-words ()
19610 "Transpose words for Org.
19611 This uses the `org-mode-transpose-word-syntax-table' syntax
19612 table, which interprets characters in `org-emphasis-alist' as
19613 word constituents."
19614 (interactive)
19615 (with-syntax-table org-mode-transpose-word-syntax-table
19616 (call-interactively 'transpose-words)))
19617 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19619 (when (eq org-enable-table-editor 'optimized)
19620 ;; If the user wants maximum table support, we need to hijack
19621 ;; some standard editing functions
19622 (org-remap org-mode-map
19623 'self-insert-command 'org-self-insert-command
19624 'delete-char 'org-delete-char
19625 'delete-backward-char 'org-delete-backward-char)
19626 (org-defkey org-mode-map "|" 'org-force-self-insert))
19628 (defvar org-ctrl-c-ctrl-c-hook nil
19629 "Hook for functions attaching themselves to `C-c C-c'.
19631 This can be used to add additional functionality to the C-c C-c
19632 key which executes context-dependent commands. This hook is run
19633 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19634 run after the last test.
19636 Each function will be called with no arguments. The function
19637 must check if the context is appropriate for it to act. If yes,
19638 it should do its thing and then return a non-nil value. If the
19639 context is wrong, just do nothing and return nil.")
19641 (defvar org-ctrl-c-ctrl-c-final-hook nil
19642 "Hook for functions attaching themselves to `C-c C-c'.
19644 This can be used to add additional functionality to the C-c C-c
19645 key which executes context-dependent commands. This hook is run
19646 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19647 before the first test.
19649 Each function will be called with no arguments. The function
19650 must check if the context is appropriate for it to act. If yes,
19651 it should do its thing and then return a non-nil value. If the
19652 context is wrong, just do nothing and return nil.")
19654 (defvar org-tab-first-hook nil
19655 "Hook for functions to attach themselves to TAB.
19656 See `org-ctrl-c-ctrl-c-hook' for more information.
19657 This hook runs as the first action when TAB is pressed, even before
19658 `org-cycle' messes around with the `outline-regexp' to cater for
19659 inline tasks and plain list item folding.
19660 If any function in this hook returns t, any other actions that
19661 would have been caused by TAB (such as table field motion or visibility
19662 cycling) will not occur.")
19664 (defvar org-tab-after-check-for-table-hook nil
19665 "Hook for functions to attach themselves to TAB.
19666 See `org-ctrl-c-ctrl-c-hook' for more information.
19667 This hook runs after it has been established that the cursor is not in a
19668 table, but before checking if the cursor is in a headline or if global cycling
19669 should be done.
19670 If any function in this hook returns t, not other actions like visibility
19671 cycling will be done.")
19673 (defvar org-tab-after-check-for-cycling-hook nil
19674 "Hook for functions to attach themselves to TAB.
19675 See `org-ctrl-c-ctrl-c-hook' for more information.
19676 This hook runs after it has been established that not table field motion and
19677 not visibility should be done because of current context. This is probably
19678 the place where a package like yasnippets can hook in.")
19680 (defvar org-tab-before-tab-emulation-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 after every other options for TAB have been exhausted, but
19684 before indentation and \t insertion takes place.")
19686 (defvar org-metaleft-hook nil
19687 "Hook for functions attaching themselves to `M-left'.
19688 See `org-ctrl-c-ctrl-c-hook' for more information.")
19689 (defvar org-metaright-hook nil
19690 "Hook for functions attaching themselves to `M-right'.
19691 See `org-ctrl-c-ctrl-c-hook' for more information.")
19692 (defvar org-metaup-hook nil
19693 "Hook for functions attaching themselves to `M-up'.
19694 See `org-ctrl-c-ctrl-c-hook' for more information.")
19695 (defvar org-metadown-hook nil
19696 "Hook for functions attaching themselves to `M-down'.
19697 See `org-ctrl-c-ctrl-c-hook' for more information.")
19698 (defvar org-shiftmetaleft-hook nil
19699 "Hook for functions attaching themselves to `M-S-left'.
19700 See `org-ctrl-c-ctrl-c-hook' for more information.")
19701 (defvar org-shiftmetaright-hook nil
19702 "Hook for functions attaching themselves to `M-S-right'.
19703 See `org-ctrl-c-ctrl-c-hook' for more information.")
19704 (defvar org-shiftmetaup-hook nil
19705 "Hook for functions attaching themselves to `M-S-up'.
19706 See `org-ctrl-c-ctrl-c-hook' for more information.")
19707 (defvar org-shiftmetadown-hook nil
19708 "Hook for functions attaching themselves to `M-S-down'.
19709 See `org-ctrl-c-ctrl-c-hook' for more information.")
19710 (defvar org-metareturn-hook nil
19711 "Hook for functions attaching themselves to `M-RET'.
19712 See `org-ctrl-c-ctrl-c-hook' for more information.")
19713 (defvar org-shiftup-hook nil
19714 "Hook for functions attaching themselves to `S-up'.
19715 See `org-ctrl-c-ctrl-c-hook' for more information.")
19716 (defvar org-shiftup-final-hook nil
19717 "Hook for functions attaching themselves to `S-up'.
19718 This one runs after all other options except shift-select have been excluded.
19719 See `org-ctrl-c-ctrl-c-hook' for more information.")
19720 (defvar org-shiftdown-hook nil
19721 "Hook for functions attaching themselves to `S-down'.
19722 See `org-ctrl-c-ctrl-c-hook' for more information.")
19723 (defvar org-shiftdown-final-hook nil
19724 "Hook for functions attaching themselves to `S-down'.
19725 This one runs after all other options except shift-select have been excluded.
19726 See `org-ctrl-c-ctrl-c-hook' for more information.")
19727 (defvar org-shiftleft-hook nil
19728 "Hook for functions attaching themselves to `S-left'.
19729 See `org-ctrl-c-ctrl-c-hook' for more information.")
19730 (defvar org-shiftleft-final-hook nil
19731 "Hook for functions attaching themselves to `S-left'.
19732 This one runs after all other options except shift-select have been excluded.
19733 See `org-ctrl-c-ctrl-c-hook' for more information.")
19734 (defvar org-shiftright-hook nil
19735 "Hook for functions attaching themselves to `S-right'.
19736 See `org-ctrl-c-ctrl-c-hook' for more information.")
19737 (defvar org-shiftright-final-hook nil
19738 "Hook for functions attaching themselves to `S-right'.
19739 This one runs after all other options except shift-select have been excluded.
19740 See `org-ctrl-c-ctrl-c-hook' for more information.")
19742 (defun org-modifier-cursor-error ()
19743 "Throw an error, a modified cursor command was applied in wrong context."
19744 (user-error "This command is active in special context like tables, headlines or items"))
19746 (defun org-shiftselect-error ()
19747 "Throw an error because Shift-Cursor command was applied in wrong context."
19748 (if (and (boundp 'shift-select-mode) shift-select-mode)
19749 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19750 (user-error "This command works only in special context like headlines or timestamps")))
19752 (defun org-call-for-shift-select (cmd)
19753 (let ((this-command-keys-shift-translated t))
19754 (call-interactively cmd)))
19756 (defun org-shifttab (&optional arg)
19757 "Global visibility cycling or move to previous table field.
19758 Call `org-table-previous-field' within a table.
19759 When ARG is nil, cycle globally through visibility states.
19760 When ARG is a numeric prefix, show contents of this level."
19761 (interactive "P")
19762 (cond
19763 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19764 ((integerp arg)
19765 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19766 (message "Content view to level: %d" arg)
19767 (org-content (prefix-numeric-value arg2))
19768 (org-cycle-show-empty-lines t)
19769 (setq org-cycle-global-status 'overview)))
19770 (t (call-interactively 'org-global-cycle))))
19772 (defun org-shiftmetaleft ()
19773 "Promote subtree or delete table column.
19774 Calls `org-promote-subtree', `org-outdent-item-tree', or
19775 `org-table-delete-column', depending on context. See the
19776 individual commands for more information."
19777 (interactive)
19778 (cond
19779 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19780 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19781 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19782 ((if (not (org-region-active-p)) (org-at-item-p)
19783 (save-excursion (goto-char (region-beginning))
19784 (org-at-item-p)))
19785 (call-interactively 'org-outdent-item-tree))
19786 (t (org-modifier-cursor-error))))
19788 (defun org-shiftmetaright ()
19789 "Demote subtree or insert table column.
19790 Calls `org-demote-subtree', `org-indent-item-tree', or
19791 `org-table-insert-column', depending on context. See the
19792 individual commands for more information."
19793 (interactive)
19794 (cond
19795 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19796 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19797 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19798 ((if (not (org-region-active-p)) (org-at-item-p)
19799 (save-excursion (goto-char (region-beginning))
19800 (org-at-item-p)))
19801 (call-interactively 'org-indent-item-tree))
19802 (t (org-modifier-cursor-error))))
19804 (defun org-shiftmetaup (&optional arg)
19805 "Move subtree up or kill table row.
19806 Calls `org-move-subtree-up' or `org-table-kill-row' or
19807 `org-move-item-up' or `org-timestamp-up', depending on context.
19808 See the individual commands for more information."
19809 (interactive "P")
19810 (cond
19811 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19812 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19813 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19814 ((org-at-item-p) (call-interactively 'org-move-item-up))
19815 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19816 (call-interactively 'org-timestamp-up)))
19817 (t (call-interactively 'org-drag-line-backward))))
19819 (defun org-shiftmetadown (&optional arg)
19820 "Move subtree down or insert table row.
19821 Calls `org-move-subtree-down' or `org-table-insert-row' or
19822 `org-move-item-down' or `org-timestamp-up', depending on context.
19823 See the individual commands for more information."
19824 (interactive "P")
19825 (cond
19826 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19827 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19828 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19829 ((org-at-item-p) (call-interactively 'org-move-item-down))
19830 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19831 (call-interactively 'org-timestamp-down)))
19832 (t (call-interactively 'org-drag-line-forward))))
19834 (defsubst org-hidden-tree-error ()
19835 (user-error
19836 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19838 (defun org-metaleft (&optional arg)
19839 "Promote heading or move table column to left.
19840 Calls `org-do-promote' or `org-table-move-column', depending on context.
19841 With no specific context, calls the Emacs default `backward-word'.
19842 See the individual commands for more information."
19843 (interactive "P")
19844 (cond
19845 ((run-hook-with-args-until-success 'org-metaleft-hook))
19846 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19847 ((org-with-limited-levels
19848 (or (org-at-heading-p)
19849 (and (org-region-active-p)
19850 (save-excursion
19851 (goto-char (region-beginning))
19852 (org-at-heading-p)))))
19853 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19854 (call-interactively 'org-do-promote))
19855 ;; At an inline task.
19856 ((org-at-heading-p)
19857 (call-interactively 'org-inlinetask-promote))
19858 ((or (org-at-item-p)
19859 (and (org-region-active-p)
19860 (save-excursion
19861 (goto-char (region-beginning))
19862 (org-at-item-p))))
19863 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19864 (call-interactively 'org-outdent-item))
19865 (t (call-interactively 'backward-word))))
19867 (defun org-metaright (&optional arg)
19868 "Demote a subtree, a list item or move table column to right.
19869 In front of a drawer or a block keyword, indent it correctly.
19870 With no specific context, calls the Emacs default `forward-word'.
19871 See the individual commands for more information."
19872 (interactive "P")
19873 (cond
19874 ((run-hook-with-args-until-success 'org-metaright-hook))
19875 ((org-at-table-p) (call-interactively 'org-table-move-column))
19876 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19877 ((org-at-block-p) (call-interactively 'org-indent-block))
19878 ((org-with-limited-levels
19879 (or (org-at-heading-p)
19880 (and (org-region-active-p)
19881 (save-excursion
19882 (goto-char (region-beginning))
19883 (org-at-heading-p)))))
19884 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19885 (call-interactively 'org-do-demote))
19886 ;; At an inline task.
19887 ((org-at-heading-p)
19888 (call-interactively 'org-inlinetask-demote))
19889 ((or (org-at-item-p)
19890 (and (org-region-active-p)
19891 (save-excursion
19892 (goto-char (region-beginning))
19893 (org-at-item-p))))
19894 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19895 (call-interactively 'org-indent-item))
19896 (t (call-interactively 'forward-word))))
19898 (defun org-check-for-hidden (what)
19899 "Check if there are hidden headlines/items in the current visual line.
19900 WHAT can be either `headlines' or `items'. If the current line is
19901 an outline or item heading and it has a folded subtree below it,
19902 this function returns t, nil otherwise."
19903 (let ((re (cond
19904 ((eq what 'headlines) org-outline-regexp-bol)
19905 ((eq what 'items) (org-item-beginning-re))
19906 (t (error "This should not happen"))))
19907 beg end)
19908 (save-excursion
19909 (catch 'exit
19910 (unless (org-region-active-p)
19911 (setq beg (point-at-bol))
19912 (beginning-of-line 2)
19913 (while (and (not (eobp)) ;; this is like `next-line'
19914 (get-char-property (1- (point)) 'invisible))
19915 (beginning-of-line 2))
19916 (setq end (point))
19917 (goto-char beg)
19918 (goto-char (point-at-eol))
19919 (setq end (max end (point)))
19920 (while (re-search-forward re end t)
19921 (if (get-char-property (match-beginning 0) 'invisible)
19922 (throw 'exit t))))
19923 nil))))
19925 (defun org-metaup (&optional arg)
19926 "Move subtree up or move table row up.
19927 Calls `org-move-subtree-up' or `org-table-move-row' or
19928 `org-move-item-up', depending on context. See the individual commands
19929 for more information."
19930 (interactive "P")
19931 (cond
19932 ((run-hook-with-args-until-success 'org-metaup-hook))
19933 ((org-region-active-p)
19934 (let* ((a (min (region-beginning) (region-end)))
19935 (b (1- (max (region-beginning) (region-end))))
19936 (c (save-excursion (goto-char a)
19937 (move-beginning-of-line 0)))
19938 (d (save-excursion (goto-char a)
19939 (move-end-of-line 0) (point))))
19940 (transpose-regions a b c d)
19941 (goto-char c)))
19942 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19943 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19944 ((org-at-item-p) (call-interactively 'org-move-item-up))
19945 (t (org-drag-element-backward))))
19947 (defun org-metadown (&optional arg)
19948 "Move subtree down or move table row down.
19949 Calls `org-move-subtree-down' or `org-table-move-row' or
19950 `org-move-item-down', depending on context. See the individual
19951 commands for more information."
19952 (interactive "P")
19953 (cond
19954 ((run-hook-with-args-until-success 'org-metadown-hook))
19955 ((org-region-active-p)
19956 (let* ((a (min (region-beginning) (region-end)))
19957 (b (max (region-beginning) (region-end)))
19958 (c (save-excursion (goto-char b)
19959 (move-beginning-of-line 1)))
19960 (d (save-excursion (goto-char b)
19961 (move-end-of-line 1) (1+ (point)))))
19962 (transpose-regions a b c d)
19963 (goto-char d)))
19964 ((org-at-table-p) (call-interactively 'org-table-move-row))
19965 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19966 ((org-at-item-p) (call-interactively 'org-move-item-down))
19967 (t (org-drag-element-forward))))
19969 (defun org-shiftup (&optional arg)
19970 "Increase item in timestamp or increase priority of current headline.
19971 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19972 depending on context. See the individual commands for more information."
19973 (interactive "P")
19974 (cond
19975 ((run-hook-with-args-until-success 'org-shiftup-hook))
19976 ((and org-support-shift-select (org-region-active-p))
19977 (org-call-for-shift-select 'previous-line))
19978 ((org-at-timestamp-p t)
19979 (call-interactively (if org-edit-timestamp-down-means-later
19980 'org-timestamp-down 'org-timestamp-up)))
19981 ((and (not (eq org-support-shift-select 'always))
19982 org-enable-priority-commands
19983 (org-at-heading-p))
19984 (call-interactively 'org-priority-up))
19985 ((and (not org-support-shift-select) (org-at-item-p))
19986 (call-interactively 'org-previous-item))
19987 ((org-clocktable-try-shift 'up arg))
19988 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19989 (org-support-shift-select
19990 (org-call-for-shift-select 'previous-line))
19991 (t (org-shiftselect-error))))
19993 (defun org-shiftdown (&optional arg)
19994 "Decrease item in timestamp or decrease priority of current headline.
19995 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19996 depending on context. See the individual commands for more information."
19997 (interactive "P")
19998 (cond
19999 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20000 ((and org-support-shift-select (org-region-active-p))
20001 (org-call-for-shift-select 'next-line))
20002 ((org-at-timestamp-p t)
20003 (call-interactively (if org-edit-timestamp-down-means-later
20004 'org-timestamp-up 'org-timestamp-down)))
20005 ((and (not (eq org-support-shift-select 'always))
20006 org-enable-priority-commands
20007 (org-at-heading-p))
20008 (call-interactively 'org-priority-down))
20009 ((and (not org-support-shift-select) (org-at-item-p))
20010 (call-interactively 'org-next-item))
20011 ((org-clocktable-try-shift 'down arg))
20012 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20013 (org-support-shift-select
20014 (org-call-for-shift-select 'next-line))
20015 (t (org-shiftselect-error))))
20017 (defun org-shiftright (&optional arg)
20018 "Cycle the thing at point or in the current line, depending on context.
20019 Depending on context, this does one of the following:
20021 - switch a timestamp at point one day into the future
20022 - on a headline, switch to the next TODO keyword.
20023 - on an item, switch entire list to the next bullet type
20024 - on a property line, switch to the next allowed value
20025 - on a clocktable definition line, move time block into the future"
20026 (interactive "P")
20027 (cond
20028 ((run-hook-with-args-until-success 'org-shiftright-hook))
20029 ((and org-support-shift-select (org-region-active-p))
20030 (org-call-for-shift-select 'forward-char))
20031 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20032 ((and (not (eq org-support-shift-select 'always))
20033 (org-at-heading-p))
20034 (let ((org-inhibit-logging
20035 (not org-treat-S-cursor-todo-selection-as-state-change))
20036 (org-inhibit-blocking
20037 (not org-treat-S-cursor-todo-selection-as-state-change)))
20038 (org-call-with-arg 'org-todo 'right)))
20039 ((or (and org-support-shift-select
20040 (not (eq org-support-shift-select 'always))
20041 (org-at-item-bullet-p))
20042 (and (not org-support-shift-select) (org-at-item-p)))
20043 (org-call-with-arg 'org-cycle-list-bullet nil))
20044 ((and (not (eq org-support-shift-select 'always))
20045 (org-at-property-p))
20046 (call-interactively 'org-property-next-allowed-value))
20047 ((org-clocktable-try-shift 'right arg))
20048 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20049 (org-support-shift-select
20050 (org-call-for-shift-select 'forward-char))
20051 (t (org-shiftselect-error))))
20053 (defun org-shiftleft (&optional arg)
20054 "Cycle the thing at point or in the current line, depending on context.
20055 Depending on context, this does one of the following:
20057 - switch a timestamp at point one day into the past
20058 - on a headline, switch to the previous TODO keyword.
20059 - on an item, switch entire list to the previous bullet type
20060 - on a property line, switch to the previous allowed value
20061 - on a clocktable definition line, move time block into the past"
20062 (interactive "P")
20063 (cond
20064 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20065 ((and org-support-shift-select (org-region-active-p))
20066 (org-call-for-shift-select 'backward-char))
20067 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20068 ((and (not (eq org-support-shift-select 'always))
20069 (org-at-heading-p))
20070 (let ((org-inhibit-logging
20071 (not org-treat-S-cursor-todo-selection-as-state-change))
20072 (org-inhibit-blocking
20073 (not org-treat-S-cursor-todo-selection-as-state-change)))
20074 (org-call-with-arg 'org-todo 'left)))
20075 ((or (and org-support-shift-select
20076 (not (eq org-support-shift-select 'always))
20077 (org-at-item-bullet-p))
20078 (and (not org-support-shift-select) (org-at-item-p)))
20079 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20080 ((and (not (eq org-support-shift-select 'always))
20081 (org-at-property-p))
20082 (call-interactively 'org-property-previous-allowed-value))
20083 ((org-clocktable-try-shift 'left arg))
20084 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20085 (org-support-shift-select
20086 (org-call-for-shift-select 'backward-char))
20087 (t (org-shiftselect-error))))
20089 (defun org-shiftcontrolright ()
20090 "Switch to next TODO set."
20091 (interactive)
20092 (cond
20093 ((and org-support-shift-select (org-region-active-p))
20094 (org-call-for-shift-select 'forward-word))
20095 ((and (not (eq org-support-shift-select 'always))
20096 (org-at-heading-p))
20097 (org-call-with-arg 'org-todo 'nextset))
20098 (org-support-shift-select
20099 (org-call-for-shift-select 'forward-word))
20100 (t (org-shiftselect-error))))
20102 (defun org-shiftcontrolleft ()
20103 "Switch to previous TODO set."
20104 (interactive)
20105 (cond
20106 ((and org-support-shift-select (org-region-active-p))
20107 (org-call-for-shift-select 'backward-word))
20108 ((and (not (eq org-support-shift-select 'always))
20109 (org-at-heading-p))
20110 (org-call-with-arg 'org-todo 'previousset))
20111 (org-support-shift-select
20112 (org-call-for-shift-select 'backward-word))
20113 (t (org-shiftselect-error))))
20115 (defun org-shiftcontrolup (&optional n)
20116 "Change timestamps synchronously up in CLOCK log lines.
20117 Optional argument N tells to change by that many units."
20118 (interactive "P")
20119 (cond ((and (not org-support-shift-select)
20120 (org-at-clock-log-p)
20121 (org-at-timestamp-p t))
20122 (org-clock-timestamps-up n))
20123 (t (org-shiftselect-error))))
20125 (defun org-shiftcontroldown (&optional n)
20126 "Change timestamps synchronously down in CLOCK log lines.
20127 Optional argument N tells to change by that many units."
20128 (interactive "P")
20129 (cond ((and (not org-support-shift-select)
20130 (org-at-clock-log-p)
20131 (org-at-timestamp-p t))
20132 (org-clock-timestamps-down n))
20133 (t (org-shiftselect-error))))
20135 (defun org-ctrl-c-ret ()
20136 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20137 (interactive)
20138 (cond
20139 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20140 (t (call-interactively 'org-insert-heading))))
20142 (defun org-find-visible ()
20143 (let ((s (point)))
20144 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20145 (get-char-property s 'invisible)))
20147 (defun org-find-invisible ()
20148 (let ((s (point)))
20149 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20150 (not (get-char-property s 'invisible))))
20153 (defun org-copy-visible (beg end)
20154 "Copy the visible parts of the region."
20155 (interactive "r")
20156 (let (snippets s)
20157 (save-excursion
20158 (save-restriction
20159 (narrow-to-region beg end)
20160 (setq s (goto-char (point-min)))
20161 (while (not (= (point) (point-max)))
20162 (goto-char (org-find-invisible))
20163 (push (buffer-substring s (point)) snippets)
20164 (setq s (goto-char (org-find-visible))))))
20165 (kill-new (apply 'concat (nreverse snippets)))))
20167 (defun org-copy-special ()
20168 "Copy region in table or copy current subtree.
20169 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20170 See the individual commands for more information."
20171 (interactive)
20172 (call-interactively
20173 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20175 (defun org-cut-special ()
20176 "Cut region in table or cut current subtree.
20177 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20178 See the individual commands for more information."
20179 (interactive)
20180 (call-interactively
20181 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20183 (defun org-paste-special (arg)
20184 "Paste rectangular region into table, or past subtree relative to level.
20185 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20186 See the individual commands for more information."
20187 (interactive "P")
20188 (if (org-at-table-p)
20189 (org-table-paste-rectangle)
20190 (org-paste-subtree arg)))
20192 (defsubst org-in-fixed-width-region-p ()
20193 "Is point in a fixed-width region?"
20194 (save-match-data
20195 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20197 (defun org-edit-special (&optional arg)
20198 "Call a special editor for the element at point.
20199 When at a table, call the formula editor with `org-table-edit-formulas'.
20200 When in a source code block, call `org-edit-src-code'.
20201 When in a fixed-width region, call `org-edit-fixed-width-region'.
20202 When at an #+INCLUDE keyword, visit the included file.
20203 On a link, call `ffap' to visit the link at point.
20204 Otherwise, return a user error."
20205 (interactive "P")
20206 (let ((element (org-element-at-point)))
20207 (assert (not buffer-read-only) nil
20208 "Buffer is read-only: %s" (buffer-name))
20209 (case (org-element-type element)
20210 (src-block
20211 (if (not arg) (org-edit-src-code)
20212 (let* ((info (org-babel-get-src-block-info))
20213 (lang (nth 0 info))
20214 (params (nth 2 info))
20215 (session (cdr (assq :session params))))
20216 (if (not session) (org-edit-src-code)
20217 ;; At a src-block with a session and function called with
20218 ;; an ARG: switch to the buffer related to the inferior
20219 ;; process.
20220 (switch-to-buffer
20221 (funcall (intern (concat "org-babel-prep-session:" lang))
20222 session params))))))
20223 (keyword
20224 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20225 (find-file
20226 (org-remove-double-quotes
20227 (car (org-split-string (org-element-property :value element)))))
20228 (user-error "No special environment to edit here")))
20229 (table
20230 (if (eq (org-element-property :type element) 'table.el)
20231 (org-edit-src-code)
20232 (call-interactively 'org-table-edit-formulas)))
20233 ;; Only Org tables contain `table-row' type elements.
20234 (table-row (call-interactively 'org-table-edit-formulas))
20235 ((example-block export-block) (org-edit-src-code))
20236 (fixed-width (org-edit-fixed-width-region))
20237 (otherwise
20238 ;; No notable element at point. Though, we may be at a link,
20239 ;; which is an object. Thus, scan deeper.
20240 (if (eq (org-element-type (org-element-context element)) 'link)
20241 (call-interactively 'ffap)
20242 (user-error "No special environment to edit here"))))))
20244 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20245 (defun org-ctrl-c-ctrl-c (&optional arg)
20246 "Set tags in headline, or update according to changed information at point.
20248 This command does many different things, depending on context:
20250 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20251 this is what we do.
20253 - If the cursor is on a statistics cookie, update it.
20255 - If the cursor is in a headline, prompt for tags and insert them
20256 into the current line, aligned to `org-tags-column'. When called
20257 with prefix arg, realign all tags in the current buffer.
20259 - If the cursor is in one of the special #+KEYWORD lines, this
20260 triggers scanning the buffer for these lines and updating the
20261 information.
20263 - If the cursor is inside a table, realign the table. This command
20264 works even if the automatic table editor has been turned off.
20266 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20267 the entire table.
20269 - If the cursor is at a footnote reference or definition, jump to
20270 the corresponding definition or references, respectively.
20272 - If the cursor is a the beginning of a dynamic block, update it.
20274 - If the current buffer is a capture buffer, close note and file it.
20276 - If the cursor is on a <<<target>>>, update radio targets and
20277 corresponding links in this buffer.
20279 - If the cursor is on a numbered item in a plain list, renumber the
20280 ordered list.
20282 - If the cursor is on a checkbox, toggle it.
20284 - If the cursor is on a code block, evaluate it. The variable
20285 `org-confirm-babel-evaluate' can be used to control prompting
20286 before code block evaluation, by default every code block
20287 evaluation requires confirmation. Code block evaluation can be
20288 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20289 (interactive "P")
20290 (cond
20291 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20292 org-occur-highlights
20293 org-latex-fragment-image-overlays)
20294 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20295 (org-remove-occur-highlights)
20296 (org-remove-latex-fragment-image-overlays)
20297 (message "Temporary highlights/overlays removed from current buffer"))
20298 ((and (local-variable-p 'org-finish-function (current-buffer))
20299 (fboundp org-finish-function))
20300 (funcall org-finish-function))
20301 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20303 (let* ((context (org-element-context)) (type (org-element-type context)))
20304 ;; Test if point is within a blank line.
20305 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20306 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20307 (user-error "C-c C-c can do nothing useful at this location"))
20308 ;; When at a link, act according to the parent instead.
20309 (when (eq type 'link)
20310 (setq context (org-element-property :parent context))
20311 (setq type (org-element-type context)))
20312 ;; For convenience: at the first line of a paragraph on the
20313 ;; same line as an item, apply function on that item instead.
20314 (when (eq type 'paragraph)
20315 (let ((parent (org-element-property :parent context)))
20316 (when (and (eq (org-element-type parent) 'item)
20317 (= (point-at-bol) (org-element-property :begin parent)))
20318 (setq context parent type 'item))))
20319 ;; Act according to type of element or object at point.
20320 (case type
20321 (clock (org-clock-update-time-maybe))
20322 (dynamic-block
20323 (save-excursion
20324 (goto-char (org-element-property :post-affiliated context))
20325 (org-update-dblock)))
20326 (footnote-definition
20327 (goto-char (org-element-property :post-affiliated context))
20328 (call-interactively 'org-footnote-action))
20329 (footnote-reference (call-interactively 'org-footnote-action))
20330 ((headline inlinetask)
20331 (save-excursion (goto-char (org-element-property :begin context))
20332 (call-interactively 'org-set-tags)))
20333 (item
20334 ;; At an item: a double C-u set checkbox to "[-]"
20335 ;; unconditionally, whereas a single one will toggle its
20336 ;; presence. Without an universal argument, if the item
20337 ;; has a checkbox, toggle it. Otherwise repair the list.
20338 (let* ((box (org-element-property :checkbox context))
20339 (struct (org-element-property :structure context))
20340 (old-struct (copy-tree struct))
20341 (parents (org-list-parents-alist struct))
20342 (prevs (org-list-prevs-alist struct))
20343 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20344 (org-list-set-checkbox
20345 (org-element-property :begin context) struct
20346 (cond ((equal arg '(16)) "[-]")
20347 ((and (not box) (equal arg '(4))) "[ ]")
20348 ((or (not box) (equal arg '(4))) nil)
20349 ((eq box 'on) "[ ]")
20350 (t "[X]")))
20351 ;; Mimic `org-list-write-struct' but with grabbing
20352 ;; a return value from `org-list-struct-fix-box'.
20353 (org-list-struct-fix-ind struct parents 2)
20354 (org-list-struct-fix-item-end struct)
20355 (org-list-struct-fix-bul struct prevs)
20356 (org-list-struct-fix-ind struct parents)
20357 (let ((block-item
20358 (org-list-struct-fix-box struct parents prevs orderedp)))
20359 (if (and box (equal struct old-struct))
20360 (if (equal arg '(16))
20361 (message "Checkboxes already reset")
20362 (user-error "Cannot toggle this checkbox: %s"
20363 (if (eq box 'on)
20364 "all subitems checked"
20365 "unchecked subitems")))
20366 (org-list-struct-apply-struct struct old-struct)
20367 (org-update-checkbox-count-maybe))
20368 (when block-item
20369 (message "Checkboxes were removed due to empty box at line %d"
20370 (org-current-line block-item))))))
20371 (keyword
20372 (let ((org-inhibit-startup-visibility-stuff t)
20373 (org-startup-align-all-tables nil))
20374 (when (boundp 'org-table-coordinate-overlays)
20375 (mapc 'delete-overlay org-table-coordinate-overlays)
20376 (setq org-table-coordinate-overlays nil))
20377 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20378 (message "Local setup has been refreshed"))
20379 (plain-list
20380 ;; At a plain list, with a double C-u argument, set
20381 ;; checkboxes of each item to "[-]", whereas a single one
20382 ;; will toggle their presence according to the state of the
20383 ;; first item in the list. Without an argument, repair the
20384 ;; list.
20385 (let* ((begin (org-element-property :contents-begin context))
20386 (beginm (move-marker (make-marker) begin))
20387 (struct (org-element-property :structure context))
20388 (old-struct (copy-tree struct))
20389 (first-box (save-excursion
20390 (goto-char begin)
20391 (looking-at org-list-full-item-re)
20392 (match-string-no-properties 3)))
20393 (new-box (cond ((equal arg '(16)) "[-]")
20394 ((equal arg '(4)) (unless first-box "[ ]"))
20395 ((equal first-box "[X]") "[ ]")
20396 (t "[X]"))))
20397 (cond
20398 (arg
20399 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20400 (org-list-get-all-items
20401 begin struct (org-list-prevs-alist struct))))
20402 ((and first-box (eq (point) begin))
20403 ;; For convenience, when point is at bol on the first
20404 ;; item of the list and no argument is provided, simply
20405 ;; toggle checkbox of that item, if any.
20406 (org-list-set-checkbox begin struct new-box)))
20407 (org-list-write-struct
20408 struct (org-list-parents-alist struct) old-struct)
20409 (org-update-checkbox-count-maybe)
20410 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20411 ((property-drawer node-property)
20412 (call-interactively 'org-property-action))
20413 ((radio-target target)
20414 (call-interactively 'org-update-radio-target-regexp))
20415 (statistics-cookie
20416 (call-interactively 'org-update-statistics-cookies))
20417 ((table table-cell table-row)
20418 ;; At a table, recalculate every field and align it. Also
20419 ;; send the table if necessary. If the table has
20420 ;; a `table.el' type, just give up. At a table row or
20421 ;; cell, maybe recalculate line but always align table.
20422 (if (eq (org-element-property :type context) 'table.el)
20423 (message "Use C-c ' to edit table.el tables")
20424 (let ((org-enable-table-editor t))
20425 (if (or (eq type 'table)
20426 ;; Check if point is at a TBLFM line.
20427 (and (eq type 'table-row)
20428 (= (point) (org-element-property :end context))))
20429 (save-excursion
20430 (if (org-at-TBLFM-p)
20431 (progn (require 'org-table)
20432 (org-table-calc-current-TBLFM))
20433 (goto-char (org-element-property :contents-begin context))
20434 (org-call-with-arg 'org-table-recalculate (or arg t))
20435 (orgtbl-send-table 'maybe)))
20436 (org-table-maybe-eval-formula)
20437 (cond (arg (call-interactively 'org-table-recalculate))
20438 ((org-table-maybe-recalculate-line))
20439 (t (org-table-align)))))))
20440 (timestamp (org-timestamp-change 0 'day))
20441 (otherwise
20442 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20443 (user-error
20444 "C-c C-c can do nothing useful at this location")))))))))
20446 (defun org-mode-restart ()
20447 "Restart Org-mode, to scan again for special lines.
20448 Also updates the keyword regular expressions."
20449 (interactive)
20450 (org-mode)
20451 (message "Org-mode restarted"))
20453 (defun org-kill-note-or-show-branches ()
20454 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20455 (interactive)
20456 (if (not org-finish-function)
20457 (progn
20458 (hide-subtree)
20459 (call-interactively 'show-branches))
20460 (let ((org-note-abort t))
20461 (funcall org-finish-function))))
20463 (defun org-open-line (n)
20464 "Insert a new row in tables, call `open-line' elsewhere.
20465 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
20466 (interactive "*p")
20467 (cond
20468 ((not org-special-ctrl-o)
20469 (open-line n))
20470 ((org-at-table-p)
20471 (org-table-insert-row))
20473 (open-line n))))
20475 (defun org-return (&optional indent)
20476 "Goto next table row or insert a newline.
20477 Calls `org-table-next-row' or `newline', depending on context.
20478 See the individual commands for more information."
20479 (interactive)
20480 (let (org-ts-what)
20481 (cond
20482 ((or (bobp) (org-in-src-block-p))
20483 (if indent (newline-and-indent) (newline)))
20484 ((org-at-table-p)
20485 (org-table-justify-field-maybe)
20486 (call-interactively 'org-table-next-row))
20487 ;; when `newline-and-indent' is called within a list, make sure
20488 ;; text moved stays inside the item.
20489 ((and (org-in-item-p) indent)
20490 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20491 (progn
20492 (save-match-data (newline))
20493 (org-indent-line-to (length (match-string 0))))
20494 (let ((ind (org-get-indentation)))
20495 (newline)
20496 (if (org-looking-back org-list-end-re)
20497 (org-indent-line)
20498 (org-indent-line-to ind)))))
20499 ((and org-return-follows-link
20500 (org-at-timestamp-p t)
20501 (not (eq org-ts-what 'after)))
20502 (org-follow-timestamp-link))
20503 ((and org-return-follows-link
20504 (let ((tprop (get-text-property (point) 'face)))
20505 (or (eq tprop 'org-link)
20506 (and (listp tprop) (memq 'org-link tprop)))))
20507 (call-interactively 'org-open-at-point))
20508 ((and (org-at-heading-p)
20509 (looking-at
20510 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20511 (org-show-entry)
20512 (end-of-line 1)
20513 (newline))
20514 (t (if indent (newline-and-indent) (newline))))))
20516 (defun org-return-indent ()
20517 "Goto next table row or insert a newline and indent.
20518 Calls `org-table-next-row' or `newline-and-indent', depending on
20519 context. See the individual commands for more information."
20520 (interactive)
20521 (org-return t))
20523 (defun org-ctrl-c-star ()
20524 "Compute table, or change heading status of lines.
20525 Calls `org-table-recalculate' or `org-toggle-heading',
20526 depending on context."
20527 (interactive)
20528 (cond
20529 ((org-at-table-p)
20530 (call-interactively 'org-table-recalculate))
20532 ;; Convert all lines in region to list items
20533 (call-interactively 'org-toggle-heading))))
20535 (defun org-ctrl-c-minus ()
20536 "Insert separator line in table or modify bullet status of line.
20537 Also turns a plain line or a region of lines into list items.
20538 Calls `org-table-insert-hline', `org-toggle-item', or
20539 `org-cycle-list-bullet', depending on context."
20540 (interactive)
20541 (cond
20542 ((org-at-table-p)
20543 (call-interactively 'org-table-insert-hline))
20544 ((org-region-active-p)
20545 (call-interactively 'org-toggle-item))
20546 ((org-in-item-p)
20547 (call-interactively 'org-cycle-list-bullet))
20549 (call-interactively 'org-toggle-item))))
20551 (defun org-toggle-item (arg)
20552 "Convert headings or normal lines to items, items to normal lines.
20553 If there is no active region, only the current line is considered.
20555 If the first non blank line in the region is a headline, convert
20556 all headlines to items, shifting text accordingly.
20558 If it is an item, convert all items to normal lines.
20560 If it is normal text, change region into a list of items.
20561 With a prefix argument ARG, change the region in a single item."
20562 (interactive "P")
20563 (let ((shift-text
20564 (function
20565 ;; Shift text in current section to IND, from point to END.
20566 ;; The function leaves point to END line.
20567 (lambda (ind end)
20568 (let ((min-i 1000) (end (copy-marker end)))
20569 ;; First determine the minimum indentation (MIN-I) of
20570 ;; the text.
20571 (save-excursion
20572 (catch 'exit
20573 (while (< (point) end)
20574 (let ((i (org-get-indentation)))
20575 (cond
20576 ;; Skip blank lines and inline tasks.
20577 ((looking-at "^[ \t]*$"))
20578 ((looking-at org-outline-regexp-bol))
20579 ;; We can't find less than 0 indentation.
20580 ((zerop i) (throw 'exit (setq min-i 0)))
20581 ((< i min-i) (setq min-i i))))
20582 (forward-line))))
20583 ;; Then indent each line so that a line indented to
20584 ;; MIN-I becomes indented to IND. Ignore blank lines
20585 ;; and inline tasks in the process.
20586 (let ((delta (- ind min-i)))
20587 (while (< (point) end)
20588 (unless (or (looking-at "^[ \t]*$")
20589 (looking-at org-outline-regexp-bol))
20590 (org-indent-line-to (+ (org-get-indentation) delta)))
20591 (forward-line)))))))
20592 (skip-blanks
20593 (function
20594 ;; Return beginning of first non-blank line, starting from
20595 ;; line at POS.
20596 (lambda (pos)
20597 (save-excursion
20598 (goto-char pos)
20599 (skip-chars-forward " \r\t\n")
20600 (point-at-bol)))))
20601 beg end)
20602 ;; Determine boundaries of changes.
20603 (if (org-region-active-p)
20604 (setq beg (funcall skip-blanks (region-beginning))
20605 end (copy-marker (region-end)))
20606 (setq beg (funcall skip-blanks (point-at-bol))
20607 end (copy-marker (point-at-eol))))
20608 ;; Depending on the starting line, choose an action on the text
20609 ;; between BEG and END.
20610 (org-with-limited-levels
20611 (save-excursion
20612 (goto-char beg)
20613 (cond
20614 ;; Case 1. Start at an item: de-itemize. Note that it only
20615 ;; happens when a region is active: `org-ctrl-c-minus'
20616 ;; would call `org-cycle-list-bullet' otherwise.
20617 ((org-at-item-p)
20618 (while (< (point) end)
20619 (when (org-at-item-p)
20620 (skip-chars-forward " \t")
20621 (delete-region (point) (match-end 0)))
20622 (forward-line)))
20623 ;; Case 2. Start at an heading: convert to items.
20624 ((org-at-heading-p)
20625 (let* ((bul (org-list-bullet-string "-"))
20626 (bul-len (length bul))
20627 ;; Indentation of the first heading. It should be
20628 ;; relative to the indentation of its parent, if any.
20629 (start-ind (save-excursion
20630 (cond
20631 ((not org-adapt-indentation) 0)
20632 ((not (outline-previous-heading)) 0)
20633 (t (length (match-string 0))))))
20634 ;; Level of first heading. Further headings will be
20635 ;; compared to it to determine hierarchy in the list.
20636 (ref-level (org-reduced-level (org-outline-level))))
20637 (while (< (point) end)
20638 (let* ((level (org-reduced-level (org-outline-level)))
20639 (delta (max 0 (- level ref-level))))
20640 ;; If current headline is less indented than the first
20641 ;; one, set it as reference, in order to preserve
20642 ;; subtrees.
20643 (when (< level ref-level) (setq ref-level level))
20644 (replace-match bul t t)
20645 (org-indent-line-to (+ start-ind (* delta bul-len)))
20646 ;; Ensure all text down to END (or SECTION-END) belongs
20647 ;; to the newly created item.
20648 (let ((section-end (save-excursion
20649 (or (outline-next-heading) (point)))))
20650 (forward-line)
20651 (funcall shift-text
20652 (+ start-ind (* (1+ delta) bul-len))
20653 (min end section-end)))))))
20654 ;; Case 3. Normal line with ARG: make the first line of region
20655 ;; an item, and shift indentation of others lines to
20656 ;; set them as item's body.
20657 (arg (let* ((bul (org-list-bullet-string "-"))
20658 (bul-len (length bul))
20659 (ref-ind (org-get-indentation)))
20660 (skip-chars-forward " \t")
20661 (insert bul)
20662 (forward-line)
20663 (while (< (point) end)
20664 ;; Ensure that lines less indented than first one
20665 ;; still get included in item body.
20666 (funcall shift-text
20667 (+ ref-ind bul-len)
20668 (min end (save-excursion (or (outline-next-heading)
20669 (point)))))
20670 (forward-line))))
20671 ;; Case 4. Normal line without ARG: turn each non-item line
20672 ;; into an item.
20674 (while (< (point) end)
20675 (unless (or (org-at-heading-p) (org-at-item-p))
20676 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20677 (replace-match
20678 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20679 (forward-line))))))))
20681 (defun org-toggle-heading (&optional nstars)
20682 "Convert headings to normal text, or items or text to headings.
20683 If there is no active region, only convert the current line.
20685 With a \\[universal-argument] prefix, convert the whole list at
20686 point into heading.
20688 In a region:
20690 - If the first non blank line is a headline, remove the stars
20691 from all headlines in the region.
20693 - If it is a normal line, turn each and every normal line (i.e.,
20694 not an heading or an item) in the region into headings. If you
20695 want to convert only the first line of this region, use one
20696 universal prefix argument.
20698 - If it is a plain list item, turn all plain list items into headings.
20700 When converting a line into a heading, the number of stars is chosen
20701 such that the lines become children of the current entry. However,
20702 when a numeric prefix argument is given, its value determines the
20703 number of stars to add."
20704 (interactive "P")
20705 (let ((skip-blanks
20706 (function
20707 ;; Return beginning of first non-blank line, starting from
20708 ;; line at POS.
20709 (lambda (pos)
20710 (save-excursion
20711 (goto-char pos)
20712 (while (org-at-comment-p) (forward-line))
20713 (skip-chars-forward " \r\t\n")
20714 (point-at-bol)))))
20715 beg end toggled)
20716 ;; Determine boundaries of changes. If a universal prefix has
20717 ;; been given, put the list in a region. If region ends at a bol,
20718 ;; do not consider the last line to be in the region.
20720 (when (and current-prefix-arg (org-at-item-p))
20721 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20722 (org-mark-element))
20724 (if (org-region-active-p)
20725 (setq beg (funcall skip-blanks (region-beginning))
20726 end (copy-marker (save-excursion
20727 (goto-char (region-end))
20728 (if (bolp) (point) (point-at-eol)))))
20729 (setq beg (funcall skip-blanks (point-at-bol))
20730 end (copy-marker (point-at-eol))))
20731 ;; Ensure inline tasks don't count as headings.
20732 (org-with-limited-levels
20733 (save-excursion
20734 (goto-char beg)
20735 (cond
20736 ;; Case 1. Started at an heading: de-star headings.
20737 ((org-at-heading-p)
20738 (while (< (point) end)
20739 (when (org-at-heading-p t)
20740 (looking-at org-outline-regexp) (replace-match "")
20741 (setq toggled t))
20742 (forward-line)))
20743 ;; Case 2. Started at an item: change items into headlines.
20744 ;; One star will be added by `org-list-to-subtree'.
20745 ((org-at-item-p)
20746 (let* ((stars (make-string
20747 ;; subtract the star that will be added again by
20748 ;; `org-list-to-subtree'
20749 (if (numberp nstars) (1- nstars)
20750 (or (org-current-level) 0))
20751 ?*))
20752 (add-stars
20753 (cond (nstars "") ; stars from prefix only
20754 ((equal stars "") "") ; before first heading
20755 (org-odd-levels-only "*") ; inside heading, odd
20756 (t "")))) ; inside heading, oddeven
20757 (while (< (point) end)
20758 (when (org-at-item-p)
20759 ;; Pay attention to cases when region ends before list.
20760 (let* ((struct (org-list-struct))
20761 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20762 (save-restriction
20763 (narrow-to-region (point) list-end)
20764 (insert
20765 (org-list-to-subtree
20766 (org-list-parse-list t)
20767 '(:istart (concat stars add-stars (funcall get-stars depth))
20768 :icount (concat stars add-stars (funcall get-stars depth)))))))
20769 (setq toggled t))
20770 (forward-line))))
20771 ;; Case 3. Started at normal text: make every line an heading,
20772 ;; skipping headlines and items.
20773 (t (let* ((stars
20774 (make-string
20775 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20776 (add-stars
20777 (cond (nstars "") ; stars from prefix only
20778 ((equal stars "") "*") ; before first heading
20779 (org-odd-levels-only "**") ; inside heading, odd
20780 (t "*"))) ; inside heading, oddeven
20781 (rpl (concat stars add-stars " "))
20782 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20783 (while (< (point) (if (equal nstars '(4)) lend end))
20784 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20785 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20786 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20787 (forward-line)))))))
20788 (unless toggled (message "Cannot toggle heading from here"))))
20790 (defun org-meta-return (&optional arg)
20791 "Insert a new heading or wrap a region in a table.
20792 Calls `org-insert-heading' or `org-table-wrap-region', depending
20793 on context. See the individual commands for more information."
20794 (interactive "P")
20795 (org-check-before-invisible-edit 'insert)
20796 (or (run-hook-with-args-until-success 'org-metareturn-hook)
20797 (let* ((element (org-element-at-point))
20798 (type (org-element-type element)))
20799 (when (eq type 'table-row)
20800 (setq element (org-element-property :parent element))
20801 (setq type 'table))
20802 (if (and (eq type 'table)
20803 (eq (org-element-property :type element) 'org)
20804 (>= (point) (org-element-property :contents-begin element))
20805 (< (point) (org-element-property :contents-end element)))
20806 (call-interactively 'org-table-wrap-region)
20807 (call-interactively 'org-insert-heading)))))
20809 ;;; Menu entries
20811 (defsubst org-in-subtree-not-table-p ()
20812 "Are we in a subtree and not in a table?"
20813 (and (not (org-before-first-heading-p))
20814 (not (org-at-table-p))))
20816 ;; Define the Org-mode menus
20817 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20818 '("Tbl"
20819 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20820 ["Next Field" org-cycle (org-at-table-p)]
20821 ["Previous Field" org-shifttab (org-at-table-p)]
20822 ["Next Row" org-return (org-at-table-p)]
20823 "--"
20824 ["Blank Field" org-table-blank-field (org-at-table-p)]
20825 ["Edit Field" org-table-edit-field (org-at-table-p)]
20826 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20827 "--"
20828 ("Column"
20829 ["Move Column Left" org-metaleft (org-at-table-p)]
20830 ["Move Column Right" org-metaright (org-at-table-p)]
20831 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20832 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20833 ("Row"
20834 ["Move Row Up" org-metaup (org-at-table-p)]
20835 ["Move Row Down" org-metadown (org-at-table-p)]
20836 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20837 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20838 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20839 "--"
20840 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20841 ("Rectangle"
20842 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20843 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20844 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20845 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20846 "--"
20847 ("Calculate"
20848 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20849 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20850 ["Edit Formulas" org-edit-special (org-at-table-p)]
20851 "--"
20852 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20853 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20854 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20855 "--"
20856 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20857 "--"
20858 ["Sum Column/Rectangle" org-table-sum
20859 (or (org-at-table-p) (org-region-active-p))]
20860 ["Which Column?" org-table-current-column (org-at-table-p)])
20861 ["Debug Formulas"
20862 org-table-toggle-formula-debugger
20863 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20864 ["Show Col/Row Numbers"
20865 org-table-toggle-coordinate-overlays
20866 :style toggle
20867 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20868 "--"
20869 ["Create" org-table-create (and (not (org-at-table-p))
20870 org-enable-table-editor)]
20871 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20872 ["Import from File" org-table-import (not (org-at-table-p))]
20873 ["Export to File" org-table-export (org-at-table-p)]
20874 "--"
20875 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20877 (easy-menu-define org-org-menu org-mode-map "Org menu"
20878 '("Org"
20879 ("Show/Hide"
20880 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20881 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20882 ["Sparse Tree..." org-sparse-tree t]
20883 ["Reveal Context" org-reveal t]
20884 ["Show All" show-all t]
20885 "--"
20886 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20887 "--"
20888 ["New Heading" org-insert-heading t]
20889 ("Navigate Headings"
20890 ["Up" outline-up-heading t]
20891 ["Next" outline-next-visible-heading t]
20892 ["Previous" outline-previous-visible-heading t]
20893 ["Next Same Level" outline-forward-same-level t]
20894 ["Previous Same Level" outline-backward-same-level t]
20895 "--"
20896 ["Jump" org-goto t])
20897 ("Edit Structure"
20898 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20899 "--"
20900 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20901 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20902 "--"
20903 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20904 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20905 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20906 "--"
20907 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20908 "--"
20909 ["Copy visible text" org-copy-visible t]
20910 "--"
20911 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20912 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20913 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20914 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20915 "--"
20916 ["Sort Region/Children" org-sort t]
20917 "--"
20918 ["Convert to odd levels" org-convert-to-odd-levels t]
20919 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20920 ("Editing"
20921 ["Emphasis..." org-emphasize t]
20922 ["Edit Source Example" org-edit-special t]
20923 "--"
20924 ["Footnote new/jump" org-footnote-action t]
20925 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20926 ("Archive"
20927 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20928 "--"
20929 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20930 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20931 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20933 "--"
20934 ("Hyperlinks"
20935 ["Store Link (Global)" org-store-link t]
20936 ["Find existing link to here" org-occur-link-in-agenda-files t]
20937 ["Insert Link" org-insert-link t]
20938 ["Follow Link" org-open-at-point t]
20939 "--"
20940 ["Next link" org-next-link t]
20941 ["Previous link" org-previous-link t]
20942 "--"
20943 ["Descriptive Links"
20944 org-toggle-link-display
20945 :style radio
20946 :selected org-descriptive-links
20948 ["Literal Links"
20949 org-toggle-link-display
20950 :style radio
20951 :selected (not org-descriptive-links)])
20952 "--"
20953 ("TODO Lists"
20954 ["TODO/DONE/-" org-todo t]
20955 ("Select keyword"
20956 ["Next keyword" org-shiftright (org-at-heading-p)]
20957 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20958 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20959 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20960 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20961 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20962 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20963 "--"
20964 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20965 :selected org-enforce-todo-dependencies :style toggle :active t]
20966 "Settings for tree at point"
20967 ["Do Children sequentially" org-toggle-ordered-property :style radio
20968 :selected (org-entry-get nil "ORDERED")
20969 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20970 ["Do Children parallel" org-toggle-ordered-property :style radio
20971 :selected (not (org-entry-get nil "ORDERED"))
20972 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20973 "--"
20974 ["Set Priority" org-priority t]
20975 ["Priority Up" org-shiftup t]
20976 ["Priority Down" org-shiftdown t]
20977 "--"
20978 ["Get news from all feeds" org-feed-update-all t]
20979 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20980 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20981 ("TAGS and Properties"
20982 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20983 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20984 "--"
20985 ["Set property" org-set-property (not (org-before-first-heading-p))]
20986 ["Column view of properties" org-columns t]
20987 ["Insert Column View DBlock" org-insert-columns-dblock t])
20988 ("Dates and Scheduling"
20989 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20990 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20991 ("Change Date"
20992 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20993 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20994 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20995 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20996 ["Compute Time Range" org-evaluate-time-range t]
20997 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20998 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20999 "--"
21000 ["Custom time format" org-toggle-time-stamp-overlays
21001 :style radio :selected org-display-custom-times]
21002 "--"
21003 ["Goto Calendar" org-goto-calendar t]
21004 ["Date from Calendar" org-date-from-calendar t]
21005 "--"
21006 ["Start/Restart Timer" org-timer-start t]
21007 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21008 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21009 ["Insert Timer String" org-timer t]
21010 ["Insert Timer Item" org-timer-item t])
21011 ("Logging work"
21012 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21013 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21014 ["Clock out" org-clock-out t]
21015 ["Clock cancel" org-clock-cancel t]
21016 "--"
21017 ["Mark as default task" org-clock-mark-default-task t]
21018 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21019 ["Goto running clock" org-clock-goto t]
21020 "--"
21021 ["Display times" org-clock-display t]
21022 ["Create clock table" org-clock-report t]
21023 "--"
21024 ["Record DONE time"
21025 (progn (setq org-log-done (not org-log-done))
21026 (message "Switching to %s will %s record a timestamp"
21027 (car org-done-keywords)
21028 (if org-log-done "automatically" "not")))
21029 :style toggle :selected org-log-done])
21030 "--"
21031 ["Agenda Command..." org-agenda t]
21032 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21033 ("File List for Agenda")
21034 ("Special views current file"
21035 ["TODO Tree" org-show-todo-tree t]
21036 ["Check Deadlines" org-check-deadlines t]
21037 ["Timeline" org-timeline t]
21038 ["Tags/Property tree" org-match-sparse-tree t])
21039 "--"
21040 ["Export/Publish..." org-export-dispatch t]
21041 ("LaTeX"
21042 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21043 :selected org-cdlatex-mode]
21044 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21045 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21046 ["Modify math symbol" org-cdlatex-math-modify
21047 (org-inside-LaTeX-fragment-p)]
21048 ["Insert citation" org-reftex-citation t]
21049 "--"
21050 ["Template for BEAMER" (org-beamer-insert-options-template) t])
21051 "--"
21052 ("MobileOrg"
21053 ["Push Files and Views" org-mobile-push t]
21054 ["Get Captured and Flagged" org-mobile-pull t]
21055 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21056 "--"
21057 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21058 "--"
21059 ("Documentation"
21060 ["Show Version" org-version t]
21061 ["Info Documentation" org-info t])
21062 ("Customize"
21063 ["Browse Org Group" org-customize t]
21064 "--"
21065 ["Expand This Menu" org-create-customize-menu
21066 (fboundp 'customize-menu-create)])
21067 ["Send bug report" org-submit-bug-report t]
21068 "--"
21069 ("Refresh/Reload"
21070 ["Refresh setup current buffer" org-mode-restart t]
21071 ["Reload Org (after update)" org-reload t]
21072 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21075 (defun org-info (&optional node)
21076 "Read documentation for Org-mode in the info system.
21077 With optional NODE, go directly to that node."
21078 (interactive)
21079 (info (format "(org)%s" (or node ""))))
21081 ;;;###autoload
21082 (defun org-submit-bug-report ()
21083 "Submit a bug report on Org-mode via mail.
21085 Don't hesitate to report any problems or inaccurate documentation.
21087 If you don't have setup sending mail from (X)Emacs, please copy the
21088 output buffer into your mail program, as it gives us important
21089 information about your Org-mode version and configuration."
21090 (interactive)
21091 (require 'reporter)
21092 (org-load-modules-maybe)
21093 (org-require-autoloaded-modules)
21094 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21095 (reporter-submit-bug-report
21096 "emacs-orgmode@gnu.org"
21097 (org-version nil 'full)
21098 (let (list)
21099 (save-window-excursion
21100 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21101 (delete-other-windows)
21102 (erase-buffer)
21103 (insert "You are about to submit a bug report to the Org-mode mailing list.
21105 We would like to add your full Org-mode and Outline configuration to the
21106 bug report. This greatly simplifies the work of the maintainer and
21107 other experts on the mailing list.
21109 HOWEVER, some variables you have customized may contain private
21110 information. The names of customers, colleagues, or friends, might
21111 appear in the form of file names, tags, todo states, or search strings.
21112 If you answer yes to the prompt, you might want to check and remove
21113 such private information before sending the email.")
21114 (add-text-properties (point-min) (point-max) '(face org-warning))
21115 (when (yes-or-no-p "Include your Org-mode configuration ")
21116 (mapatoms
21117 (lambda (v)
21118 (and (boundp v)
21119 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21120 (or (and (symbol-value v)
21121 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21122 (and
21123 (get v 'custom-type) (get v 'standard-value)
21124 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21125 (push v list)))))
21126 (kill-buffer (get-buffer "*Warn about privacy*"))
21127 list))
21128 nil nil
21129 "Remember to cover the basics, that is, what you expected to happen and
21130 what in fact did happen. You don't know how to make a good report? See
21132 http://orgmode.org/manual/Feedback.html#Feedback
21134 Your bug report will be posted to the Org-mode mailing list.
21135 ------------------------------------------------------------------------")
21136 (save-excursion
21137 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21138 (replace-match "\\1Bug: \\3 [\\2]")))))
21141 (defun org-install-agenda-files-menu ()
21142 (let ((bl (buffer-list)))
21143 (save-excursion
21144 (while bl
21145 (set-buffer (pop bl))
21146 (if (derived-mode-p 'org-mode) (setq bl nil)))
21147 (when (derived-mode-p 'org-mode)
21148 (easy-menu-change
21149 '("Org") "File List for Agenda"
21150 (append
21151 (list
21152 ["Edit File List" (org-edit-agenda-file-list) t]
21153 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21154 ["Remove Current File from List" org-remove-file t]
21155 ["Cycle through agenda files" org-cycle-agenda-files t]
21156 ["Occur in all agenda files" org-occur-in-agenda-files t]
21157 "--")
21158 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21160 ;;;; Documentation
21162 (defun org-require-autoloaded-modules ()
21163 (interactive)
21164 (mapc 'require
21165 '(org-agenda org-archive org-attach org-clock org-colview org-id
21166 org-table org-timer)))
21168 ;;;###autoload
21169 (defun org-reload (&optional uncompiled)
21170 "Reload all org lisp files.
21171 With prefix arg UNCOMPILED, load the uncompiled versions."
21172 (interactive "P")
21173 (require 'loadhist)
21174 (let* ((org-dir (org-find-library-dir "org"))
21175 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21176 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21177 (remove-re (mapconcat 'identity
21178 (mapcar (lambda (f) (concat "^" f "$"))
21179 (list (if (featurep 'xemacs)
21180 "org-colview"
21181 "org-colview-xemacs")
21182 "org" "org-loaddefs" "org-version"))
21183 "\\|"))
21184 (feats (delete-dups
21185 (mapcar 'file-name-sans-extension
21186 (mapcar 'file-name-nondirectory
21187 (delq nil
21188 (mapcar 'feature-file
21189 features))))))
21190 (lfeat (append
21191 (sort
21192 (setq feats
21193 (delq nil (mapcar
21194 (lambda (f)
21195 (if (and (string-match feature-re f)
21196 (not (string-match remove-re f)))
21197 f nil))
21198 feats)))
21199 'string-lessp)
21200 (list "org-version" "org")))
21201 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21202 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21203 load-uncore load-misses)
21204 (setq load-misses
21205 (delq 't
21206 (mapcar (lambda (f)
21207 (or (org-load-noerror-mustsuffix (concat org-dir f))
21208 (and (string= org-dir contrib-dir)
21209 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21210 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21211 (add-to-list 'load-uncore f 'append)
21214 lfeat)))
21215 (if load-uncore
21216 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21217 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21218 (if load-misses
21219 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21220 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21221 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21223 ;;;###autoload
21224 (defun org-customize ()
21225 "Call the customize function with org as argument."
21226 (interactive)
21227 (org-load-modules-maybe)
21228 (org-require-autoloaded-modules)
21229 (customize-browse 'org))
21231 (defun org-create-customize-menu ()
21232 "Create a full customization menu for Org-mode, insert it into the menu."
21233 (interactive)
21234 (org-load-modules-maybe)
21235 (org-require-autoloaded-modules)
21236 (if (fboundp 'customize-menu-create)
21237 (progn
21238 (easy-menu-change
21239 '("Org") "Customize"
21240 `(["Browse Org group" org-customize t]
21241 "--"
21242 ,(customize-menu-create 'org)
21243 ["Set" Custom-set t]
21244 ["Save" Custom-save t]
21245 ["Reset to Current" Custom-reset-current t]
21246 ["Reset to Saved" Custom-reset-saved t]
21247 ["Reset to Standard Settings" Custom-reset-standard t]))
21248 (message "\"Org\"-menu now contains full customization menu"))
21249 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21251 ;;;; Miscellaneous stuff
21253 ;;; Generally useful functions
21255 (defun org-get-at-bol (property)
21256 "Get text property PROPERTY at beginning of line."
21257 (get-text-property (point-at-bol) property))
21259 (defun org-find-text-property-in-string (prop s)
21260 "Return the first non-nil value of property PROP in string S."
21261 (or (get-text-property 0 prop s)
21262 (get-text-property (or (next-single-property-change 0 prop s) 0)
21263 prop s)))
21265 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21266 "Display the given MESSAGE as a warning."
21267 (if (fboundp 'display-warning)
21268 (display-warning 'org message
21269 (if (featurep 'xemacs) 'warning :warning))
21270 (let ((buf (get-buffer-create "*Org warnings*")))
21271 (with-current-buffer buf
21272 (goto-char (point-max))
21273 (insert "Warning (Org): " message)
21274 (unless (bolp)
21275 (newline)))
21276 (display-buffer buf)
21277 (sit-for 0))))
21279 (defun org-eval (form)
21280 "Eval FORM and return result."
21281 (condition-case error
21282 (eval form)
21283 (error (format "%%![Error: %s]" error))))
21285 (defun org-in-clocktable-p ()
21286 "Check if the cursor is in a clocktable."
21287 (let ((pos (point)) start)
21288 (save-excursion
21289 (end-of-line 1)
21290 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21291 (setq start (match-beginning 0))
21292 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21293 (>= (match-end 0) pos)
21294 start))))
21296 (defun org-in-commented-line ()
21297 "Is point in a line starting with `#'?"
21298 (equal (char-after (point-at-bol)) ?#))
21300 (defun org-in-indented-comment-line ()
21301 "Is point in a line starting with `#' after some white space?"
21302 (save-excursion
21303 (save-match-data
21304 (goto-char (point-at-bol))
21305 (looking-at "[ \t]*#"))))
21307 (defun org-in-verbatim-emphasis ()
21308 (save-match-data
21309 (and (org-in-regexp org-emph-re 2)
21310 (>= (point) (match-beginning 3))
21311 (<= (point) (match-end 4))
21312 (member (match-string 3) '("=" "~")))))
21314 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21315 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21316 (if (and marker (marker-buffer marker)
21317 (buffer-live-p (marker-buffer marker)))
21318 (progn
21319 (org-pop-to-buffer-same-window (marker-buffer marker))
21320 (if (or (> marker (point-max)) (< marker (point-min)))
21321 (widen))
21322 (goto-char marker)
21323 (org-show-context 'org-goto))
21324 (if bookmark
21325 (bookmark-jump bookmark)
21326 (error "Cannot find location"))))
21328 (defun org-quote-csv-field (s)
21329 "Quote field for inclusion in CSV material."
21330 (if (string-match "[\",]" s)
21331 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21334 (defun org-force-self-insert (N)
21335 "Needed to enforce self-insert under remapping."
21336 (interactive "p")
21337 (self-insert-command N))
21339 (defun org-string-width (s)
21340 "Compute width of string, ignoring invisible characters.
21341 This ignores character with invisibility property `org-link', and also
21342 characters with property `org-cwidth', because these will become invisible
21343 upon the next fontification round."
21344 (let (b l)
21345 (when (or (eq t buffer-invisibility-spec)
21346 (assq 'org-link buffer-invisibility-spec))
21347 (while (setq b (text-property-any 0 (length s)
21348 'invisible 'org-link s))
21349 (setq s (concat (substring s 0 b)
21350 (substring s (or (next-single-property-change
21351 b 'invisible s) (length s)))))))
21352 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21353 (setq s (concat (substring s 0 b)
21354 (substring s (or (next-single-property-change
21355 b 'org-cwidth s) (length s))))))
21356 (setq l (string-width s) b -1)
21357 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21358 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21361 (defun org-shorten-string (s maxlength)
21362 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21363 If the string is shorter or has length MAXLENGTH, just return the
21364 original string. If it is longer, the functions finds a space in the
21365 string, breaks this string off at that locations and adds three dots
21366 as ellipsis. Including the ellipsis, the string will not be longer
21367 than MAXLENGTH. If finding a good breaking point in the string does
21368 not work, the string is just chopped off in the middle of a word
21369 if necessary."
21370 (if (<= (length s) maxlength)
21372 (let* ((n (max (- maxlength 4) 1))
21373 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21374 (if (string-match re s)
21375 (concat (match-string 1 s) "...")
21376 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21378 (defun org-get-indentation (&optional line)
21379 "Get the indentation of the current line, interpreting tabs.
21380 When LINE is given, assume it represents a line and compute its indentation."
21381 (if line
21382 (if (string-match "^ *" (org-remove-tabs line))
21383 (match-end 0))
21384 (save-excursion
21385 (beginning-of-line 1)
21386 (skip-chars-forward " \t")
21387 (current-column))))
21389 (defun org-get-string-indentation (s)
21390 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21391 (let ((n -1) (i 0) (w tab-width) c)
21392 (catch 'exit
21393 (while (< (setq n (1+ n)) (length s))
21394 (setq c (aref s n))
21395 (cond ((= c ?\ ) (setq i (1+ i)))
21396 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21397 (t (throw 'exit t)))))
21400 (defun org-remove-tabs (s &optional width)
21401 "Replace tabulators in S with spaces.
21402 Assumes that s is a single line, starting in column 0."
21403 (setq width (or width tab-width))
21404 (while (string-match "\t" s)
21405 (setq s (replace-match
21406 (make-string
21407 (- (* width (/ (+ (match-beginning 0) width) width))
21408 (match-beginning 0)) ?\ )
21409 t t s)))
21412 (defun org-fix-indentation (line ind)
21413 "Fix indentation in LINE.
21414 IND is a cons cell with target and minimum indentation.
21415 If the current indentation in LINE is smaller than the minimum,
21416 leave it alone. If it is larger than ind, set it to the target."
21417 (let* ((l (org-remove-tabs line))
21418 (i (org-get-indentation l))
21419 (i1 (car ind)) (i2 (cdr ind)))
21420 (if (>= i i2) (setq l (substring line i2)))
21421 (if (> i1 0)
21422 (concat (make-string i1 ?\ ) l)
21423 l)))
21425 (defun org-remove-indentation (code &optional n)
21426 "Remove the maximum common indentation from the lines in CODE.
21427 N may optionally be the number of spaces to remove."
21428 (with-temp-buffer
21429 (insert code)
21430 (org-do-remove-indentation n)
21431 (buffer-string)))
21433 (defun org-do-remove-indentation (&optional n)
21434 "Remove the maximum common indentation from the buffer."
21435 (untabify (point-min) (point-max))
21436 (let ((min 10000) re)
21437 (if n
21438 (setq min n)
21439 (goto-char (point-min))
21440 (while (re-search-forward "^ *[^ \n]" nil t)
21441 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21442 (unless (or (= min 0) (= min 10000))
21443 (setq re (format "^ \\{%d\\}" min))
21444 (goto-char (point-min))
21445 (while (re-search-forward re nil t)
21446 (replace-match "")
21447 (end-of-line 1))
21448 min)))
21450 (defun org-fill-template (template alist)
21451 "Find each %key of ALIST in TEMPLATE and replace it."
21452 (let ((case-fold-search nil)
21453 entry key value)
21454 (setq alist (sort (copy-sequence alist)
21455 (lambda (a b) (< (length (car a)) (length (car b))))))
21456 (while (setq entry (pop alist))
21457 (setq template
21458 (replace-regexp-in-string
21459 (concat "%" (regexp-quote (car entry)))
21460 (or (cdr entry) "") template t t)))
21461 template))
21463 (defun org-base-buffer (buffer)
21464 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21465 (if (not buffer)
21466 buffer
21467 (or (buffer-base-buffer buffer)
21468 buffer)))
21470 (defun org-trim (s)
21471 "Remove whitespace at beginning and end of string."
21472 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
21473 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
21476 (defun org-wrap (string &optional width lines)
21477 "Wrap string to either a number of lines, or a width in characters.
21478 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21479 that costs. If there is a word longer than WIDTH, the text is actually
21480 wrapped to the length of that word.
21481 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21482 many lines, whatever width that takes.
21483 The return value is a list of lines, without newlines at the end."
21484 (let* ((words (org-split-string string "[ \t\n]+"))
21485 (maxword (apply 'max (mapcar 'org-string-width words)))
21486 w ll)
21487 (cond (width
21488 (org-do-wrap words (max maxword width)))
21489 (lines
21490 (setq w maxword)
21491 (setq ll (org-do-wrap words maxword))
21492 (if (<= (length ll) lines)
21494 (setq ll words)
21495 (while (> (length ll) lines)
21496 (setq w (1+ w))
21497 (setq ll (org-do-wrap words w)))
21498 ll))
21499 (t (error "Cannot wrap this")))))
21501 (defun org-do-wrap (words width)
21502 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21503 (let (lines line)
21504 (while words
21505 (setq line (pop words))
21506 (while (and words (< (+ (length line) (length (car words))) width))
21507 (setq line (concat line " " (pop words))))
21508 (setq lines (push line lines)))
21509 (nreverse lines)))
21511 (defun org-split-string (string &optional separators)
21512 "Splits STRING into substrings at SEPARATORS.
21513 No empty strings are returned if there are matches at the beginning
21514 and end of string."
21515 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21516 (start 0)
21517 notfirst
21518 (list nil))
21519 (while (and (string-match rexp string
21520 (if (and notfirst
21521 (= start (match-beginning 0))
21522 (< start (length string)))
21523 (1+ start) start))
21524 (< (match-beginning 0) (length string)))
21525 (setq notfirst t)
21526 (or (eq (match-beginning 0) 0)
21527 (and (eq (match-beginning 0) (match-end 0))
21528 (eq (match-beginning 0) start))
21529 (setq list
21530 (cons (substring string start (match-beginning 0))
21531 list)))
21532 (setq start (match-end 0)))
21533 (or (eq start (length string))
21534 (setq list
21535 (cons (substring string start)
21536 list)))
21537 (nreverse list)))
21539 (defun org-quote-vert (s)
21540 "Replace \"|\" with \"\\vert\"."
21541 (while (string-match "|" s)
21542 (setq s (replace-match "\\vert" t t s)))
21545 (defun org-uuidgen-p (s)
21546 "Is S an ID created by UUIDGEN?"
21547 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21549 (defun org-in-src-block-p (&optional inside)
21550 "Whether point is in a code source block.
21551 When INSIDE is non-nil, don't consider we are within a src block
21552 when point is at #+BEGIN_SRC or #+END_SRC."
21553 (let ((case-fold-search t) ov)
21554 (or (and (setq ov (overlays-at (point)))
21555 (memq 'org-block-background
21556 (overlay-properties (car ov))))
21557 (and (not inside)
21558 (save-match-data
21559 (save-excursion
21560 (beginning-of-line)
21561 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21563 (defun org-context ()
21564 "Return a list of contexts of the current cursor position.
21565 If several contexts apply, all are returned.
21566 Each context entry is a list with a symbol naming the context, and
21567 two positions indicating start and end of the context. Possible
21568 contexts are:
21570 :headline anywhere in a headline
21571 :headline-stars on the leading stars in a headline
21572 :todo-keyword on a TODO keyword (including DONE) in a headline
21573 :tags on the TAGS in a headline
21574 :priority on the priority cookie in a headline
21575 :item on the first line of a plain list item
21576 :item-bullet on the bullet/number of a plain list item
21577 :checkbox on the checkbox in a plain list item
21578 :table in an org-mode table
21579 :table-special on a special filed in a table
21580 :table-table in a table.el table
21581 :clocktable in a clocktable
21582 :src-block in a source block
21583 :link on a hyperlink
21584 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21585 :target on a <<target>>
21586 :radio-target on a <<<radio-target>>>
21587 :latex-fragment on a LaTeX fragment
21588 :latex-preview on a LaTeX fragment with overlaid preview image
21590 This function expects the position to be visible because it uses font-lock
21591 faces as a help to recognize the following contexts: :table-special, :link,
21592 and :keyword."
21593 (let* ((f (get-text-property (point) 'face))
21594 (faces (if (listp f) f (list f)))
21595 (case-fold-search t)
21596 (p (point)) clist o)
21597 ;; First the large context
21598 (cond
21599 ((org-at-heading-p t)
21600 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21601 (when (progn
21602 (beginning-of-line 1)
21603 (looking-at org-todo-line-tags-regexp))
21604 (push (org-point-in-group p 1 :headline-stars) clist)
21605 (push (org-point-in-group p 2 :todo-keyword) clist)
21606 (push (org-point-in-group p 4 :tags) clist))
21607 (goto-char p)
21608 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21609 (if (looking-at "\\[#[A-Z0-9]\\]")
21610 (push (org-point-in-group p 0 :priority) clist)))
21612 ((org-at-item-p)
21613 (push (org-point-in-group p 2 :item-bullet) clist)
21614 (push (list :item (point-at-bol)
21615 (save-excursion (org-end-of-item) (point)))
21616 clist)
21617 (and (org-at-item-checkbox-p)
21618 (push (org-point-in-group p 0 :checkbox) clist)))
21620 ((org-at-table-p)
21621 (push (list :table (org-table-begin) (org-table-end)) clist)
21622 (if (memq 'org-formula faces)
21623 (push (list :table-special
21624 (previous-single-property-change p 'face)
21625 (next-single-property-change p 'face)) clist)))
21626 ((org-at-table-p 'any)
21627 (push (list :table-table) clist)))
21628 (goto-char p)
21630 (let ((case-fold-search t))
21631 ;; New the "medium" contexts: clocktables, source blocks
21632 (cond ((org-in-clocktable-p)
21633 (push (list :clocktable
21634 (and (or (looking-at "#\\+BEGIN: clocktable")
21635 (search-backward "#+BEGIN: clocktable" nil t))
21636 (match-beginning 0))
21637 (and (re-search-forward "#\\+END:?" nil t)
21638 (match-end 0))) clist))
21639 ((org-in-src-block-p)
21640 (push (list :src-block
21641 (and (or (looking-at "#\\+BEGIN_SRC")
21642 (search-backward "#+BEGIN_SRC" nil t))
21643 (match-beginning 0))
21644 (and (search-forward "#+END_SRC" nil t)
21645 (match-beginning 0))) clist))))
21646 (goto-char p)
21648 ;; Now the small context
21649 (cond
21650 ((org-at-timestamp-p)
21651 (push (org-point-in-group p 0 :timestamp) clist))
21652 ((memq 'org-link faces)
21653 (push (list :link
21654 (previous-single-property-change p 'face)
21655 (next-single-property-change p 'face)) clist))
21656 ((memq 'org-special-keyword faces)
21657 (push (list :keyword
21658 (previous-single-property-change p 'face)
21659 (next-single-property-change p 'face)) clist))
21660 ((org-at-target-p)
21661 (push (org-point-in-group p 0 :target) clist)
21662 (goto-char (1- (match-beginning 0)))
21663 (if (looking-at org-radio-target-regexp)
21664 (push (org-point-in-group p 0 :radio-target) clist))
21665 (goto-char p))
21666 ((setq o (car (delq nil
21667 (mapcar
21668 (lambda (x)
21669 (if (memq x org-latex-fragment-image-overlays) x))
21670 (overlays-at (point))))))
21671 (push (list :latex-fragment
21672 (overlay-start o) (overlay-end o)) clist)
21673 (push (list :latex-preview
21674 (overlay-start o) (overlay-end o)) clist))
21675 ((org-inside-LaTeX-fragment-p)
21676 ;; FIXME: positions wrong.
21677 (push (list :latex-fragment (point) (point)) clist)))
21679 (setq clist (nreverse (delq nil clist)))
21680 clist))
21682 ;; FIXME: Compare with at-regexp-p Do we need both?
21683 (defun org-in-regexp (re &optional nlines visually)
21684 "Check if point is inside a match of regexp.
21685 Normally only the current line is checked, but you can include NLINES extra
21686 lines both before and after point into the search.
21687 If VISUALLY is set, require that the cursor is not after the match but
21688 really on, so that the block visually is on the match."
21689 (catch 'exit
21690 (let ((pos (point))
21691 (eol (point-at-eol (+ 1 (or nlines 0))))
21692 (inc (if visually 1 0)))
21693 (save-excursion
21694 (beginning-of-line (- 1 (or nlines 0)))
21695 (while (re-search-forward re eol t)
21696 (if (and (<= (match-beginning 0) pos)
21697 (>= (+ inc (match-end 0)) pos))
21698 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21700 (defun org-at-regexp-p (regexp)
21701 "Is point inside a match of REGEXP in the current line?"
21702 (catch 'exit
21703 (save-excursion
21704 (let ((pos (point)) (end (point-at-eol)))
21705 (beginning-of-line 1)
21706 (while (re-search-forward regexp end t)
21707 (if (and (<= (match-beginning 0) pos)
21708 (>= (match-end 0) pos))
21709 (throw 'exit t)))
21710 nil))))
21712 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21713 "Non-nil when point is between matches of START-RE and END-RE.
21715 Also return a non-nil value when point is on one of the matches.
21717 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21718 buffer positions. Default values are the positions of headlines
21719 surrounding the point.
21721 The functions returns a cons cell whose car (resp. cdr) is the
21722 position before START-RE (resp. after END-RE)."
21723 (save-match-data
21724 (let ((pos (point))
21725 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21726 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21727 beg end)
21728 (save-excursion
21729 ;; Point is on a block when on START-RE or if START-RE can be
21730 ;; found before it...
21731 (and (or (org-at-regexp-p start-re)
21732 (re-search-backward start-re limit-up t))
21733 (setq beg (match-beginning 0))
21734 ;; ... and END-RE after it...
21735 (goto-char (match-end 0))
21736 (re-search-forward end-re limit-down t)
21737 (> (setq end (match-end 0)) pos)
21738 ;; ... without another START-RE in-between.
21739 (goto-char (match-beginning 0))
21740 (not (re-search-backward start-re (1+ beg) t))
21741 ;; Return value.
21742 (cons beg end))))))
21744 (defun org-in-block-p (names)
21745 "Non-nil when point belongs to a block whose name belongs to NAMES.
21747 NAMES is a list of strings containing names of blocks.
21749 Return first block name matched, or nil. Beware that in case of
21750 nested blocks, the returned name may not belong to the closest
21751 block from point."
21752 (save-match-data
21753 (catch 'exit
21754 (let ((case-fold-search t)
21755 (lim-up (save-excursion (outline-previous-heading)))
21756 (lim-down (save-excursion (outline-next-heading))))
21757 (mapc (lambda (name)
21758 (let ((n (regexp-quote name)))
21759 (when (org-between-regexps-p
21760 (concat "^[ \t]*#\\+begin_" n)
21761 (concat "^[ \t]*#\\+end_" n)
21762 lim-up lim-down)
21763 (throw 'exit n))))
21764 names))
21765 nil)))
21767 (defun org-in-drawer-p ()
21768 "Non-nil if point is within a drawer.
21769 If point is within a drawer, return it, as parsed data."
21770 (let ((element (save-match-data (org-element-at-point))))
21771 (while (and element (not (memq (org-element-type element)
21772 '(drawer property-drawer))))
21773 (setq element (org-element-property :parent element)))
21774 element))
21776 (defun org-occur-in-agenda-files (regexp &optional nlines)
21777 "Call `multi-occur' with buffers for all agenda files."
21778 (interactive "sOrg-files matching: \np")
21779 (let* ((files (org-agenda-files))
21780 (tnames (mapcar 'file-truename files))
21781 (extra org-agenda-text-search-extra-files)
21783 (when (eq (car extra) 'agenda-archives)
21784 (setq extra (cdr extra))
21785 (setq files (org-add-archive-files files)))
21786 (while (setq f (pop extra))
21787 (unless (member (file-truename f) tnames)
21788 (add-to-list 'files f 'append)
21789 (add-to-list 'tnames (file-truename f) 'append)))
21790 (multi-occur
21791 (mapcar (lambda (x)
21792 (with-current-buffer
21793 (or (get-file-buffer x) (find-file-noselect x))
21794 (widen)
21795 (current-buffer)))
21796 files)
21797 regexp)))
21799 (if (boundp 'occur-mode-find-occurrence-hook)
21800 ;; Emacs 23
21801 (add-hook 'occur-mode-find-occurrence-hook
21802 (lambda ()
21803 (when (derived-mode-p 'org-mode)
21804 (org-reveal))))
21805 ;; Emacs 22
21806 (defadvice occur-mode-goto-occurrence
21807 (after org-occur-reveal activate)
21808 (and (derived-mode-p 'org-mode) (org-reveal)))
21809 (defadvice occur-mode-goto-occurrence-other-window
21810 (after org-occur-reveal activate)
21811 (and (derived-mode-p 'org-mode) (org-reveal)))
21812 (defadvice occur-mode-display-occurrence
21813 (after org-occur-reveal activate)
21814 (when (derived-mode-p 'org-mode)
21815 (let ((pos (occur-mode-find-occurrence)))
21816 (with-current-buffer (marker-buffer pos)
21817 (save-excursion
21818 (goto-char pos)
21819 (org-reveal)))))))
21821 (defun org-occur-link-in-agenda-files ()
21822 "Create a link and search for it in the agendas.
21823 The link is not stored in `org-stored-links', it is just created
21824 for the search purpose."
21825 (interactive)
21826 (let ((link (condition-case nil
21827 (org-store-link nil)
21828 (error "Unable to create a link to here"))))
21829 (org-occur-in-agenda-files (regexp-quote link))))
21831 (defun org-reverse-string (string)
21832 "Return the reverse of STRING."
21833 (apply 'string (reverse (string-to-list string))))
21835 (defun org-uniquify-alist (alist)
21836 "Merge elements of ALIST with the same key.
21838 For example, in this alist:
21840 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
21841 => '((a 1 3) (b 2))
21843 merge (a 1) and (a 3) into (a 1 3).
21845 The function returns the new ALIST."
21846 (let (rtn)
21847 (mapc
21848 (lambda (e)
21849 (let (n)
21850 (if (not (assoc (car e) rtn))
21851 (push e rtn)
21852 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
21853 (setq rtn (assq-delete-all (car e) rtn))
21854 (push n rtn))))
21855 alist)
21856 rtn))
21858 (defun org-delete-all (elts list)
21859 "Remove all elements in ELTS from LIST."
21860 (while elts
21861 (setq list (delete (pop elts) list)))
21862 list)
21864 (defun org-count (cl-item cl-seq)
21865 "Count the number of occurrences of ITEM in SEQ.
21866 Taken from `count' in cl-seq.el with all keyword arguments removed."
21867 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21868 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21869 (while (< cl-start cl-end)
21870 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21871 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21872 (setq cl-start (1+ cl-start)))
21873 cl-count))
21875 (defun org-remove-if (predicate seq)
21876 "Remove everything from SEQ that fulfills PREDICATE."
21877 (let (res e)
21878 (while seq
21879 (setq e (pop seq))
21880 (if (not (funcall predicate e)) (push e res)))
21881 (nreverse res)))
21883 (defun org-remove-if-not (predicate seq)
21884 "Remove everything from SEQ that does not fulfill PREDICATE."
21885 (let (res e)
21886 (while seq
21887 (setq e (pop seq))
21888 (if (funcall predicate e) (push e res)))
21889 (nreverse res)))
21891 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21892 "Reduce two-argument FUNCTION across SEQ.
21893 Taken from `reduce' in cl-seq.el with all keyword arguments but
21894 \":initial-value\" removed."
21895 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21896 (cadr (memq :initial-value cl-keys)))
21897 (cl-seq (pop cl-seq))
21898 (t (funcall cl-func)))))
21899 (while cl-seq
21900 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21901 cl-accum))
21903 (defun org-every (pred seq)
21904 "Return true if PREDICATE is true of every element of SEQ.
21905 Adapted from `every' in cl.el."
21906 (catch 'org-every
21907 (mapc (lambda (e) (unless (funcall pred e) (throw 'org-every nil))) seq)
21910 (defun org-some (pred seq)
21911 "Return true if PREDICATE is true of any element of SEQ.
21912 Adapted from `some' in cl.el."
21913 (catch 'org-some
21914 (mapc (lambda (e) (when (funcall pred e) (throw 'org-some t))) seq)
21915 nil))
21917 (defun org-back-over-empty-lines ()
21918 "Move backwards over whitespace, to the beginning of the first empty line.
21919 Returns the number of empty lines passed."
21920 (let ((pos (point)))
21921 (if (cdr (assoc 'heading org-blank-before-new-entry))
21922 (skip-chars-backward " \t\n\r")
21923 (unless (eobp)
21924 (forward-line -1)))
21925 (beginning-of-line 2)
21926 (goto-char (min (point) pos))
21927 (count-lines (point) pos)))
21929 (defun org-skip-whitespace ()
21930 (skip-chars-forward " \t\n\r"))
21932 (defun org-point-in-group (point group &optional context)
21933 "Check if POINT is in match-group GROUP.
21934 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21935 match. If the match group does not exist or point is not inside it,
21936 return nil."
21937 (and (match-beginning group)
21938 (>= point (match-beginning group))
21939 (<= point (match-end group))
21940 (if context
21941 (list context (match-beginning group) (match-end group))
21942 t)))
21944 (defun org-switch-to-buffer-other-window (&rest args)
21945 "Switch to buffer in a second window on the current frame.
21946 In particular, do not allow pop-up frames.
21947 Returns the newly created buffer."
21948 (org-no-popups
21949 (apply 'switch-to-buffer-other-window args)))
21951 (defun org-combine-plists (&rest plists)
21952 "Create a single property list from all plists in PLISTS.
21953 The process starts by copying the first list, and then setting properties
21954 from the other lists. Settings in the last list are the most significant
21955 ones and overrule settings in the other lists."
21956 (let ((rtn (copy-sequence (pop plists)))
21957 p v ls)
21958 (while plists
21959 (setq ls (pop plists))
21960 (while ls
21961 (setq p (pop ls) v (pop ls))
21962 (setq rtn (plist-put rtn p v))))
21963 rtn))
21965 (defun org-replace-escapes (string table)
21966 "Replace %-escapes in STRING with values in TABLE.
21967 TABLE is an association list with keys like \"%a\" and string values.
21968 The sequences in STRING may contain normal field width and padding information,
21969 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21970 so values can contain further %-escapes if they are define later in TABLE."
21971 (let ((tbl (copy-alist table))
21972 (case-fold-search nil)
21973 (pchg 0)
21974 e re rpl)
21975 (while (setq e (pop tbl))
21976 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21977 (when (and (cdr e) (string-match re (cdr e)))
21978 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21979 (safe "SREF"))
21980 (add-text-properties 0 3 (list 'sref sref) safe)
21981 (setcdr e (replace-match safe t t (cdr e)))))
21982 (while (string-match re string)
21983 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21984 (cdr e)))
21985 (setq string (replace-match rpl t t string))))
21986 (while (setq pchg (next-property-change pchg string))
21987 (let ((sref (get-text-property pchg 'sref string)))
21988 (when (and sref (string-match "SREF" string pchg))
21989 (setq string (replace-match sref t t string)))))
21990 string))
21992 (defun org-sublist (list start end)
21993 "Return a section of LIST, from START to END.
21994 Counting starts at 1."
21995 (let (rtn (c start))
21996 (setq list (nthcdr (1- start) list))
21997 (while (and list (<= c end))
21998 (push (pop list) rtn)
21999 (setq c (1+ c)))
22000 (nreverse rtn)))
22002 (defun org-find-base-buffer-visiting (file)
22003 "Like `find-buffer-visiting' but always return the base buffer and
22004 not an indirect buffer."
22005 (let ((buf (or (get-file-buffer file)
22006 (find-buffer-visiting file))))
22007 (if buf
22008 (or (buffer-base-buffer buf) buf)
22009 nil)))
22011 (defun org-image-file-name-regexp (&optional extensions)
22012 "Return regexp matching the file names of images.
22013 If EXTENSIONS is given, only match these."
22014 (if (and (not extensions) (fboundp 'image-file-name-regexp))
22015 (image-file-name-regexp)
22016 (let ((image-file-name-extensions
22017 (or extensions
22018 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
22019 "xbm" "xpm" "pbm" "pgm" "ppm"))))
22020 (concat "\\."
22021 (regexp-opt (nconc (mapcar 'upcase
22022 image-file-name-extensions)
22023 image-file-name-extensions)
22025 "\\'"))))
22027 (defun org-file-image-p (file &optional extensions)
22028 "Return non-nil if FILE is an image."
22029 (save-match-data
22030 (string-match (org-image-file-name-regexp extensions) file)))
22032 (defun org-get-cursor-date (&optional with-time)
22033 "Return the date at cursor in as a time.
22034 This works in the calendar and in the agenda, anywhere else it just
22035 returns the current time.
22036 If WITH-TIME is non-nil, returns the time of the event at point (in
22037 the agenda) or the current time of the day."
22038 (let (date day defd tp tm hod mod)
22039 (when with-time
22040 (setq tp (get-text-property (point) 'time))
22041 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22042 (setq hod (string-to-number (match-string 1 tp))
22043 mod (string-to-number (match-string 2 tp))))
22044 (or tp (setq hod (nth 2 (decode-time (current-time)))
22045 mod (nth 1 (decode-time (current-time))))))
22046 (cond
22047 ((eq major-mode 'calendar-mode)
22048 (setq date (calendar-cursor-to-date)
22049 defd (encode-time 0 (or mod 0) (or hod 0)
22050 (nth 1 date) (nth 0 date) (nth 2 date))))
22051 ((eq major-mode 'org-agenda-mode)
22052 (setq day (get-text-property (point) 'day))
22053 (if day
22054 (setq date (calendar-gregorian-from-absolute day)
22055 defd (encode-time 0 (or mod 0) (or hod 0)
22056 (nth 1 date) (nth 0 date) (nth 2 date))))))
22057 (or defd (current-time))))
22059 (defun org-mark-subtree (&optional up)
22060 "Mark the current subtree.
22061 This puts point at the start of the current subtree, and mark at
22062 the end. If a numeric prefix UP is given, move up into the
22063 hierarchy of headlines by UP levels before marking the subtree."
22064 (interactive "P")
22065 (org-with-limited-levels
22066 (cond ((org-at-heading-p) (beginning-of-line))
22067 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22068 (t (outline-previous-visible-heading 1))))
22069 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
22070 (if (org-called-interactively-p 'any)
22071 (call-interactively 'org-mark-element)
22072 (org-mark-element)))
22075 ;;; Indentation
22077 (defun org-indent-line ()
22078 "Indent line depending on context."
22079 (interactive)
22080 (let* ((pos (point))
22081 (itemp (org-at-item-p))
22082 (case-fold-search t)
22083 (org-drawer-regexp (or org-drawer-regexp "\000"))
22084 (inline-task-p (and (featurep 'org-inlinetask)
22085 (org-inlinetask-in-task-p)))
22086 (inline-re (and inline-task-p
22087 (org-inlinetask-outline-regexp)))
22088 column)
22089 (if (and orgstruct-is-++ (eq pos (point)))
22090 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
22091 (indent-according-to-mode))
22092 (beginning-of-line 1)
22093 (cond
22094 ;; Headings
22095 ((looking-at org-outline-regexp) (setq column 0))
22096 ;; Footnote definition
22097 ((looking-at org-footnote-definition-re) (setq column 0))
22098 ;; Literal examples
22099 ((looking-at "[ \t]*:\\( \\|$\\)")
22100 (setq column (org-get-indentation))) ; do nothing
22101 ;; Lists
22102 ((ignore-errors (goto-char (org-in-item-p)))
22103 (setq column (if itemp
22104 (org-get-indentation)
22105 (org-list-item-body-column (point))))
22106 (goto-char pos))
22107 ;; Drawers
22108 ((and (looking-at "[ \t]*:END:")
22109 (save-excursion (re-search-backward org-drawer-regexp nil t)))
22110 (save-excursion
22111 (goto-char (1- (match-beginning 1)))
22112 (setq column (current-column))))
22113 ;; Special blocks
22114 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
22115 (save-excursion
22116 (re-search-backward
22117 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
22118 (setq column (org-get-indentation (match-string 0))))
22119 ((and (not (looking-at "[ \t]*#\\+begin_"))
22120 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
22121 (save-excursion
22122 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
22123 (setq column
22124 (cond ((equal (downcase (match-string 1)) "src")
22125 ;; src blocks: let `org-edit-src-exit' handle them
22126 (org-get-indentation))
22127 ((equal (downcase (match-string 1)) "example")
22128 (max (org-get-indentation)
22129 (org-get-indentation (match-string 0))))
22131 (org-get-indentation (match-string 0))))))
22132 ;; This line has nothing special, look at the previous relevant
22133 ;; line to compute indentation
22135 (beginning-of-line 0)
22136 (while (and (not (bobp))
22137 (not (looking-at org-table-line-regexp))
22138 (not (looking-at org-drawer-regexp))
22139 ;; When point started in an inline task, do not move
22140 ;; above task starting line.
22141 (not (and inline-task-p (looking-at inline-re)))
22142 ;; Skip drawers, blocks, empty lines, verbatim,
22143 ;; comments, tables, footnotes definitions, lists,
22144 ;; inline tasks.
22145 (or (and (looking-at "[ \t]*:END:")
22146 (re-search-backward org-drawer-regexp nil t))
22147 (and (looking-at "[ \t]*#\\+end_")
22148 (re-search-backward "[ \t]*#\\+begin_"nil t))
22149 (looking-at "[ \t]*[\n:#|]")
22150 (looking-at org-footnote-definition-re)
22151 (and (not inline-task-p)
22152 (featurep 'org-inlinetask)
22153 (org-inlinetask-in-task-p)
22154 (or (org-inlinetask-goto-beginning) t))))
22155 (beginning-of-line 0))
22156 (cond
22157 ;; There was a list item above.
22158 ((ignore-errors (goto-char (org-in-item-p)))
22159 (goto-char (org-list-get-top-point (org-list-struct)))
22160 (setq column (org-get-indentation)))
22161 ;; There was an heading above.
22162 ((looking-at "\\*+[ \t]+")
22163 (if (not org-adapt-indentation)
22164 (setq column 0)
22165 (goto-char (match-end 0))
22166 (setq column (current-column))))
22167 ;; A drawer had started and is unfinished
22168 ((looking-at org-drawer-regexp)
22169 (goto-char (1- (match-beginning 1)))
22170 (setq column (current-column)))
22171 ;; Else, nothing noticeable found: get indentation and go on.
22172 (t (setq column (org-get-indentation))))))
22173 ;; Now apply indentation and move cursor accordingly
22174 (goto-char pos)
22175 (if (<= (current-column) (current-indentation))
22176 (org-indent-line-to column)
22177 (save-excursion (org-indent-line-to column)))
22178 ;; Special polishing for properties, see `org-property-format'
22179 (setq column (current-column))
22180 (beginning-of-line 1)
22181 (if (looking-at org-property-re)
22182 (replace-match (concat (match-string 4)
22183 (format org-property-format
22184 (match-string 1) (match-string 3)))
22185 t t))
22186 (org-move-to-column column))))
22188 (defun org-indent-drawer ()
22189 "Indent the drawer at point."
22190 (interactive)
22191 (let ((p (point))
22192 (e (and (save-excursion (re-search-forward ":END:" nil t))
22193 (match-end 0)))
22194 (folded
22195 (save-excursion
22196 (end-of-line)
22197 (when (overlays-at (point))
22198 (member 'invisible (overlay-properties
22199 (car (overlays-at (point)))))))))
22200 (when folded (org-cycle))
22201 (indent-for-tab-command)
22202 (while (and (move-beginning-of-line 2) (< (point) e))
22203 (indent-for-tab-command))
22204 (goto-char p)
22205 (when folded (org-cycle)))
22206 (message "Drawer at point indented"))
22208 (defun org-indent-block ()
22209 "Indent the block at point."
22210 (interactive)
22211 (let ((p (point))
22212 (case-fold-search t)
22213 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
22214 (match-end 0)))
22215 (folded
22216 (save-excursion
22217 (end-of-line)
22218 (when (overlays-at (point))
22219 (member 'invisible (overlay-properties
22220 (car (overlays-at (point)))))))))
22221 (when folded (org-cycle))
22222 (indent-for-tab-command)
22223 (while (and (move-beginning-of-line 2) (< (point) e))
22224 (indent-for-tab-command))
22225 (goto-char p)
22226 (when folded (org-cycle)))
22227 (message "Block at point indented"))
22229 (defun org-indent-region (start end)
22230 "Indent region."
22231 (interactive "r")
22232 (save-excursion
22233 (let ((line-end (org-current-line end)))
22234 (goto-char start)
22235 (while (< (org-current-line) line-end)
22236 (cond ((org-in-src-block-p t) (org-src-native-tab-command-maybe))
22237 (t (call-interactively 'org-indent-line)))
22238 (move-beginning-of-line 2)))))
22241 ;;; Filling
22243 ;; We use our own fill-paragraph and auto-fill functions.
22245 ;; `org-fill-paragraph' relies on adaptive filling and context
22246 ;; checking. Appropriate `fill-prefix' is computed with
22247 ;; `org-adaptive-fill-function'.
22249 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22250 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22251 ;; `org-adaptive-fill-function' value. Internally,
22252 ;; `org-comment-line-break-function' breaks the line.
22254 ;; `org-setup-filling' installs filling and auto-filling related
22255 ;; variables during `org-mode' initialization.
22257 (defvar org-element-paragraph-separate) ; org-element.el
22258 (defun org-setup-filling ()
22259 (require 'org-element)
22260 ;; Prevent auto-fill from inserting unwanted new items.
22261 (when (boundp 'fill-nobreak-predicate)
22262 (org-set-local
22263 'fill-nobreak-predicate
22264 (org-uniquify
22265 (append fill-nobreak-predicate
22266 '(org-fill-line-break-nobreak-p
22267 org-fill-paragraph-with-timestamp-nobreak-p)))))
22268 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22269 (org-set-local 'paragraph-start paragraph-ending)
22270 (org-set-local 'paragraph-separate paragraph-ending))
22271 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22272 (org-set-local 'auto-fill-inhibit-regexp nil)
22273 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22274 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22275 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22277 (defun org-fill-line-break-nobreak-p ()
22278 "Non-nil when a new line at point would create an Org line break."
22279 (save-excursion
22280 (skip-chars-backward "[ \t]")
22281 (skip-chars-backward "\\\\")
22282 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22284 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22285 "Non-nil when a new line at point would split a timestamp."
22286 (and (org-at-timestamp-p t)
22287 (not (looking-at org-ts-regexp-both))))
22289 (declare-function message-in-body-p "message" ())
22290 (defvar orgtbl-line-start-regexp) ; From org-table.el
22291 (defun org-adaptive-fill-function ()
22292 "Compute a fill prefix for the current line.
22293 Return fill prefix, as a string, or nil if current line isn't
22294 meant to be filled. For convenience, if `adaptive-fill-regexp'
22295 matches in paragraphs or comments, use it."
22296 (catch 'exit
22297 (when (derived-mode-p 'message-mode)
22298 (save-excursion
22299 (beginning-of-line)
22300 (cond ((or (not (message-in-body-p))
22301 (looking-at orgtbl-line-start-regexp))
22302 (throw 'exit nil))
22303 ((looking-at message-cite-prefix-regexp)
22304 (throw 'exit (match-string-no-properties 0)))
22305 ((looking-at org-outline-regexp)
22306 (throw 'exit (make-string (length (match-string 0)) ? ))))))
22307 (org-with-wide-buffer
22308 (let* ((p (line-beginning-position))
22309 (element (save-excursion
22310 (beginning-of-line)
22311 (or (ignore-errors (org-element-at-point))
22312 (user-error "An element cannot be parsed line %d"
22313 (line-number-at-pos (point))))))
22314 (type (org-element-type element))
22315 (post-affiliated (org-element-property :post-affiliated element)))
22316 (unless (and post-affiliated (< p post-affiliated))
22317 (case type
22318 (comment
22319 (save-excursion
22320 (beginning-of-line)
22321 (looking-at "[ \t]*")
22322 (concat (match-string 0) "# ")))
22323 (footnote-definition "")
22324 ((item plain-list)
22325 (make-string (org-list-item-body-column
22326 (or post-affiliated
22327 (org-element-property :begin element)))
22328 ? ))
22329 (paragraph
22330 ;; Fill prefix is usually the same as the current line,
22331 ;; unless the paragraph is at the beginning of an item.
22332 (let ((parent (org-element-property :parent element)))
22333 (save-excursion
22334 (beginning-of-line)
22335 (cond ((eq (org-element-type parent) 'item)
22336 (make-string (org-list-item-body-column
22337 (org-element-property :begin parent))
22338 ? ))
22339 ((and adaptive-fill-regexp
22340 ;; Locally disable
22341 ;; `adaptive-fill-function' to let
22342 ;; `fill-context-prefix' handle
22343 ;; `adaptive-fill-regexp' variable.
22344 (let (adaptive-fill-function)
22345 (fill-context-prefix
22346 post-affiliated
22347 (org-element-property :end element)))))
22348 ((looking-at "[ \t]+") (match-string 0))
22349 (t "")))))
22350 (comment-block
22351 ;; Only fill contents if P is within block boundaries.
22352 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22353 (forward-line)
22354 (point)))
22355 (cend (save-excursion
22356 (goto-char (org-element-property :end element))
22357 (skip-chars-backward " \r\t\n")
22358 (line-beginning-position))))
22359 (when (and (>= p cbeg) (< p cend))
22360 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22361 (match-string 0)
22362 ""))))))))))
22364 (declare-function message-goto-body "message" ())
22365 (defvar message-cite-prefix-regexp) ; From message.el
22366 (defun org-fill-paragraph (&optional justify)
22367 "Fill element at point, when applicable.
22369 This function only applies to comment blocks, comments, example
22370 blocks and paragraphs. Also, as a special case, re-align table
22371 when point is at one.
22373 If JUSTIFY is non-nil (interactively, with prefix argument),
22374 justify as well. If `sentence-end-double-space' is non-nil, then
22375 period followed by one space does not end a sentence, so don't
22376 break a line there. The variable `fill-column' controls the
22377 width for filling.
22379 For convenience, when point is at a plain list, an item or
22380 a footnote definition, try to fill the first paragraph within."
22381 (interactive)
22382 (if (and (derived-mode-p 'message-mode)
22383 (or (not (message-in-body-p))
22384 (save-excursion (move-beginning-of-line 1)
22385 (looking-at message-cite-prefix-regexp))))
22386 ;; First ensure filling is correct in message-mode.
22387 (let ((fill-paragraph-function
22388 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22389 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22390 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22391 (paragraph-separate
22392 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22393 (fill-paragraph nil))
22394 (with-syntax-table org-mode-transpose-word-syntax-table
22395 ;; Move to end of line in order to get the first paragraph
22396 ;; within a plain list or a footnote definition.
22397 (let ((element (save-excursion
22398 (end-of-line)
22399 (or (ignore-errors (org-element-at-point))
22400 (user-error "An element cannot be parsed line %d"
22401 (line-number-at-pos (point)))))))
22402 ;; First check if point is in a blank line at the beginning of
22403 ;; the buffer. In that case, ignore filling.
22404 (case (org-element-type element)
22405 ;; Use major mode filling function is src blocks.
22406 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22407 ;; Align Org tables, leave table.el tables as-is.
22408 (table-row (org-table-align) t)
22409 (table
22410 (when (eq (org-element-property :type element) 'org)
22411 (save-excursion
22412 (goto-char (org-element-property :post-affiliated element))
22413 (org-table-align)))
22415 (paragraph
22416 ;; Paragraphs may contain `line-break' type objects.
22417 (let ((beg (max (point-min)
22418 (org-element-property :contents-begin element)))
22419 (end (min (point-max)
22420 (org-element-property :contents-end element))))
22421 ;; Do nothing if point is at an affiliated keyword.
22422 (if (< (line-end-position) beg) t
22423 (when (derived-mode-p 'message-mode)
22424 ;; In `message-mode', do not fill following citation
22425 ;; in current paragraph nor text before message body.
22426 (let ((body-start (save-excursion (message-goto-body))))
22427 (when body-start (setq beg (max body-start beg))))
22428 (when (save-excursion
22429 (re-search-forward
22430 (concat "^" message-cite-prefix-regexp) end t))
22431 (setq end (match-beginning 0))))
22432 ;; Fill paragraph, taking line breaks into account.
22433 ;; For that, slice the paragraph using line breaks as
22434 ;; separators, and fill the parts in reverse order to
22435 ;; avoid messing with markers.
22436 (save-excursion
22437 (goto-char end)
22438 (mapc
22439 (lambda (pos)
22440 (fill-region-as-paragraph pos (point) justify)
22441 (goto-char pos))
22442 ;; Find the list of ending positions for line breaks
22443 ;; in the current paragraph. Add paragraph
22444 ;; beginning to include first slice.
22445 (nreverse
22446 (cons beg
22447 (org-element-map
22448 (org-element--parse-objects
22449 beg end nil (org-element-restriction 'paragraph))
22450 'line-break
22451 (lambda (lb) (org-element-property :end lb)))))))
22452 t)))
22453 ;; Contents of `comment-block' type elements should be
22454 ;; filled as plain text, but only if point is within block
22455 ;; markers.
22456 (comment-block
22457 (let* ((case-fold-search t)
22458 (beg (save-excursion
22459 (goto-char (org-element-property :begin element))
22460 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22461 (forward-line)
22462 (point)))
22463 (end (save-excursion
22464 (goto-char (org-element-property :end element))
22465 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22466 (line-beginning-position))))
22467 (if (or (< (point) beg) (> (point) end)) t
22468 (fill-region-as-paragraph
22469 (save-excursion (end-of-line)
22470 (re-search-backward "^[ \t]*$" beg 'move)
22471 (line-beginning-position))
22472 (save-excursion (beginning-of-line)
22473 (re-search-forward "^[ \t]*$" end 'move)
22474 (line-beginning-position))
22475 justify))))
22476 ;; Fill comments.
22477 (comment
22478 (let ((begin (org-element-property :post-affiliated element))
22479 (end (org-element-property :end element)))
22480 (when (and (>= (point) begin) (<= (point) end))
22481 (let ((begin (save-excursion
22482 (end-of-line)
22483 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22484 (progn (forward-line) (point))
22485 begin)))
22486 (end (save-excursion
22487 (end-of-line)
22488 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22489 (1- (line-beginning-position))
22490 (skip-chars-backward " \r\t\n")
22491 (line-end-position)))))
22492 ;; Do not fill comments when at a blank line.
22493 (when (> end begin)
22494 (let ((fill-prefix
22495 (save-excursion
22496 (beginning-of-line)
22497 (looking-at "[ \t]*#")
22498 (let ((comment-prefix (match-string 0)))
22499 (goto-char (match-end 0))
22500 (if (looking-at adaptive-fill-regexp)
22501 (concat comment-prefix (match-string 0))
22502 (concat comment-prefix " "))))))
22503 (save-excursion
22504 (fill-region-as-paragraph begin end justify))))))
22506 ;; Ignore every other element.
22507 (otherwise t))))))
22509 (defun org-auto-fill-function ()
22510 "Auto-fill function."
22511 ;; Check if auto-filling is meaningful.
22512 (let ((fc (current-fill-column)))
22513 (when (and fc (> (current-column) fc))
22514 (let* ((fill-prefix (org-adaptive-fill-function))
22515 ;; Enforce empty fill prefix, if required. Otherwise, it
22516 ;; will be computed again.
22517 (adaptive-fill-mode (not (equal fill-prefix ""))))
22518 (when fill-prefix (do-auto-fill))))))
22520 (defun org-comment-line-break-function (&optional soft)
22521 "Break line at point and indent, continuing comment if within one.
22522 The inserted newline is marked hard if variable
22523 `use-hard-newlines' is true, unless optional argument SOFT is
22524 non-nil."
22525 (if soft (insert-and-inherit ?\n) (newline 1))
22526 (save-excursion (forward-char -1) (delete-horizontal-space))
22527 (delete-horizontal-space)
22528 (indent-to-left-margin)
22529 (insert-before-markers-and-inherit fill-prefix))
22532 ;;; Comments
22534 ;; Org comments syntax is quite complex. It requires the entire line
22535 ;; to be just a comment. Also, even with the right syntax at the
22536 ;; beginning of line, some some elements (i.e. verse-block or
22537 ;; example-block) don't accept comments. Usual Emacs comment commands
22538 ;; cannot cope with those requirements. Therefore, Org replaces them.
22540 ;; Org still relies on `comment-dwim', but cannot trust
22541 ;; `comment-only-p'. So, `comment-region-function' and
22542 ;; `uncomment-region-function' both point
22543 ;; to`org-comment-or-uncomment-region'. Eventually,
22544 ;; `org-insert-comment' takes care of insertion of comments at the
22545 ;; beginning of line.
22547 ;; `org-setup-comments-handling' install comments related variables
22548 ;; during `org-mode' initialization.
22550 (defun org-setup-comments-handling ()
22551 (interactive)
22552 (org-set-local 'comment-use-syntax nil)
22553 (org-set-local 'comment-start "# ")
22554 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22555 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22556 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22557 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22559 (defun org-insert-comment ()
22560 "Insert an empty comment above current line.
22561 If the line is empty, insert comment at its beginning. When
22562 point is within a source block, comment according to the related
22563 major mode."
22564 (if (let ((element (org-element-at-point)))
22565 (and (eq (org-element-type element) 'src-block)
22566 (< (save-excursion
22567 (goto-char (org-element-property :post-affiliated element))
22568 (line-end-position))
22569 (point))
22570 (> (save-excursion
22571 (goto-char (org-element-property :end element))
22572 (skip-chars-backward " \r\t\n")
22573 (line-beginning-position))
22574 (point))))
22575 (progn
22576 (require 'ob-core)
22577 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
22578 (beginning-of-line)
22579 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
22580 (open-line 1))
22581 (org-indent-line)
22582 (insert "# ")))
22584 (defvar comment-empty-lines) ; From newcomment.el.
22585 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22586 "Comment or uncomment each non-blank line in the region.
22587 Uncomment each non-blank line between BEG and END if it only
22588 contains commented lines. Otherwise, comment them. If region is
22589 strictly within a source block, use appropriate comment syntax."
22590 (if (let ((element (org-element-at-point)))
22591 (and (eq (org-element-type element) 'src-block)
22592 (< (save-excursion
22593 (goto-char (org-element-property :post-affiliated element))
22594 (line-end-position))
22595 beg)
22596 (>= (save-excursion
22597 (goto-char (org-element-property :end element))
22598 (skip-chars-backward " \r\t\n")
22599 (line-beginning-position))
22600 end)))
22601 (progn
22602 (require 'ob-core)
22603 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
22604 (save-restriction
22605 ;; Restrict region
22606 (narrow-to-region (save-excursion (goto-char beg)
22607 (skip-chars-forward " \r\t\n" end)
22608 (line-beginning-position))
22609 (save-excursion (goto-char end)
22610 (skip-chars-backward " \r\t\n" beg)
22611 (line-end-position)))
22612 (let ((uncommentp
22613 ;; UNCOMMENTP is non-nil when every non blank line between
22614 ;; BEG and END is a comment.
22615 (save-excursion
22616 (goto-char (point-min))
22617 (while (and (not (eobp))
22618 (let ((element (org-element-at-point)))
22619 (and (eq (org-element-type element) 'comment)
22620 (goto-char (min (point-max)
22621 (org-element-property
22622 :end element)))))))
22623 (eobp))))
22624 (if uncommentp
22625 ;; Only blank lines and comments in region: uncomment it.
22626 (save-excursion
22627 (goto-char (point-min))
22628 (while (not (eobp))
22629 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22630 (replace-match "" nil nil nil 1))
22631 (forward-line)))
22632 ;; Comment each line in region.
22633 (let ((min-indent (point-max)))
22634 ;; First find the minimum indentation across all lines.
22635 (save-excursion
22636 (goto-char (point-min))
22637 (while (and (not (eobp)) (not (zerop min-indent)))
22638 (unless (looking-at "[ \t]*$")
22639 (setq min-indent (min min-indent (current-indentation))))
22640 (forward-line)))
22641 ;; Then loop over all lines.
22642 (save-excursion
22643 (goto-char (point-min))
22644 (while (not (eobp))
22645 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22646 ;; Don't get fooled by invisible text (e.g. link path)
22647 ;; when moving to column MIN-INDENT.
22648 (let ((buffer-invisibility-spec nil))
22649 (org-move-to-column min-indent t))
22650 (insert comment-start))
22651 (forward-line)))))))))
22654 ;;; Planning
22656 ;; This section contains tools to operate on timestamp objects, as
22657 ;; returned by, e.g. `org-element-context'.
22659 (defun org-timestamp-has-time-p (timestamp)
22660 "Non-nil when TIMESTAMP has a time specified."
22661 (org-element-property :hour-start timestamp))
22663 (defun org-timestamp-format (timestamp format &optional end utc)
22664 "Format a TIMESTAMP element into a string.
22666 FORMAT is a format specifier to be passed to
22667 `format-time-string'.
22669 When optional argument END is non-nil, use end of date-range or
22670 time-range, if possible.
22672 When optional argument UTC is non-nil, time will be expressed as
22673 Universal Time."
22674 (format-time-string
22675 format
22676 (apply 'encode-time
22677 (cons 0
22678 (mapcar
22679 (lambda (prop) (or (org-element-property prop timestamp) 0))
22680 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22681 '(:minute-start :hour-start :day-start :month-start
22682 :year-start)))))
22683 utc))
22685 (defun org-timestamp-split-range (timestamp &optional end)
22686 "Extract a timestamp object from a date or time range.
22688 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22689 the end of the range. Otherwise, extract its start.
22691 Return a new timestamp object sharing the same parent as
22692 TIMESTAMP."
22693 (let ((type (org-element-property :type timestamp)))
22694 (if (memq type '(active inactive diary)) timestamp
22695 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22696 ;; Set new type.
22697 (org-element-put-property
22698 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22699 ;; Copy start properties over end properties if END is
22700 ;; non-nil. Otherwise, copy end properties over `start' ones.
22701 (let ((p-alist '((:minute-start . :minute-end)
22702 (:hour-start . :hour-end)
22703 (:day-start . :day-end)
22704 (:month-start . :month-end)
22705 (:year-start . :year-end))))
22706 (dolist (p-cell p-alist)
22707 (org-element-put-property
22708 split-ts
22709 (funcall (if end 'car 'cdr) p-cell)
22710 (org-element-property
22711 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22712 ;; Eventually refresh `:raw-value'.
22713 (org-element-put-property split-ts :raw-value nil)
22714 (org-element-put-property
22715 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22717 (defun org-timestamp-translate (timestamp &optional boundary)
22718 "Apply `org-translate-time' on a TIMESTAMP object.
22719 When optional argument BOUNDARY is non-nil, it is either the
22720 symbol `start' or `end'. In this case, only translate the
22721 starting or ending part of TIMESTAMP if it is a date or time
22722 range. Otherwise, translate both parts."
22723 (if (and (not boundary)
22724 (memq (org-element-property :type timestamp)
22725 '(active-range inactive-range)))
22726 (concat
22727 (org-translate-time
22728 (org-element-property :raw-value
22729 (org-timestamp-split-range timestamp)))
22730 "--"
22731 (org-translate-time
22732 (org-element-property :raw-value
22733 (org-timestamp-split-range timestamp t))))
22734 (org-translate-time
22735 (org-element-property
22736 :raw-value
22737 (if (not boundary) timestamp
22738 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22742 ;;; Other stuff.
22744 (defun org-toggle-fixed-width-section (arg)
22745 "Toggle the fixed-width export.
22746 If there is no active region, the QUOTE keyword at the current headline is
22747 inserted or removed. When present, it causes the text between this headline
22748 and the next to be exported as fixed-width text, and unmodified.
22749 If there is an active region, this command adds or removes a colon as the
22750 first character of this line. If the first character of a line is a colon,
22751 this line is also exported in fixed-width font."
22752 (interactive "P")
22753 (let* ((cc 0)
22754 (regionp (org-region-active-p))
22755 (beg (if regionp (region-beginning) (point)))
22756 (end (if regionp (region-end)))
22757 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22758 (case-fold-search nil)
22759 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22760 off)
22761 (if regionp
22762 (save-excursion
22763 (goto-char beg)
22764 (setq cc (current-column))
22765 (beginning-of-line 1)
22766 (setq off (looking-at re))
22767 (while (> nlines 0)
22768 (setq nlines (1- nlines))
22769 (beginning-of-line 1)
22770 (cond
22771 (arg
22772 (org-move-to-column cc t)
22773 (insert ": \n")
22774 (forward-line -1))
22775 ((and off (looking-at re))
22776 (replace-match "" t t nil 1))
22777 ((not off) (org-move-to-column cc t) (insert ": ")))
22778 (forward-line 1)))
22779 (save-excursion
22780 (org-back-to-heading)
22781 (cond
22782 ((looking-at (format org-heading-keyword-regexp-format
22783 org-quote-string))
22784 (goto-char (match-end 1))
22785 (looking-at (concat " +" org-quote-string))
22786 (replace-match "" t t)
22787 (when (eolp) (insert " ")))
22788 ((looking-at org-outline-regexp)
22789 (goto-char (match-end 0))
22790 (insert org-quote-string " ")))))))
22792 (defun org-reftex-citation ()
22793 "Use reftex-citation to insert a citation into the buffer.
22794 This looks for a line like
22796 #+BIBLIOGRAPHY: foo plain option:-d
22798 and derives from it that foo.bib is the bibliography file relevant
22799 for this document. It then installs the necessary environment for RefTeX
22800 to work in this buffer and calls `reftex-citation' to insert a citation
22801 into the buffer.
22803 Export of such citations to both LaTeX and HTML is handled by the contributed
22804 package ox-bibtex by Taru Karttunen."
22805 (interactive)
22806 (let ((reftex-docstruct-symbol 'rds)
22807 (reftex-cite-format "\\cite{%l}")
22808 rds bib)
22809 (save-excursion
22810 (save-restriction
22811 (widen)
22812 (let ((case-fold-search t)
22813 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22814 (if (not (save-excursion
22815 (or (re-search-forward re nil t)
22816 (re-search-backward re nil t))))
22817 (error "No bibliography defined in file")
22818 (setq bib (concat (match-string 1) ".bib")
22819 rds (list (list 'bib bib)))))))
22820 (call-interactively 'reftex-citation)))
22822 ;;;; Functions extending outline functionality
22824 (defun org-beginning-of-line (&optional arg)
22825 "Go to the beginning of the current line. If that is invisible, continue
22826 to a visible line beginning. This makes the function of C-a more intuitive.
22827 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22828 first attempt, and only move to after the tags when the cursor is already
22829 beyond the end of the headline."
22830 (interactive "P")
22831 (let ((pos (point))
22832 (special (if (consp org-special-ctrl-a/e)
22833 (car org-special-ctrl-a/e)
22834 org-special-ctrl-a/e))
22835 deactivate-mark refpos)
22836 (if (org-bound-and-true-p visual-line-mode)
22837 (beginning-of-visual-line 1)
22838 (beginning-of-line 1))
22839 (if (and arg (fboundp 'move-beginning-of-line))
22840 (call-interactively 'move-beginning-of-line)
22841 (if (bobp)
22843 (backward-char 1)
22844 (if (org-truely-invisible-p)
22845 (while (and (not (bobp)) (org-truely-invisible-p))
22846 (backward-char 1)
22847 (beginning-of-line 1))
22848 (forward-char 1))))
22849 (when special
22850 (cond
22851 ((and (looking-at org-complex-heading-regexp)
22852 (= (char-after (match-end 1)) ?\ ))
22853 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22854 (point-at-eol)))
22855 (goto-char
22856 (if (eq special t)
22857 (cond ((> pos refpos) refpos)
22858 ((= pos (point)) refpos)
22859 (t (point)))
22860 (cond ((> pos (point)) (point))
22861 ((not (eq last-command this-command)) (point))
22862 (t refpos)))))
22863 ((org-at-item-p)
22864 ;; Being at an item and not looking at an the item means point
22865 ;; was previously moved to beginning of a visual line, which
22866 ;; doesn't contain the item. Therefore, do nothing special,
22867 ;; just stay here.
22868 (when (looking-at org-list-full-item-re)
22869 ;; Set special position at first white space character after
22870 ;; bullet, and check-box, if any.
22871 (let ((after-bullet
22872 (let ((box (match-end 3)))
22873 (if (not box) (match-end 1)
22874 (let ((after (char-after box)))
22875 (if (and after (= after ? )) (1+ box) box))))))
22876 ;; Special case: Move point to special position when
22877 ;; currently after it or at beginning of line.
22878 (if (eq special t)
22879 (when (or (> pos after-bullet) (= (point) pos))
22880 (goto-char after-bullet))
22881 ;; Reversed case: Move point to special position when
22882 ;; point was already at beginning of line and command is
22883 ;; repeated.
22884 (when (and (= (point) pos) (eq last-command this-command))
22885 (goto-char after-bullet))))))))
22886 (org-no-warnings
22887 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22888 (setq disable-point-adjustment
22889 (or (not (invisible-p (point)))
22890 (not (invisible-p (max (point-min) (1- (point))))))))
22892 (defun org-end-of-line (&optional arg)
22893 "Go to the end of the line.
22894 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22895 tags on the first attempt, and only move to after the tags when
22896 the cursor is already beyond the end of the headline."
22897 (interactive "P")
22898 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22899 org-special-ctrl-a/e))
22900 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22901 'end-of-visual-line)
22902 ((fboundp 'move-end-of-line) 'move-end-of-line)
22903 (t 'end-of-line)))
22904 deactivate-mark)
22905 (if (or (not special) arg) (call-interactively move-fun)
22906 (let* ((element (save-excursion (beginning-of-line)
22907 (org-element-at-point)))
22908 (type (org-element-type element)))
22909 (cond
22910 ((memq type '(headline inlinetask))
22911 (let ((pos (point)))
22912 (beginning-of-line 1)
22913 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22914 (if (eq special t)
22915 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22916 (goto-char (match-beginning 1))
22917 (goto-char (match-end 0)))
22918 (if (or (< pos (match-end 0))
22919 (not (eq this-command last-command)))
22920 (goto-char (match-end 0))
22921 (goto-char (match-beginning 1))))
22922 (call-interactively move-fun))))
22923 ((outline-invisible-p (line-end-position))
22924 ;; If element is hidden, `move-end-of-line' would put point
22925 ;; after it. Use `end-of-line' to stay on current line.
22926 (call-interactively 'end-of-line))
22927 (t (call-interactively move-fun)))))
22928 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22929 (setq disable-point-adjustment
22930 (or (not (invisible-p (point)))
22931 (not (invisible-p (max (point-min) (1- (point))))))))
22933 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22934 (define-key org-mode-map "\C-e" 'org-end-of-line)
22936 (defun org-backward-sentence (&optional arg)
22937 "Go to beginning of sentence, or beginning of table field.
22938 This will call `backward-sentence' or `org-table-beginning-of-field',
22939 depending on context."
22940 (interactive "P")
22941 (cond
22942 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22943 (t (call-interactively 'backward-sentence))))
22945 (defun org-forward-sentence (&optional arg)
22946 "Go to end of sentence, or end of table field.
22947 This will call `forward-sentence' or `org-table-end-of-field',
22948 depending on context."
22949 (interactive "P")
22950 (cond
22951 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22952 (t (call-interactively 'forward-sentence))))
22954 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22955 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22957 (defun org-kill-line (&optional arg)
22958 "Kill line, to tags or end of line."
22959 (interactive "P")
22960 (cond
22961 ((or (not org-special-ctrl-k)
22962 (bolp)
22963 (not (org-at-heading-p)))
22964 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22965 org-ctrl-k-protect-subtree)
22966 (if (or (eq org-ctrl-k-protect-subtree 'error)
22967 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22968 (user-error "C-k aborted as it would kill a hidden subtree")))
22969 (call-interactively
22970 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22971 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22972 (kill-region (point) (match-beginning 1))
22973 (org-set-tags nil t))
22974 (t (kill-region (point) (point-at-eol)))))
22976 (define-key org-mode-map "\C-k" 'org-kill-line)
22978 (defun org-yank (&optional arg)
22979 "Yank. If the kill is a subtree, treat it specially.
22980 This command will look at the current kill and check if is a single
22981 subtree, or a series of subtrees[1]. If it passes the test, and if the
22982 cursor is at the beginning of a line or after the stars of a currently
22983 empty headline, then the yank is handled specially. How exactly depends
22984 on the value of the following variables, both set by default.
22986 org-yank-folded-subtrees
22987 When set, the subtree(s) will be folded after insertion, but only
22988 if doing so would now swallow text after the yanked text.
22990 org-yank-adjusted-subtrees
22991 When set, the subtree will be promoted or demoted in order to
22992 fit into the local outline tree structure, which means that the level
22993 will be adjusted so that it becomes the smaller one of the two
22994 *visible* surrounding headings.
22996 Any prefix to this command will cause `yank' to be called directly with
22997 no special treatment. In particular, a simple \\[universal-argument] prefix \
22998 will just
22999 plainly yank the text as it is.
23001 \[1] The test checks if the first non-white line is a heading
23002 and if there are no other headings with fewer stars."
23003 (interactive "P")
23004 (org-yank-generic 'yank arg))
23006 (defun org-yank-generic (command arg)
23007 "Perform some yank-like command.
23009 This function implements the behavior described in the `org-yank'
23010 documentation. However, it has been generalized to work for any
23011 interactive command with similar behavior."
23013 ;; pretend to be command COMMAND
23014 (setq this-command command)
23016 (if arg
23017 (call-interactively command)
23019 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23020 (and (org-kill-is-subtree-p)
23021 (or (bolp)
23022 (and (looking-at "[ \t]*$")
23023 (string-match
23024 "\\`\\*+\\'"
23025 (buffer-substring (point-at-bol) (point)))))))
23026 swallowp)
23027 (cond
23028 ((and subtreep org-yank-folded-subtrees)
23029 (let ((beg (point))
23030 end)
23031 (if (and subtreep org-yank-adjusted-subtrees)
23032 (org-paste-subtree nil nil 'for-yank)
23033 (call-interactively command))
23035 (setq end (point))
23036 (goto-char beg)
23037 (when (and (bolp) subtreep
23038 (not (setq swallowp
23039 (org-yank-folding-would-swallow-text beg end))))
23040 (org-with-limited-levels
23041 (or (looking-at org-outline-regexp)
23042 (re-search-forward org-outline-regexp-bol end t))
23043 (while (and (< (point) end) (looking-at org-outline-regexp))
23044 (hide-subtree)
23045 (org-cycle-show-empty-lines 'folded)
23046 (condition-case nil
23047 (outline-forward-same-level 1)
23048 (error (goto-char end))))))
23049 (when swallowp
23050 (message
23051 "Inserted text not folded because that would swallow text"))
23053 (goto-char end)
23054 (skip-chars-forward " \t\n\r")
23055 (beginning-of-line 1)
23056 (push-mark beg 'nomsg)))
23057 ((and subtreep org-yank-adjusted-subtrees)
23058 (let ((beg (point-at-bol)))
23059 (org-paste-subtree nil nil 'for-yank)
23060 (push-mark beg 'nomsg)))
23062 (call-interactively command))))))
23064 (defun org-yank-folding-would-swallow-text (beg end)
23065 "Would hide-subtree at BEG swallow any text after END?"
23066 (let (level)
23067 (org-with-limited-levels
23068 (save-excursion
23069 (goto-char beg)
23070 (when (or (looking-at org-outline-regexp)
23071 (re-search-forward org-outline-regexp-bol end t))
23072 (setq level (org-outline-level)))
23073 (goto-char end)
23074 (skip-chars-forward " \t\r\n\v\f")
23075 (if (or (eobp)
23076 (and (bolp) (looking-at org-outline-regexp)
23077 (<= (org-outline-level) level)))
23078 nil ; Nothing would be swallowed
23079 t))))) ; something would swallow
23081 (define-key org-mode-map "\C-y" 'org-yank)
23083 (defun org-truely-invisible-p ()
23084 "Check if point is at a character currently not visible.
23085 This version does not only check the character property, but also
23086 `visible-mode'."
23087 ;; Early versions of noutline don't have `outline-invisible-p'.
23088 (if (org-bound-and-true-p visible-mode)
23090 (outline-invisible-p)))
23092 (defun org-invisible-p2 ()
23093 "Check if point is at a character currently not visible."
23094 (save-excursion
23095 (if (and (eolp) (not (bobp))) (backward-char 1))
23096 ;; Early versions of noutline don't have `outline-invisible-p'.
23097 (outline-invisible-p)))
23099 (defun org-back-to-heading (&optional invisible-ok)
23100 "Call `outline-back-to-heading', but provide a better error message."
23101 (condition-case nil
23102 (outline-back-to-heading invisible-ok)
23103 (error (error "Before first headline at position %d in buffer %s"
23104 (point) (current-buffer)))))
23106 (defun org-before-first-heading-p ()
23107 "Before first heading?"
23108 (save-excursion
23109 (end-of-line)
23110 (null (re-search-backward org-outline-regexp-bol nil t))))
23112 (defun org-at-heading-p (&optional ignored)
23113 (outline-on-heading-p t))
23114 ;; Compatibility alias with Org versions < 7.8.03
23115 (defalias 'org-on-heading-p 'org-at-heading-p)
23117 (defun org-at-comment-p nil
23118 "Is cursor in a line starting with a # character?"
23119 (save-excursion
23120 (beginning-of-line)
23121 (looking-at "^#")))
23123 (defun org-at-drawer-p nil
23124 "Is cursor at a drawer keyword?"
23125 (save-excursion
23126 (move-beginning-of-line 1)
23127 (looking-at org-drawer-regexp)))
23129 (defun org-at-block-p nil
23130 "Is cursor at a block keyword?"
23131 (save-excursion
23132 (move-beginning-of-line 1)
23133 (looking-at org-block-regexp)))
23135 (defun org-point-at-end-of-empty-headline ()
23136 "If point is at the end of an empty headline, return t, else nil.
23137 If the heading only contains a TODO keyword, it is still still considered
23138 empty."
23139 (and (looking-at "[ \t]*$")
23140 (when org-todo-line-regexp
23141 (save-excursion
23142 (beginning-of-line 1)
23143 (let ((case-fold-search nil))
23144 (looking-at org-todo-line-regexp)
23145 (string= (match-string 3) ""))))))
23147 (defun org-at-heading-or-item-p ()
23148 (or (org-at-heading-p) (org-at-item-p)))
23150 (defun org-at-target-p ()
23151 (or (org-in-regexp org-radio-target-regexp)
23152 (org-in-regexp org-target-regexp)))
23153 ;; Compatibility alias with Org versions < 7.8.03
23154 (defalias 'org-on-target-p 'org-at-target-p)
23156 (defun org-up-heading-all (arg)
23157 "Move to the heading line of which the present line is a subheading.
23158 This function considers both visible and invisible heading lines.
23159 With argument, move up ARG levels."
23160 (if (fboundp 'outline-up-heading-all)
23161 (outline-up-heading-all arg) ; emacs 21 version of outline.el
23162 (outline-up-heading arg t))) ; emacs 22 version of outline.el
23164 (defun org-up-heading-safe ()
23165 "Move to the heading line of which the present line is a subheading.
23166 This version will not throw an error. It will return the level of the
23167 headline found, or nil if no higher level is found.
23169 Also, this function will be a lot faster than `outline-up-heading',
23170 because it relies on stars being the outline starters. This can really
23171 make a significant difference in outlines with very many siblings."
23172 (let (start-level re)
23173 (org-back-to-heading t)
23174 (setq start-level (funcall outline-level))
23175 (if (equal start-level 1)
23177 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
23178 (if (re-search-backward re nil t)
23179 (funcall outline-level)))))
23181 (defun org-first-sibling-p ()
23182 "Is this heading the first child of its parents?"
23183 (interactive)
23184 (let ((re org-outline-regexp-bol)
23185 level l)
23186 (unless (org-at-heading-p t)
23187 (user-error "Not at a heading"))
23188 (setq level (funcall outline-level))
23189 (save-excursion
23190 (if (not (re-search-backward re nil t))
23192 (setq l (funcall outline-level))
23193 (< l level)))))
23195 (defun org-goto-sibling (&optional previous)
23196 "Goto the next sibling, even if it is invisible.
23197 When PREVIOUS is set, go to the previous sibling instead. Returns t
23198 when a sibling was found. When none is found, return nil and don't
23199 move point."
23200 (let ((fun (if previous 're-search-backward 're-search-forward))
23201 (pos (point))
23202 (re org-outline-regexp-bol)
23203 level l)
23204 (when (condition-case nil (org-back-to-heading t) (error nil))
23205 (setq level (funcall outline-level))
23206 (catch 'exit
23207 (or previous (forward-char 1))
23208 (while (funcall fun re nil t)
23209 (setq l (funcall outline-level))
23210 (when (< l level) (goto-char pos) (throw 'exit nil))
23211 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23212 (goto-char pos)
23213 nil))))
23215 (defun org-show-siblings ()
23216 "Show all siblings of the current headline."
23217 (save-excursion
23218 (while (org-goto-sibling) (org-flag-heading nil)))
23219 (save-excursion
23220 (while (org-goto-sibling 'previous)
23221 (org-flag-heading nil))))
23223 (defun org-goto-first-child ()
23224 "Goto the first child, even if it is invisible.
23225 Return t when a child was found. Otherwise don't move point and
23226 return nil."
23227 (let (level (pos (point)) (re org-outline-regexp-bol))
23228 (when (condition-case nil (org-back-to-heading t) (error nil))
23229 (setq level (outline-level))
23230 (forward-char 1)
23231 (if (and (re-search-forward re nil t) (> (outline-level) level))
23232 (progn (goto-char (match-beginning 0)) t)
23233 (goto-char pos) nil))))
23235 (defun org-show-hidden-entry ()
23236 "Show an entry where even the heading is hidden."
23237 (save-excursion
23238 (org-show-entry)))
23240 (defun org-flag-heading (flag &optional entry)
23241 "Flag the current heading. FLAG non-nil means make invisible.
23242 When ENTRY is non-nil, show the entire entry."
23243 (save-excursion
23244 (org-back-to-heading t)
23245 ;; Check if we should show the entire entry
23246 (if entry
23247 (progn
23248 (org-show-entry)
23249 (save-excursion
23250 (and (outline-next-heading)
23251 (org-flag-heading nil))))
23252 (outline-flag-region (max (point-min) (1- (point)))
23253 (save-excursion (outline-end-of-heading) (point))
23254 flag))))
23256 (defun org-get-next-sibling ()
23257 "Move to next heading of the same level, and return point.
23258 If there is no such heading, return nil.
23259 This is like outline-next-sibling, but invisible headings are ok."
23260 (let ((level (funcall outline-level)))
23261 (outline-next-heading)
23262 (while (and (not (eobp)) (> (funcall outline-level) level))
23263 (outline-next-heading))
23264 (if (or (eobp) (< (funcall outline-level) level))
23266 (point))))
23268 (defun org-get-last-sibling ()
23269 "Move to previous heading of the same level, and return point.
23270 If there is no such heading, return nil."
23271 (let ((opoint (point))
23272 (level (funcall outline-level)))
23273 (outline-previous-heading)
23274 (when (and (/= (point) opoint) (outline-on-heading-p t))
23275 (while (and (> (funcall outline-level) level)
23276 (not (bobp)))
23277 (outline-previous-heading))
23278 (if (< (funcall outline-level) level)
23280 (point)))))
23282 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23283 "Goto to the end of a subtree."
23284 ;; This contains an exact copy of the original function, but it uses
23285 ;; `org-back-to-heading', to make it work also in invisible
23286 ;; trees. And is uses an invisible-ok argument.
23287 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23288 ;; Furthermore, when used inside Org, finding the end of a large subtree
23289 ;; with many children and grandchildren etc, this can be much faster
23290 ;; than the outline version.
23291 (org-back-to-heading invisible-ok)
23292 (let ((first t)
23293 (level (funcall outline-level)))
23294 (if (and (derived-mode-p 'org-mode) (< level 1000))
23295 ;; A true heading (not a plain list item), in Org-mode
23296 ;; This means we can easily find the end by looking
23297 ;; only for the right number of stars. Using a regexp to do
23298 ;; this is so much faster than using a Lisp loop.
23299 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23300 (forward-char 1)
23301 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23302 ;; something else, do it the slow way
23303 (while (and (not (eobp))
23304 (or first (> (funcall outline-level) level)))
23305 (setq first nil)
23306 (outline-next-heading)))
23307 (unless to-heading
23308 (if (memq (preceding-char) '(?\n ?\^M))
23309 (progn
23310 ;; Go to end of line before heading
23311 (forward-char -1)
23312 (if (memq (preceding-char) '(?\n ?\^M))
23313 ;; leave blank line before heading
23314 (forward-char -1))))))
23315 (point))
23317 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
23318 "Use Org version in org-mode, for dramatic speed-up."
23319 (if (derived-mode-p 'org-mode)
23320 (progn
23321 (org-end-of-subtree nil t)
23322 (unless (eobp) (backward-char 1)))
23323 ad-do-it))
23325 (defun org-end-of-meta-data-and-drawers ()
23326 "Jump to the first text after meta data and drawers in the current entry.
23327 This will move over empty lines, lines with planning time stamps,
23328 clocking lines, and drawers."
23329 (org-back-to-heading t)
23330 (let ((end (save-excursion (outline-next-heading) (point)))
23331 (re (concat "\\(" org-drawer-regexp "\\)"
23332 "\\|" "[ \t]*" org-keyword-time-regexp)))
23333 (forward-line 1)
23334 (while (re-search-forward re end t)
23335 (if (not (match-end 1))
23336 ;; empty or planning line
23337 (forward-line 1)
23338 ;; a drawer, find the end
23339 (re-search-forward "^[ \t]*:END:" end 'move)
23340 (forward-line 1)))
23341 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23342 (point)))
23344 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23345 "Move forward to the ARG'th subheading at same level as this one.
23346 Stop at the first and last subheadings of a superior heading.
23347 Normally this only looks at visible headings, but when INVISIBLE-OK is
23348 non-nil it will also look at invisible ones."
23349 (interactive "p")
23350 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23351 (if (and arg (< arg 0))
23352 (goto-char (point-min))
23353 (outline-next-heading))
23354 (org-at-heading-p)
23355 (let ((level (- (match-end 0) (match-beginning 0) 1))
23356 (f (if (and arg (< arg 0))
23357 're-search-backward
23358 're-search-forward))
23359 (count (if arg (abs arg) 1))
23360 (result (point)))
23361 (while (and (prog1 (> count 0)
23362 (forward-char (if (and arg (< arg 0)) -1 1)))
23363 (funcall f org-outline-regexp-bol nil 'move))
23364 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23365 (cond ((< l level) (setq count 0))
23366 ((and (= l level)
23367 (or invisible-ok
23368 (progn
23369 (goto-char (line-beginning-position))
23370 (not (outline-invisible-p)))))
23371 (setq count (1- count))
23372 (when (eq l level)
23373 (setq result (point)))))))
23374 (goto-char result))
23375 (beginning-of-line 1)))
23377 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23378 "Move backward to the ARG'th subheading at same level as this one.
23379 Stop at the first and last subheadings of a superior heading."
23380 (interactive "p")
23381 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23383 (defun org-next-block (arg &optional backward block-regexp)
23384 "Jump to the next block.
23385 With a prefix argument ARG, jump forward ARG many source blocks.
23386 When BACKWARD is non-nil, jump to the previous block.
23387 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23388 (interactive "p")
23389 (let ((re (or block-regexp org-block-regexp))
23390 (re-search-fn (or (and backward 're-search-backward)
23391 're-search-forward)))
23392 (if (looking-at re) (forward-char 1))
23393 (condition-case nil
23394 (funcall re-search-fn re nil nil arg)
23395 (error (error "No %s code blocks" (if backward "previous" "further" ))))
23396 (goto-char (match-beginning 0)) (org-show-context)))
23398 (defun org-previous-block (arg &optional block-regexp)
23399 "Jump to the previous block.
23400 With a prefix argument ARG, jump backward ARG many source blocks.
23401 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23402 (interactive "p")
23403 (org-next-block arg t block-regexp))
23405 (defun org-forward-paragraph ()
23406 "Move forward to beginning of next paragraph or equivalent.
23408 The function moves point to the beginning of the next visible
23409 structural element, which can be a paragraph, a table, a list
23410 item, etc. It also provides some special moves for convenience:
23412 - On an affiliated keyword, jump to the beginning of the
23413 relative element.
23414 - On an item or a footnote definition, move to the second
23415 element inside, if any.
23416 - On a table or a property drawer, jump after it.
23417 - On a verse or source block, stop after blank lines."
23418 (interactive)
23419 (when (eobp) (user-error "Cannot move further down"))
23420 (let* ((deactivate-mark nil)
23421 (element (org-element-at-point))
23422 (type (org-element-type element))
23423 (post-affiliated (org-element-property :post-affiliated element))
23424 (contents-begin (org-element-property :contents-begin element))
23425 (contents-end (org-element-property :contents-end element))
23426 (end (let ((end (org-element-property :end element)) (parent element))
23427 (while (and (setq parent (org-element-property :parent parent))
23428 (= (org-element-property :contents-end parent) end))
23429 (setq end (org-element-property :end parent)))
23430 end)))
23431 (cond ((not element)
23432 (skip-chars-forward " \r\t\n")
23433 (or (eobp) (beginning-of-line)))
23434 ;; On affiliated keywords, move to element's beginning.
23435 ((and post-affiliated (< (point) post-affiliated))
23436 (goto-char post-affiliated))
23437 ;; At a table row, move to the end of the table. Similarly,
23438 ;; at a node property, move to the end of the property
23439 ;; drawer.
23440 ((memq type '(node-property table-row))
23441 (goto-char (org-element-property
23442 :end (org-element-property :parent element))))
23443 ((memq type '(property-drawer table)) (goto-char end))
23444 ;; Consider blank lines as separators in verse and source
23445 ;; blocks to ease editing.
23446 ((memq type '(src-block verse-block))
23447 (when (eq type 'src-block)
23448 (setq contents-end
23449 (save-excursion (goto-char end)
23450 (skip-chars-backward " \r\t\n")
23451 (line-beginning-position))))
23452 (beginning-of-line)
23453 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23454 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23455 (goto-char end)
23456 (skip-chars-forward " \r\t\n")
23457 (if (= (point) contents-end) (goto-char end)
23458 (beginning-of-line))))
23459 ;; With no contents, just skip element.
23460 ((not contents-begin) (goto-char end))
23461 ;; If contents are invisible, skip the element altogether.
23462 ((outline-invisible-p (line-end-position))
23463 (case type
23464 (headline
23465 (org-with-limited-levels (outline-next-visible-heading 1)))
23466 ;; At a plain list, make sure we move to the next item
23467 ;; instead of skipping the whole list.
23468 (plain-list (forward-char)
23469 (org-forward-paragraph))
23470 (otherwise (goto-char end))))
23471 ((>= (point) contents-end) (goto-char end))
23472 ((>= (point) contents-begin)
23473 ;; This can only happen on paragraphs and plain lists.
23474 (case type
23475 (paragraph (goto-char end))
23476 ;; At a plain list, try to move to second element in
23477 ;; first item, if possible.
23478 (plain-list (end-of-line)
23479 (org-forward-paragraph))))
23480 ;; When contents start on the middle of a line (e.g. in
23481 ;; items and footnote definitions), try to reach first
23482 ;; element starting after current line.
23483 ((> (line-end-position) contents-begin)
23484 (end-of-line)
23485 (org-forward-paragraph))
23486 (t (goto-char contents-begin)))))
23488 (defun org-backward-paragraph ()
23489 "Move backward to start of previous paragraph or equivalent.
23491 The function moves point to the beginning of the current
23492 structural element, which can be a paragraph, a table, a list
23493 item, etc., or to the beginning of the previous visible one if
23494 point is already there. It also provides some special moves for
23495 convenience:
23497 - On an affiliated keyword, jump to the first one.
23498 - On a table or a property drawer, move to its beginning.
23499 - On a verse or source block, stop before blank lines."
23500 (interactive)
23501 (when (bobp) (user-error "Cannot move further up"))
23502 (let* ((deactivate-mark nil)
23503 (element (org-element-at-point))
23504 (type (org-element-type element))
23505 (contents-begin (org-element-property :contents-begin element))
23506 (contents-end (org-element-property :contents-end element))
23507 (post-affiliated (org-element-property :post-affiliated element))
23508 (begin (org-element-property :begin element)))
23509 (cond
23510 ((not element) (goto-char (point-min)))
23511 ((= (point) begin)
23512 (backward-char)
23513 (org-backward-paragraph))
23514 ((and post-affiliated (<= (point) post-affiliated)) (goto-char begin))
23515 ((memq type '(node-property table-row))
23516 (goto-char (org-element-property
23517 :post-affiliated (org-element-property :parent element))))
23518 ((memq type '(property-drawer table)) (goto-char begin))
23519 ((memq type '(src-block verse-block))
23520 (when (eq type 'src-block)
23521 (setq contents-begin
23522 (save-excursion (goto-char begin) (forward-line) (point))))
23523 (if (= (point) contents-begin) (goto-char post-affiliated)
23524 ;; Inside a verse block, see blank lines as paragraph
23525 ;; separators.
23526 (let ((origin (point)))
23527 (skip-chars-backward " \r\t\n" contents-begin)
23528 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
23529 (skip-chars-forward " \r\t\n" origin)
23530 (if (= (point) origin) (goto-char contents-begin)
23531 (beginning-of-line))))))
23532 ((not contents-begin) (goto-char (or post-affiliated begin)))
23533 ((eq type 'paragraph)
23534 (goto-char contents-begin)
23535 ;; When at first paragraph in an item or a footnote definition,
23536 ;; move directly to beginning of line.
23537 (let ((parent-contents
23538 (org-element-property
23539 :contents-begin (org-element-property :parent element))))
23540 (when (and parent-contents (= parent-contents contents-begin))
23541 (beginning-of-line))))
23542 ;; At the end of a greater element, move to the beginning of the
23543 ;; last element within.
23544 ((>= (point) contents-end)
23545 (goto-char (1- contents-end))
23546 (org-backward-paragraph))
23547 (t (goto-char (or post-affiliated begin))))
23548 ;; Ensure we never leave point invisible.
23549 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
23551 (defun org-forward-element ()
23552 "Move forward by one element.
23553 Move to the next element at the same level, when possible."
23554 (interactive)
23555 (cond ((eobp) (user-error "Cannot move further down"))
23556 ((org-with-limited-levels (org-at-heading-p))
23557 (let ((origin (point)))
23558 (goto-char (org-end-of-subtree nil t))
23559 (unless (org-with-limited-levels (org-at-heading-p))
23560 (goto-char origin)
23561 (user-error "Cannot move further down"))))
23563 (let* ((elem (org-element-at-point))
23564 (end (org-element-property :end elem))
23565 (parent (org-element-property :parent elem)))
23566 (cond ((and parent (= (org-element-property :contents-end parent) end))
23567 (goto-char (org-element-property :end parent)))
23568 ((integer-or-marker-p end) (goto-char end))
23569 (t (message "No element at point")))))))
23571 (defun org-backward-element ()
23572 "Move backward by one element.
23573 Move to the previous element at the same level, when possible."
23574 (interactive)
23575 (cond ((bobp) (user-error "Cannot move further up"))
23576 ((org-with-limited-levels (org-at-heading-p))
23577 ;; At a headline, move to the previous one, if any, or stay
23578 ;; here.
23579 (let ((origin (point)))
23580 (org-with-limited-levels (org-backward-heading-same-level 1))
23581 ;; When current headline has no sibling above, move to its
23582 ;; parent.
23583 (when (= (point) origin)
23584 (or (org-with-limited-levels (org-up-heading-safe))
23585 (progn (goto-char origin)
23586 (user-error "Cannot move further up"))))))
23588 (let* ((trail (org-element-at-point 'keep-trail))
23589 (elem (car trail))
23590 (prev-elem (nth 1 trail))
23591 (beg (org-element-property :begin elem)))
23592 (cond
23593 ;; Move to beginning of current element if point isn't
23594 ;; there already.
23595 ((null beg) (message "No element at point"))
23596 ((/= (point) beg) (goto-char beg))
23597 (prev-elem (goto-char (org-element-property :begin prev-elem)))
23598 ((org-before-first-heading-p) (goto-char (point-min)))
23599 (t (org-back-to-heading)))))))
23601 (defun org-up-element ()
23602 "Move to upper element."
23603 (interactive)
23604 (if (org-with-limited-levels (org-at-heading-p))
23605 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23606 (let* ((elem (org-element-at-point))
23607 (parent (org-element-property :parent elem)))
23608 (if parent (goto-char (org-element-property :begin parent))
23609 (if (org-with-limited-levels (org-before-first-heading-p))
23610 (user-error "No surrounding element")
23611 (org-with-limited-levels (org-back-to-heading)))))))
23613 (defvar org-element-greater-elements)
23614 (defun org-down-element ()
23615 "Move to inner element."
23616 (interactive)
23617 (let ((element (org-element-at-point)))
23618 (cond
23619 ((memq (org-element-type element) '(plain-list table))
23620 (goto-char (org-element-property :contents-begin element))
23621 (forward-char))
23622 ((memq (org-element-type element) org-element-greater-elements)
23623 ;; If contents are hidden, first disclose them.
23624 (when (outline-invisible-p (line-end-position)) (org-cycle))
23625 (goto-char (or (org-element-property :contents-begin element)
23626 (user-error "No content for this element"))))
23627 (t (user-error "No inner element")))))
23629 (defun org-drag-element-backward ()
23630 "Move backward element at point."
23631 (interactive)
23632 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
23633 (let* ((trail (org-element-at-point 'keep-trail))
23634 (elem (car trail))
23635 (prev-elem (nth 1 trail)))
23636 ;; Error out if no previous element or previous element is
23637 ;; a parent of the current one.
23638 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23639 (user-error "Cannot drag element backward")
23640 (let ((pos (point)))
23641 (org-element-swap-A-B prev-elem elem)
23642 (goto-char (+ (org-element-property :begin prev-elem)
23643 (- pos (org-element-property :begin elem)))))))))
23645 (defun org-drag-element-forward ()
23646 "Move forward element at point."
23647 (interactive)
23648 (let* ((pos (point))
23649 (elem (org-element-at-point)))
23650 (when (= (point-max) (org-element-property :end elem))
23651 (user-error "Cannot drag element forward"))
23652 (goto-char (org-element-property :end elem))
23653 (let ((next-elem (org-element-at-point)))
23654 (when (or (org-element-nested-p elem next-elem)
23655 (and (eq (org-element-type next-elem) 'headline)
23656 (not (eq (org-element-type elem) 'headline))))
23657 (goto-char pos)
23658 (user-error "Cannot drag element forward"))
23659 ;; Compute new position of point: it's shifted by NEXT-ELEM
23660 ;; body's length (without final blanks) and by the length of
23661 ;; blanks between ELEM and NEXT-ELEM.
23662 (let ((size-next (- (save-excursion
23663 (goto-char (org-element-property :end next-elem))
23664 (skip-chars-backward " \r\t\n")
23665 (forward-line)
23666 ;; Small correction if buffer doesn't end
23667 ;; with a newline character.
23668 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23669 (org-element-property :begin next-elem)))
23670 (size-blank (- (org-element-property :end elem)
23671 (save-excursion
23672 (goto-char (org-element-property :end elem))
23673 (skip-chars-backward " \r\t\n")
23674 (forward-line)
23675 (point)))))
23676 (org-element-swap-A-B elem next-elem)
23677 (goto-char (+ pos size-next size-blank))))))
23679 (defun org-drag-line-forward (arg)
23680 "Drag the line at point ARG lines forward."
23681 (interactive "p")
23682 (dotimes (n (abs arg))
23683 (let ((c (current-column)))
23684 (if (< 0 arg)
23685 (progn
23686 (beginning-of-line 2)
23687 (transpose-lines 1)
23688 (beginning-of-line 0))
23689 (transpose-lines 1)
23690 (beginning-of-line -1))
23691 (org-move-to-column c))))
23693 (defun org-drag-line-backward (arg)
23694 "Drag the line at point ARG lines backward."
23695 (interactive "p")
23696 (org-drag-line-forward (- arg)))
23698 (defun org-mark-element ()
23699 "Put point at beginning of this element, mark at end.
23701 Interactively, if this command is repeated or (in Transient Mark
23702 mode) if the mark is active, it marks the next element after the
23703 ones already marked."
23704 (interactive)
23705 (let (deactivate-mark)
23706 (if (and (org-called-interactively-p 'any)
23707 (or (and (eq last-command this-command) (mark t))
23708 (and transient-mark-mode mark-active)))
23709 (set-mark
23710 (save-excursion
23711 (goto-char (mark))
23712 (goto-char (org-element-property :end (org-element-at-point)))))
23713 (let ((element (org-element-at-point)))
23714 (end-of-line)
23715 (push-mark (org-element-property :end element) t t)
23716 (goto-char (org-element-property :begin element))))))
23718 (defun org-narrow-to-element ()
23719 "Narrow buffer to current element."
23720 (interactive)
23721 (let ((elem (org-element-at-point)))
23722 (cond
23723 ((eq (car elem) 'headline)
23724 (narrow-to-region
23725 (org-element-property :begin elem)
23726 (org-element-property :end elem)))
23727 ((memq (car elem) org-element-greater-elements)
23728 (narrow-to-region
23729 (org-element-property :contents-begin elem)
23730 (org-element-property :contents-end elem)))
23732 (narrow-to-region
23733 (org-element-property :begin elem)
23734 (org-element-property :end elem))))))
23736 (defun org-transpose-element ()
23737 "Transpose current and previous elements, keeping blank lines between.
23738 Point is moved after both elements."
23739 (interactive)
23740 (org-skip-whitespace)
23741 (let ((end (org-element-property :end (org-element-at-point))))
23742 (org-drag-element-backward)
23743 (goto-char end)))
23745 (defun org-unindent-buffer ()
23746 "Un-indent the visible part of the buffer.
23747 Relative indentation (between items, inside blocks, etc.) isn't
23748 modified."
23749 (interactive)
23750 (unless (eq major-mode 'org-mode)
23751 (user-error "Cannot un-indent a buffer not in Org mode"))
23752 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23753 unindent-tree ; For byte-compiler.
23754 (unindent-tree
23755 (function
23756 (lambda (contents)
23757 (mapc
23758 (lambda (element)
23759 (if (memq (org-element-type element) '(headline section))
23760 (funcall unindent-tree (org-element-contents element))
23761 (save-excursion
23762 (save-restriction
23763 (narrow-to-region
23764 (org-element-property :begin element)
23765 (org-element-property :end element))
23766 (org-do-remove-indentation)))))
23767 (reverse contents))))))
23768 (funcall unindent-tree (org-element-contents parse-tree))))
23770 (defun org-show-subtree ()
23771 "Show everything after this heading at deeper levels."
23772 (interactive)
23773 (outline-flag-region
23774 (point)
23775 (save-excursion
23776 (org-end-of-subtree t t))
23777 nil))
23779 (defun org-show-entry ()
23780 "Show the body directly following this heading.
23781 Show the heading too, if it is currently invisible."
23782 (interactive)
23783 (save-excursion
23784 (condition-case nil
23785 (progn
23786 (org-back-to-heading t)
23787 (outline-flag-region
23788 (max (point-min) (1- (point)))
23789 (save-excursion
23790 (if (re-search-forward
23791 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23792 (match-beginning 1)
23793 (point-max)))
23794 nil)
23795 (org-cycle-hide-drawers 'children))
23796 (error nil))))
23798 (defun org-make-options-regexp (kwds &optional extra)
23799 "Make a regular expression for keyword lines."
23800 (concat
23801 "^#\\+\\("
23802 (mapconcat 'regexp-quote kwds "\\|")
23803 (if extra (concat "\\|" extra))
23804 "\\):[ \t]*\\(.*\\)"))
23806 ;; Make isearch reveal the necessary context
23807 (defun org-isearch-end ()
23808 "Reveal context after isearch exits."
23809 (when isearch-success ; only if search was successful
23810 (if (featurep 'xemacs)
23811 ;; Under XEmacs, the hook is run in the correct place,
23812 ;; we directly show the context.
23813 (org-show-context 'isearch)
23814 ;; In Emacs the hook runs *before* restoring the overlays.
23815 ;; So we have to use a one-time post-command-hook to do this.
23816 ;; (Emacs 22 has a special variable, see function `org-mode')
23817 (unless (and (boundp 'isearch-mode-end-hook-quit)
23818 isearch-mode-end-hook-quit)
23819 ;; Only when the isearch was not quitted.
23820 (org-add-hook 'post-command-hook 'org-isearch-post-command
23821 'append 'local)))
23822 (org-fix-ellipsis-at-bol)))
23824 (defun org-isearch-post-command ()
23825 "Remove self from hook, and show context."
23826 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23827 (org-show-context 'isearch))
23830 ;;;; Integration with and fixes for other packages
23832 ;;; Imenu support
23834 (defvar org-imenu-markers nil
23835 "All markers currently used by Imenu.")
23836 (make-variable-buffer-local 'org-imenu-markers)
23838 (defun org-imenu-new-marker (&optional pos)
23839 "Return a new marker for use by Imenu, and remember the marker."
23840 (let ((m (make-marker)))
23841 (move-marker m (or pos (point)))
23842 (push m org-imenu-markers)
23845 (defun org-imenu-get-tree ()
23846 "Produce the index for Imenu."
23847 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23848 (setq org-imenu-markers nil)
23849 (let* ((n org-imenu-depth)
23850 (re (concat "^" (org-get-limited-outline-regexp)))
23851 (subs (make-vector (1+ n) nil))
23852 (last-level 0)
23853 m level head0 head)
23854 (save-excursion
23855 (save-restriction
23856 (widen)
23857 (goto-char (point-max))
23858 (while (re-search-backward re nil t)
23859 (setq level (org-reduced-level (funcall outline-level)))
23860 (when (and (<= level n)
23861 (looking-at org-complex-heading-regexp)
23862 (setq head0 (org-match-string-no-properties 4)))
23863 (setq head (org-link-display-format head0)
23864 m (org-imenu-new-marker))
23865 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23866 (if (>= level last-level)
23867 (push (cons head m) (aref subs level))
23868 (push (cons head (aref subs (1+ level))) (aref subs level))
23869 (loop for i from (1+ level) to n do (aset subs i nil)))
23870 (setq last-level level)))))
23871 (aref subs 1)))
23873 (eval-after-load "imenu"
23874 '(progn
23875 (add-hook 'imenu-after-jump-hook
23876 (lambda ()
23877 (if (derived-mode-p 'org-mode)
23878 (org-show-context 'org-goto))))))
23880 (defun org-link-display-format (link)
23881 "Replace a link with its the description.
23882 If there is no description, use the link target."
23883 (save-match-data
23884 (if (string-match org-bracket-link-analytic-regexp link)
23885 (replace-match (if (match-end 5)
23886 (match-string 5 link)
23887 (concat (match-string 1 link)
23888 (match-string 3 link)))
23889 nil t link)
23890 link)))
23892 (defun org-toggle-link-display ()
23893 "Toggle the literal or descriptive display of links."
23894 (interactive)
23895 (if org-descriptive-links
23896 (progn (org-remove-from-invisibility-spec '(org-link))
23897 (org-restart-font-lock)
23898 (setq org-descriptive-links nil))
23899 (progn (add-to-invisibility-spec '(org-link))
23900 (org-restart-font-lock)
23901 (setq org-descriptive-links t))))
23903 ;; Speedbar support
23905 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23906 "Overlay marking the agenda restriction line in speedbar.")
23907 (overlay-put org-speedbar-restriction-lock-overlay
23908 'face 'org-agenda-restriction-lock)
23909 (overlay-put org-speedbar-restriction-lock-overlay
23910 'help-echo "Agendas are currently limited to this item.")
23911 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23913 (defun org-speedbar-set-agenda-restriction ()
23914 "Restrict future agenda commands to the location at point in speedbar.
23915 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23916 (interactive)
23917 (require 'org-agenda)
23918 (let (p m tp np dir txt)
23919 (cond
23920 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23921 'org-imenu t))
23922 (setq m (get-text-property p 'org-imenu-marker))
23923 (with-current-buffer (marker-buffer m)
23924 (goto-char m)
23925 (org-agenda-set-restriction-lock 'subtree)))
23926 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23927 'speedbar-function 'speedbar-find-file))
23928 (setq tp (previous-single-property-change
23929 (1+ p) 'speedbar-function)
23930 np (next-single-property-change
23931 tp 'speedbar-function)
23932 dir (speedbar-line-directory)
23933 txt (buffer-substring-no-properties (or tp (point-min))
23934 (or np (point-max))))
23935 (with-current-buffer (find-file-noselect
23936 (let ((default-directory dir))
23937 (expand-file-name txt)))
23938 (unless (derived-mode-p 'org-mode)
23939 (user-error "Cannot restrict to non-Org-mode file"))
23940 (org-agenda-set-restriction-lock 'file)))
23941 (t (user-error "Don't know how to restrict Org-mode's agenda")))
23942 (move-overlay org-speedbar-restriction-lock-overlay
23943 (point-at-bol) (point-at-eol))
23944 (setq current-prefix-arg nil)
23945 (org-agenda-maybe-redo)))
23947 (defvar speedbar-file-key-map)
23948 (declare-function speedbar-add-supported-extension "speedbar" (extension))
23949 (eval-after-load "speedbar"
23950 '(progn
23951 (speedbar-add-supported-extension ".org")
23952 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23953 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23954 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23955 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23956 (add-hook 'speedbar-visiting-tag-hook
23957 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23959 ;;; Fixes and Hacks for problems with other packages
23961 ;; Make flyspell not check words in links, to not mess up our keymap
23962 (defvar org-element-affiliated-keywords) ; From org-element.el
23963 (defvar org-element-block-name-alist) ; From org-element.el
23964 (defun org-mode-flyspell-verify ()
23965 "Don't let flyspell put overlays at active buttons, or on
23966 {todo,all-time,additional-option-like}-keywords."
23967 (require 'org-element) ; For `org-element-affiliated-keywords'
23968 (let ((pos (max (1- (point)) (point-min)))
23969 (word (thing-at-point 'word)))
23970 (and (not (get-text-property pos 'keymap))
23971 (not (get-text-property pos 'org-no-flyspell))
23972 (not (member word org-todo-keywords-1))
23973 (not (member word org-all-time-keywords))
23974 (not (member word org-options-keywords))
23975 (not (member word (mapcar 'car org-startup-options)))
23976 (not (member-ignore-case word org-element-affiliated-keywords))
23977 (not (member-ignore-case word (org-get-export-keywords)))
23978 (not (member-ignore-case
23979 word (mapcar 'car org-element-block-name-alist)))
23980 (not (member-ignore-case word '("BEGIN" "END" "ATTR")))
23981 (not (org-in-src-block-p)))))
23983 (defun org-remove-flyspell-overlays-in (beg end)
23984 "Remove flyspell overlays in region."
23985 (and (org-bound-and-true-p flyspell-mode)
23986 (fboundp 'flyspell-delete-region-overlays)
23987 (flyspell-delete-region-overlays beg end))
23988 (add-text-properties beg end '(org-no-flyspell t)))
23990 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23991 (eval-after-load "bookmark"
23992 '(if (boundp 'bookmark-after-jump-hook)
23993 ;; We can use the hook
23994 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23995 ;; Hook not available, use advice
23996 (defadvice bookmark-jump (after org-make-visible activate)
23997 "Make the position visible."
23998 (org-bookmark-jump-unhide))))
24000 ;; Make sure saveplace shows the location if it was hidden
24001 (eval-after-load "saveplace"
24002 '(defadvice save-place-find-file-hook (after org-make-visible activate)
24003 "Make the position visible."
24004 (org-bookmark-jump-unhide)))
24006 ;; Make sure ecb shows the location if it was hidden
24007 (eval-after-load "ecb"
24008 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
24009 "Make hierarchy visible when jumping into location from ECB tree buffer."
24010 (if (derived-mode-p 'org-mode)
24011 (org-show-context))))
24013 (defun org-bookmark-jump-unhide ()
24014 "Unhide the current position, to show the bookmark location."
24015 (and (derived-mode-p 'org-mode)
24016 (or (outline-invisible-p)
24017 (save-excursion (goto-char (max (point-min) (1- (point))))
24018 (outline-invisible-p)))
24019 (org-show-context 'bookmark-jump)))
24021 ;; Make session.el ignore our circular variable
24022 (defvar session-globals-exclude)
24023 (eval-after-load "session"
24024 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24026 ;;;; Finish up
24028 (provide 'org)
24030 (run-hooks 'org-load-hook)
24032 ;;; org.el ends here