Don't use the org-warning face for the wrong install warning
[org-mode.git] / lisp / org.el
blob228e46cd4cefcfc637ef5cc78d561336de6c66f0
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2014 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
29 ;; project planning with a fast and effective plain-text system.
31 ;; Org-mode develops organizational tasks around NOTES files that contain
32 ;; information about projects as plain text. Org-mode is implemented on
33 ;; top of outline-mode, which makes it possible to keep the content of
34 ;; large files well structured. Visibility cycling and structure editing
35 ;; help to work with the tree. Tables are easily created with a built-in
36 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
37 ;; and scheduling. It dynamically compiles entries into an agenda that
38 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
39 ;; Plain text URL-like links connect to websites, emails, Usenet
40 ;; messages, BBDB entries, and any files related to the projects. For
41 ;; printing and sharing of notes, an Org-mode file can be exported as a
42 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
43 ;; iCalendar file. It can also serve as a publishing tool for a set of
44 ;; linked webpages.
46 ;; Installation and Activation
47 ;; ---------------------------
48 ;; See the corresponding sections in the manual at
50 ;; http://orgmode.org/org.html#Installation
52 ;; Documentation
53 ;; -------------
54 ;; The documentation of Org-mode can be found in the TeXInfo file. The
55 ;; distribution also contains a PDF version of it. At the homepage of
56 ;; Org-mode, you can read the same text online as HTML. There is also an
57 ;; excellent reference card made by Philip Rooke. This card can be found
58 ;; in the etc/ directory of Emacs 22.
60 ;; A list of recent changes can be found at
61 ;; http://orgmode.org/Changes.html
63 ;;; Code:
65 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
66 (defvar org-table-formula-constants-local nil
67 "Local version of `org-table-formula-constants'.")
68 (make-variable-buffer-local 'org-table-formula-constants-local)
70 ;;;; Require other packages
72 (eval-when-compile
73 (require 'cl)
74 (require 'gnus-sum))
76 (require 'calendar)
77 (require 'find-func)
78 (require 'format-spec)
80 (or (equal this-command 'eval-buffer)
81 (condition-case nil
82 (load (concat (file-name-directory load-file-name)
83 "org-loaddefs.el")
84 nil t t t)
85 (error
86 (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
87 (sit-for 3)
88 (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
89 (sit-for 3))))
91 (require 'org-macs)
92 (require 'org-compat)
94 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
95 ;; some places -- e.g. see the macro `org-with-limited-levels'.
97 ;; In Org buffers, the value of `outline-regexp' is that of
98 ;; `org-outline-regexp'. The only function still directly relying on
99 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
100 ;; job when `orgstruct-mode' is active.
101 (defvar org-outline-regexp "\\*+ "
102 "Regexp to match Org headlines.")
104 (defvar org-outline-regexp-bol "^\\*+ "
105 "Regexp to match Org headlines.
106 This is similar to `org-outline-regexp' but additionally makes
107 sure that we are at the beginning of the line.")
109 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
110 "Matches a headline, putting stars and text into groups.
111 Stars are put in group 1 and the trimmed body in group 2.")
113 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
114 (unless (boundp 'calendar-view-holidays-initially-flag)
115 (org-defvaralias 'calendar-view-holidays-initially-flag
116 'view-calendar-holidays-initially))
117 (unless (boundp 'calendar-view-diary-initially-flag)
118 (org-defvaralias 'calendar-view-diary-initially-flag
119 'view-diary-entries-initially))
120 (unless (boundp 'diary-fancy-buffer)
121 (org-defvaralias 'diary-fancy-buffer 'fancy-diary-buffer))
123 (declare-function org-add-archive-files "org-archive" (files))
125 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
126 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
127 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
128 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
129 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
130 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
131 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
132 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
133 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
134 (declare-function org-clock-update-time-maybe "org-clock" ())
135 (declare-function org-clocktable-shift "org-clock" (dir n))
137 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
138 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body))
139 (declare-function orgtbl-mode "org-table" (&optional arg))
140 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
141 (declare-function org-beamer-mode "ox-beamer" ())
142 (declare-function org-table-blank-field "org-table" ())
143 (declare-function org-table-edit-field "org-table" (arg))
144 (declare-function org-table-insert-row "org-table" (&optional arg))
145 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
146 (declare-function org-table-set-constants "org-table" ())
147 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
148 (declare-function org-id-get-create "org-id" (&optional force))
149 (declare-function org-add-archive-files "org-archive" (files))
150 (declare-function org-id-find-id-file "org-id" (id))
151 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
152 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
153 (declare-function org-agenda-redo "org-agenda" (&optional all))
154 (declare-function org-table-align "org-table" ())
155 (declare-function org-table-begin "org-table" (&optional table-type))
156 (declare-function org-table-blank-field "org-table" ())
157 (declare-function org-table-end "org-table" (&optional table-type))
158 (declare-function org-table-insert-row "org-table" (&optional arg))
159 (declare-function org-table-paste-rectangle "org-table" ())
160 (declare-function org-table-maybe-eval-formula "org-table" ())
161 (declare-function org-table-maybe-recalculate-line "org-table" ())
163 (declare-function org-element--parse-objects "org-element"
164 (beg end acc restriction))
165 (declare-function org-element-at-point "org-element" ())
166 (declare-function org-element-cache-reset "org-element" (&optional all))
167 (declare-function org-element-contents "org-element" (element))
168 (declare-function org-element-context "org-element" (&optional element))
169 (declare-function org-element-interpret-data "org-element"
170 (data &optional parent))
171 (declare-function org-element-map "org-element"
172 (data types fun &optional info first-match no-recursion))
173 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
174 (declare-function org-element-parse-buffer "org-element"
175 (&optional granularity visible-only))
176 (declare-function org-element-property "org-element" (property element))
177 (declare-function org-element-put-property "org-element"
178 (element property value))
179 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
180 (declare-function org-element--parse-objects "org-element"
181 (beg end acc restriction))
182 (declare-function org-element-parse-buffer "org-element"
183 (&optional granularity visible-only))
184 (declare-function org-element-restriction "org-element" (element))
185 (declare-function org-element-type "org-element" (element))
187 (defsubst org-uniquify (list)
188 "Non-destructively remove duplicate elements from LIST."
189 (let ((res (copy-sequence list))) (delete-dups res)))
191 (defsubst org-get-at-bol (property)
192 "Get text property PROPERTY at the beginning of line."
193 (get-text-property (point-at-bol) property))
195 (defsubst org-trim (s)
196 "Remove whitespace at the beginning and the end of string S."
197 (replace-regexp-in-string
198 "\\`[ \t\n\r]+" ""
199 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
201 ;; load languages based on value of `org-babel-load-languages'
202 (defvar org-babel-load-languages)
204 ;;;###autoload
205 (defun org-babel-do-load-languages (sym value)
206 "Load the languages defined in `org-babel-load-languages'."
207 (set-default sym value)
208 (mapc (lambda (pair)
209 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
210 (if active
211 (progn
212 (require (intern (concat "ob-" lang))))
213 (progn
214 (funcall 'fmakunbound
215 (intern (concat "org-babel-execute:" lang)))
216 (funcall 'fmakunbound
217 (intern (concat "org-babel-expand-body:" lang)))))))
218 org-babel-load-languages))
220 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
221 ;;;###autoload
222 (defun org-babel-load-file (file &optional compile)
223 "Load Emacs Lisp source code blocks in the Org-mode FILE.
224 This function exports the source code using `org-babel-tangle'
225 and then loads the resulting file using `load-file'. With prefix
226 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
227 file to byte-code before it is loaded."
228 (interactive "fFile to load: \nP")
229 (let* ((age (lambda (file)
230 (float-time
231 (time-subtract (current-time)
232 (nth 5 (or (file-attributes (file-truename file))
233 (file-attributes file)))))))
234 (base-name (file-name-sans-extension file))
235 (exported-file (concat base-name ".el")))
236 ;; tangle if the org-mode file is newer than the elisp file
237 (unless (and (file-exists-p exported-file)
238 (> (funcall age file) (funcall age exported-file)))
239 (setq exported-file
240 (car (org-babel-tangle-file file exported-file "emacs-lisp"))))
241 (message "%s %s"
242 (if compile
243 (progn (byte-compile-file exported-file 'load)
244 "Compiled and loaded")
245 (progn (load-file exported-file) "Loaded"))
246 exported-file)))
248 (defcustom org-babel-load-languages '((emacs-lisp . t))
249 "Languages which can be evaluated in Org-mode buffers.
250 This list can be used to load support for any of the languages
251 below, note that each language will depend on a different set of
252 system executables and/or Emacs modes. When a language is
253 \"loaded\", then code blocks in that language can be evaluated
254 with `org-babel-execute-src-block' bound by default to C-c
255 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
256 be set to remove code block evaluation from the C-c C-c
257 keybinding. By default only Emacs Lisp (which has no
258 requirements) is loaded."
259 :group 'org-babel
260 :set 'org-babel-do-load-languages
261 :version "24.1"
262 :type '(alist :tag "Babel Languages"
263 :key-type
264 (choice
265 (const :tag "Awk" awk)
266 (const :tag "C" C)
267 (const :tag "R" R)
268 (const :tag "Asymptote" asymptote)
269 (const :tag "Calc" calc)
270 (const :tag "Clojure" clojure)
271 (const :tag "CSS" css)
272 (const :tag "Ditaa" ditaa)
273 (const :tag "Dot" dot)
274 (const :tag "Emacs Lisp" emacs-lisp)
275 (const :tag "Fortran" fortran)
276 (const :tag "Gnuplot" gnuplot)
277 (const :tag "Haskell" haskell)
278 (const :tag "IO" io)
279 (const :tag "J" J)
280 (const :tag "Java" java)
281 (const :tag "Javascript" js)
282 (const :tag "LaTeX" latex)
283 (const :tag "Ledger" ledger)
284 (const :tag "Lilypond" lilypond)
285 (const :tag "Lisp" lisp)
286 (const :tag "Makefile" makefile)
287 (const :tag "Maxima" maxima)
288 (const :tag "Matlab" matlab)
289 (const :tag "Mscgen" mscgen)
290 (const :tag "Ocaml" ocaml)
291 (const :tag "Octave" octave)
292 (const :tag "Org" org)
293 (const :tag "Perl" perl)
294 (const :tag "Pico Lisp" picolisp)
295 (const :tag "PlantUML" plantuml)
296 (const :tag "Python" python)
297 (const :tag "Ruby" ruby)
298 (const :tag "Sass" sass)
299 (const :tag "Scala" scala)
300 (const :tag "Scheme" scheme)
301 (const :tag "Screen" screen)
302 (const :tag "Shell Script" shell)
303 (const :tag "Shen" shen)
304 (const :tag "Sql" sql)
305 (const :tag "Sqlite" sqlite)
306 (const :tag "ebnf2ps" ebnf2ps))
307 :value-type (boolean :tag "Activate" :value t)))
309 ;;;; Customization variables
310 (defcustom org-clone-delete-id nil
311 "Remove ID property of clones of a subtree.
312 When non-nil, clones of a subtree don't inherit the ID property.
313 Otherwise they inherit the ID property with a new unique
314 identifier."
315 :type 'boolean
316 :version "24.1"
317 :group 'org-id)
319 ;;; Version
320 (org-check-version)
322 ;;;###autoload
323 (defun org-version (&optional here full message)
324 "Show the org-mode version.
325 Interactively, or when MESSAGE is non-nil, show it in echo area.
326 With prefix argument, or when HERE is non-nil, insert it at point.
327 In non-interactive uses, a reduced version string is output unless
328 FULL is given."
329 (interactive (list current-prefix-arg t (not current-prefix-arg)))
330 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
331 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
332 (load-suffixes (list ".el"))
333 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
334 (org-trash (or
335 (and (fboundp 'org-release) (fboundp 'org-git-version))
336 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
337 (load-suffixes save-load-suffixes)
338 (org-version (org-release))
339 (git-version (org-git-version))
340 (version (format "Org-mode version %s (%s @ %s)"
341 org-version
342 git-version
343 (if org-install-dir
344 (if (string= org-dir org-install-dir)
345 org-install-dir
346 (concat "mixed installation! " org-install-dir " and " org-dir))
347 "org-loaddefs.el can not be found!")))
348 (version1 (if full version org-version)))
349 (when here (insert version1))
350 (when message (message "%s" version1))
351 version1))
353 (defconst org-version (org-version))
356 ;;; Syntax Constants
358 ;;;; Block
360 (defconst org-block-regexp
361 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
362 "Regular expression for hiding blocks.")
364 (defconst org-dblock-start-re
365 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
366 "Matches the start line of a dynamic block, with parameters.")
368 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
369 "Matches the end of a dynamic block.")
371 ;;;; Clock and Planning
373 (defconst org-clock-string "CLOCK:"
374 "String used as prefix for timestamps clocking work hours on an item.")
376 (defconst org-closed-string "CLOSED:"
377 "String used as the prefix for timestamps logging closing a TODO entry.")
379 (defconst org-deadline-string "DEADLINE:"
380 "String to mark deadline entries.
381 A deadline is this string, followed by a time stamp. Should be a word,
382 terminated by a colon. You can insert a schedule keyword and
383 a timestamp with \\[org-deadline].")
385 (defconst org-scheduled-string "SCHEDULED:"
386 "String to mark scheduled TODO entries.
387 A schedule is this string, followed by a time stamp. Should be a word,
388 terminated by a colon. You can insert a schedule keyword and
389 a timestamp with \\[org-schedule].")
391 (defconst org-planning-or-clock-line-re
392 (concat "^[ \t]*"
393 (regexp-opt
394 (list org-clock-string org-closed-string org-deadline-string
395 org-scheduled-string)
397 "Matches a line with planning or clock info.
398 Matched keyword is in group 1.")
400 ;;;; Drawer
402 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
403 "Matches first or last line of a hidden block.
404 Group 1 contains drawer's name or \"END\".")
406 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
407 "Regular expression matching the first line of a property drawer.")
409 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
410 "Regular expression matching the last line of a property drawer.")
412 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
413 "Regular expression matching the first line of a clock drawer.")
415 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
416 "Regular expression matching the last line of a clock drawer.")
418 (defconst org-property-drawer-re
419 (concat "\\(" org-property-start-re "\\)[^\000]*?\\("
420 org-property-end-re "\\)\n?")
421 "Matches an entire property drawer.")
423 (defconst org-clock-drawer-re
424 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
425 org-clock-drawer-end-re "\\)\n?")
426 "Matches an entire clock drawer.")
428 ;;;; Headline
430 (defconst org-heading-keyword-regexp-format
431 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
432 "Printf format for a regexp matching a headline with some keyword.
433 This regexp will match the headline of any node which has the
434 exact keyword that is put into the format. The keyword isn't in
435 any group by default, but the stars and the body are.")
437 (defconst org-heading-keyword-maybe-regexp-format
438 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
439 "Printf format for a regexp matching a headline, possibly with some keyword.
440 This regexp can match any headline with the specified keyword, or
441 without a keyword. The keyword isn't in any group by default,
442 but the stars and the body are.")
444 (defconst org-archive-tag "ARCHIVE"
445 "The tag that marks a subtree as archived.
446 An archived subtree does not open during visibility cycling, and does
447 not contribute to the agenda listings.")
449 (defconst org-comment-string "COMMENT"
450 "Entries starting with this keyword will never be exported.
451 An entry can be toggled between COMMENT and normal with
452 \\[org-toggle-comment].")
455 ;;;; LaTeX Environments and Fragments
457 (defconst org-latex-regexps
458 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
459 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
460 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
461 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
462 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
463 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
464 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
465 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
466 "Regular expressions for matching embedded LaTeX.")
468 ;;;; Node Property
470 (defconst org-effort-property "Effort"
471 "The property that is being used to keep track of effort estimates.
472 Effort estimates given in this property need to have the format H:MM.")
474 ;;;; Table
476 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
477 "Detect an org-type or table-type table.")
479 (defconst org-table-line-regexp "^[ \t]*|"
480 "Detect an org-type table line.")
482 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
483 "Detect an org-type table line.")
485 (defconst org-table-hline-regexp "^[ \t]*|-"
486 "Detect an org-type table hline.")
488 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
489 "Detect a table-type table hline.")
491 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
492 "Detect the first line outside a table when searching from within it.
493 This works for both table types.")
495 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
496 "Detect a #+TBLFM line.")
498 ;;;; Timestamp
500 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
501 "Regular expression for fast time stamp matching.")
503 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
504 "Regular expression for fast time stamp matching.")
506 (defconst org-ts-regexp0
507 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
508 "Regular expression matching time strings for analysis.
509 This one does not require the space after the date, so it can be used
510 on a string that terminates immediately after the date.")
512 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
513 "Regular expression matching time strings for analysis.")
515 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
516 "Regular expression matching time stamps, with groups.")
518 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
519 "Regular expression matching time stamps (also [..]), with groups.")
521 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
522 "Regular expression matching a time stamp range.")
524 (defconst org-tr-regexp-both
525 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
526 "Regular expression matching a time stamp range.")
528 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
529 org-ts-regexp "\\)?")
530 "Regular expression matching a time stamp or time stamp range.")
532 (defconst org-tsr-regexp-both
533 (concat org-ts-regexp-both "\\(--?-?"
534 org-ts-regexp-both "\\)?")
535 "Regular expression matching a time stamp or time stamp range.
536 The time stamps may be either active or inactive.")
538 (defconst org-repeat-re
539 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
540 "Regular expression for specifying repeated events.
541 After a match, group 1 contains the repeat expression.")
543 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
544 "Formats for `format-time-string' which are used for time stamps.")
547 ;;; The custom variables
549 (defgroup org nil
550 "Outline-based notes management and organizer."
551 :tag "Org"
552 :group 'outlines
553 :group 'calendar)
555 (defcustom org-mode-hook nil
556 "Mode hook for Org-mode, run after the mode was turned on."
557 :group 'org
558 :type 'hook)
560 (defcustom org-load-hook nil
561 "Hook that is run after org.el has been loaded."
562 :group 'org
563 :type 'hook)
565 (defcustom org-log-buffer-setup-hook nil
566 "Hook that is run after an Org log buffer is created."
567 :group 'org
568 :version "24.1"
569 :type 'hook)
571 (defvar org-modules) ; defined below
572 (defvar org-modules-loaded nil
573 "Have the modules been loaded already?")
575 (defun org-load-modules-maybe (&optional force)
576 "Load all extensions listed in `org-modules'."
577 (when (or force (not org-modules-loaded))
578 (mapc (lambda (ext)
579 (condition-case nil (require ext)
580 (error (message "Problems while trying to load feature `%s'" ext))))
581 org-modules)
582 (setq org-modules-loaded t)))
584 (defun org-set-modules (var value)
585 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
586 (set var value)
587 (when (featurep 'org)
588 (org-load-modules-maybe 'force)
589 (org-element-cache-reset 'all)))
591 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
592 "Modules that should always be loaded together with org.el.
594 If a description starts with <C>, the file is not part of Emacs
595 and loading it will require that you have downloaded and properly
596 installed the Org mode distribution.
598 You can also use this system to load external packages (i.e. neither Org
599 core modules, nor modules from the CONTRIB directory). Just add symbols
600 to the end of the list. If the package is called org-xyz.el, then you need
601 to add the symbol `xyz', and the package must have a call to:
603 \(provide 'org-xyz)
605 For export specific modules, see also `org-export-backends'."
606 :group 'org
607 :set 'org-set-modules
608 :version "24.4"
609 :package-version '(Org . "8.0")
610 :type
611 '(set :greedy t
612 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
613 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
614 (const :tag " crypt: Encryption of subtrees" org-crypt)
615 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
616 (const :tag " docview: Links to doc-view buffers" org-docview)
617 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
618 (const :tag " habit: Track your consistency with habits" org-habit)
619 (const :tag " id: Global IDs for identifying entries" org-id)
620 (const :tag " info: Links to Info nodes" org-info)
621 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
622 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
623 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
624 (const :tag " mouse: Additional mouse support" org-mouse)
625 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
626 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
627 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
629 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
630 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
631 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
632 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
633 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
634 (const :tag "C collector: Collect properties into tables" org-collector)
635 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
636 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
637 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
638 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
639 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
640 (const :tag "C eval: Include command output as text" org-eval)
641 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
642 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
643 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
644 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
645 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
646 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
647 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
648 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
649 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
650 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
651 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
652 (const :tag "C mew: Links to Mew folders/messages" org-mew)
653 (const :tag "C mtags: Support for muse-like tags" org-mtags)
654 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
655 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
656 (const :tag "C registry: A registry for Org-mode links" org-registry)
657 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
658 (const :tag "C secretary: Team management with org-mode" org-secretary)
659 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
660 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
661 (const :tag "C track: Keep up with Org-mode development" org-track)
662 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
663 (const :tag "C vm: Links to VM folders/messages" org-vm)
664 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
665 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
666 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
668 (defvar org-export--registered-backends) ; From ox.el.
669 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
670 (declare-function org-export-backend-name "ox" (backend))
671 (defcustom org-export-backends '(ascii html icalendar latex)
672 "List of export back-ends that should be always available.
674 If a description starts with <C>, the file is not part of Emacs
675 and loading it will require that you have downloaded and properly
676 installed the Org mode distribution.
678 Unlike to `org-modules', libraries in this list will not be
679 loaded along with Org, but only once the export framework is
680 needed.
682 This variable needs to be set before org.el is loaded. If you
683 need to make a change while Emacs is running, use the customize
684 interface or run the following code, where VAL stands for the new
685 value of the variable, after updating it:
687 \(progn
688 \(setq org-export--registered-backends
689 \(org-remove-if-not
690 \(lambda (backend)
691 \(let ((name (org-export-backend-name backend)))
692 \(or (memq name val)
693 \(catch 'parentp
694 \(dolist (b val)
695 \(and (org-export-derived-backend-p b name)
696 \(throw 'parentp t)))))))
697 org-export--registered-backends))
698 \(let ((new-list (mapcar 'org-export-backend-name
699 org-export--registered-backends)))
700 \(dolist (backend val)
701 \(cond
702 \((not (load (format \"ox-%s\" backend) t t))
703 \(message \"Problems while trying to load export back-end `%s'\"
704 backend))
705 \((not (memq backend new-list)) (push backend new-list))))
706 \(set-default 'org-export-backends new-list)))
708 Adding a back-end to this list will also pull the back-end it
709 depends on, if any."
710 :group 'org
711 :group 'org-export
712 :version "24.4"
713 :package-version '(Org . "8.0")
714 :initialize 'custom-initialize-set
715 :set (lambda (var val)
716 (if (not (featurep 'ox)) (set-default var val)
717 ;; Any back-end not required anymore (not present in VAL and not
718 ;; a parent of any back-end in the new value) is removed from the
719 ;; list of registered back-ends.
720 (setq org-export--registered-backends
721 (org-remove-if-not
722 (lambda (backend)
723 (let ((name (org-export-backend-name backend)))
724 (or (memq name val)
725 (catch 'parentp
726 (dolist (b val)
727 (and (org-export-derived-backend-p b name)
728 (throw 'parentp t)))))))
729 org-export--registered-backends))
730 ;; Now build NEW-LIST of both new back-ends and required
731 ;; parents.
732 (let ((new-list (mapcar 'org-export-backend-name
733 org-export--registered-backends)))
734 (dolist (backend val)
735 (cond
736 ((not (load (format "ox-%s" backend) t t))
737 (message "Problems while trying to load export back-end `%s'"
738 backend))
739 ((not (memq backend new-list)) (push backend new-list))))
740 ;; Set VAR to that list with fixed dependencies.
741 (set-default var new-list))))
742 :type '(set :greedy t
743 (const :tag " ascii Export buffer to ASCII format" ascii)
744 (const :tag " beamer Export buffer to Beamer presentation" beamer)
745 (const :tag " html Export buffer to HTML format" html)
746 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
747 (const :tag " latex Export buffer to LaTeX format" latex)
748 (const :tag " man Export buffer to MAN format" man)
749 (const :tag " md Export buffer to Markdown format" md)
750 (const :tag " odt Export buffer to ODT format" odt)
751 (const :tag " org Export buffer to Org format" org)
752 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
753 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
754 (const :tag "C deck Export buffer to deck.js presentations" deck)
755 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
756 (const :tag "C groff Export buffer to Groff format" groff)
757 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
758 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
759 (const :tag "C s5 Export buffer to s5 presentations" s5)
760 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
762 (eval-after-load 'ox
763 '(mapc
764 (lambda (backend)
765 (condition-case nil (require (intern (format "ox-%s" backend)))
766 (error (message "Problems while trying to load export back-end `%s'"
767 backend))))
768 org-export-backends))
770 (defcustom org-support-shift-select nil
771 "Non-nil means make shift-cursor commands select text when possible.
773 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
774 start selecting a region, or enlarge regions started in this way.
775 In Org-mode, in special contexts, these same keys are used for
776 other purposes, important enough to compete with shift selection.
777 Org tries to balance these needs by supporting `shift-select-mode'
778 outside these special contexts, under control of this variable.
780 The default of this variable is nil, to avoid confusing behavior. Shifted
781 cursor keys will then execute Org commands in the following contexts:
782 - on a headline, changing TODO state (left/right) and priority (up/down)
783 - on a time stamp, changing the time
784 - in a plain list item, changing the bullet type
785 - in a property definition line, switching between allowed values
786 - in the BEGIN line of a clock table (changing the time block).
787 Outside these contexts, the commands will throw an error.
789 When this variable is t and the cursor is not in a special
790 context, Org-mode will support shift-selection for making and
791 enlarging regions. To make this more effective, the bullet
792 cycling will no longer happen anywhere in an item line, but only
793 if the cursor is exactly on the bullet.
795 If you set this variable to the symbol `always', then the keys
796 will not be special in headlines, property lines, and item lines,
797 to make shift selection work there as well. If this is what you
798 want, you can use the following alternative commands: `C-c C-t'
799 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
800 can be used to switch TODO sets, `C-c -' to cycle item bullet
801 types, and properties can be edited by hand or in column view.
803 However, when the cursor is on a timestamp, shift-cursor commands
804 will still edit the time stamp - this is just too good to give up.
806 XEmacs user should have this variable set to nil, because
807 `shift-select-mode' is in Emacs 23 or later only."
808 :group 'org
809 :type '(choice
810 (const :tag "Never" nil)
811 (const :tag "When outside special context" t)
812 (const :tag "Everywhere except timestamps" always)))
814 (defcustom org-loop-over-headlines-in-active-region nil
815 "Shall some commands act upon headlines in the active region?
817 When set to `t', some commands will be performed in all headlines
818 within the active region.
820 When set to `start-level', some commands will be performed in all
821 headlines within the active region, provided that these headlines
822 are of the same level than the first one.
824 When set to a string, those commands will be performed on the
825 matching headlines within the active region. Such string must be
826 a tags/property/todo match as it is used in the agenda tags view.
828 The list of commands is: `org-schedule', `org-deadline',
829 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
830 `org-archive-to-archive-sibling'. The archiving commands skip
831 already archived entries."
832 :type '(choice (const :tag "Don't loop" nil)
833 (const :tag "All headlines in active region" t)
834 (const :tag "In active region, headlines at the same level than the first one" start-level)
835 (string :tag "Tags/Property/Todo matcher"))
836 :version "24.1"
837 :group 'org-todo
838 :group 'org-archive)
840 (defgroup org-startup nil
841 "Options concerning startup of Org-mode."
842 :tag "Org Startup"
843 :group 'org)
845 (defcustom org-startup-folded t
846 "Non-nil means entering Org-mode will switch to OVERVIEW.
847 This can also be configured on a per-file basis by adding one of
848 the following lines anywhere in the buffer:
850 #+STARTUP: fold (or `overview', this is equivalent)
851 #+STARTUP: nofold (or `showall', this is equivalent)
852 #+STARTUP: content
853 #+STARTUP: showeverything
855 By default, this option is ignored when Org opens agenda files
856 for the first time. If you want the agenda to honor the startup
857 option, set `org-agenda-inhibit-startup' to nil."
858 :group 'org-startup
859 :type '(choice
860 (const :tag "nofold: show all" nil)
861 (const :tag "fold: overview" t)
862 (const :tag "content: all headlines" content)
863 (const :tag "show everything, even drawers" showeverything)))
865 (defcustom org-startup-truncated t
866 "Non-nil means entering Org-mode will set `truncate-lines'.
867 This is useful since some lines containing links can be very long and
868 uninteresting. Also tables look terrible when wrapped."
869 :group 'org-startup
870 :type 'boolean)
872 (defcustom org-startup-indented nil
873 "Non-nil means turn on `org-indent-mode' on startup.
874 This can also be configured on a per-file basis by adding one of
875 the following lines anywhere in the buffer:
877 #+STARTUP: indent
878 #+STARTUP: noindent"
879 :group 'org-structure
880 :type '(choice
881 (const :tag "Not" nil)
882 (const :tag "Globally (slow on startup in large files)" t)))
884 (defcustom org-use-sub-superscripts t
885 "Non-nil means interpret \"_\" and \"^\" for display.
887 If you want to control how Org exports those characters, see
888 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
889 used to be an alias for `org-export-with-sub-superscripts' in
890 Org <8.0, it is not anymore.
892 When this option is turned on, you can use TeX-like syntax for
893 sub- and superscripts within the buffer. Several characters after
894 \"_\" or \"^\" will be considered as a single item - so grouping
895 with {} is normally not needed. For example, the following things
896 will be parsed as single sub- or superscripts:
898 10^24 or 10^tau several digits will be considered 1 item.
899 10^-12 or 10^-tau a leading sign with digits or a word
900 x^2-y^3 will be read as x^2 - y^3, because items are
901 terminated by almost any nonword/nondigit char.
902 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
904 Still, ambiguity is possible. So when in doubt, use {} to enclose
905 the sub/superscript. If you set this variable to the symbol `{}',
906 the braces are *required* in order to trigger interpretations as
907 sub/superscript. This can be helpful in documents that need \"_\"
908 frequently in plain text."
909 :group 'org-startup
910 :version "24.4"
911 :package-version '(Org . "8.0")
912 :type '(choice
913 (const :tag "Always interpret" t)
914 (const :tag "Only with braces" {})
915 (const :tag "Never interpret" nil)))
917 (defcustom org-startup-with-beamer-mode nil
918 "Non-nil means turn on `org-beamer-mode' on startup.
919 This can also be configured on a per-file basis by adding one of
920 the following lines anywhere in the buffer:
922 #+STARTUP: beamer"
923 :group 'org-startup
924 :version "24.1"
925 :type 'boolean)
927 (defcustom org-startup-align-all-tables nil
928 "Non-nil means align all tables when visiting a file.
929 This is useful when the column width in tables is forced with <N> cookies
930 in table fields. Such tables will look correct only after the first re-align.
931 This can also be configured on a per-file basis by adding one of
932 the following lines anywhere in the buffer:
933 #+STARTUP: align
934 #+STARTUP: noalign"
935 :group 'org-startup
936 :type 'boolean)
938 (defcustom org-startup-with-inline-images nil
939 "Non-nil means show inline images when loading a new Org file.
940 This can also be configured on a per-file basis by adding one of
941 the following lines anywhere in the buffer:
942 #+STARTUP: inlineimages
943 #+STARTUP: noinlineimages"
944 :group 'org-startup
945 :version "24.1"
946 :type 'boolean)
948 (defcustom org-startup-with-latex-preview nil
949 "Non-nil means preview LaTeX fragments when loading a new Org file.
951 This can also be configured on a per-file basis by adding one of
952 the following lines anywhere in the buffer:
953 #+STARTUP: latexpreview
954 #+STARTUP: nolatexpreview"
955 :group 'org-startup
956 :version "24.4"
957 :package-version '(Org . "8.0")
958 :type 'boolean)
960 (defcustom org-insert-mode-line-in-empty-file nil
961 "Non-nil means insert the first line setting Org-mode in empty files.
962 When the function `org-mode' is called interactively in an empty file, this
963 normally means that the file name does not automatically trigger Org-mode.
964 To ensure that the file will always be in Org-mode in the future, a
965 line enforcing Org-mode will be inserted into the buffer, if this option
966 has been set."
967 :group 'org-startup
968 :type 'boolean)
970 (defcustom org-replace-disputed-keys nil
971 "Non-nil means use alternative key bindings for some keys.
972 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
973 These keys are also used by other packages like shift-selection-mode'
974 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
975 If you want to use Org-mode together with one of these other modes,
976 or more generally if you would like to move some Org-mode commands to
977 other keys, set this variable and configure the keys with the variable
978 `org-disputed-keys'.
980 This option is only relevant at load-time of Org-mode, and must be set
981 *before* org.el is loaded. Changing it requires a restart of Emacs to
982 become effective."
983 :group 'org-startup
984 :type 'boolean)
986 (defcustom org-use-extra-keys nil
987 "Non-nil means use extra key sequence definitions for certain commands.
988 This happens automatically if you run XEmacs or if `window-system'
989 is nil. This variable lets you do the same manually. You must
990 set it before loading org.
992 Example: on Carbon Emacs 22 running graphically, with an external
993 keyboard on a Powerbook, the default way of setting M-left might
994 not work for either Alt or ESC. Setting this variable will make
995 it work for ESC."
996 :group 'org-startup
997 :type 'boolean)
999 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1001 (defcustom org-disputed-keys
1002 '(([(shift up)] . [(meta p)])
1003 ([(shift down)] . [(meta n)])
1004 ([(shift left)] . [(meta -)])
1005 ([(shift right)] . [(meta +)])
1006 ([(control shift right)] . [(meta shift +)])
1007 ([(control shift left)] . [(meta shift -)]))
1008 "Keys for which Org-mode and other modes compete.
1009 This is an alist, cars are the default keys, second element specifies
1010 the alternative to use when `org-replace-disputed-keys' is t.
1012 Keys can be specified in any syntax supported by `define-key'.
1013 The value of this option takes effect only at Org-mode's startup,
1014 therefore you'll have to restart Emacs to apply it after changing."
1015 :group 'org-startup
1016 :type 'alist)
1018 (defun org-key (key)
1019 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1020 Or return the original if not disputed.
1021 Also apply the translations defined in `org-xemacs-key-equivalents'."
1022 (when org-replace-disputed-keys
1023 (let* ((nkey (key-description key))
1024 (x (org-find-if (lambda (x)
1025 (equal (key-description (car x)) nkey))
1026 org-disputed-keys)))
1027 (setq key (if x (cdr x) key))))
1028 (when (featurep 'xemacs)
1029 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
1030 key)
1032 (defun org-find-if (predicate seq)
1033 (catch 'exit
1034 (while seq
1035 (if (funcall predicate (car seq))
1036 (throw 'exit (car seq))
1037 (pop seq)))))
1039 (defun org-defkey (keymap key def)
1040 "Define a key, possibly translated, as returned by `org-key'."
1041 (define-key keymap (org-key key) def))
1043 (defcustom org-ellipsis nil
1044 "The ellipsis to use in the Org-mode outline.
1045 When nil, just use the standard three dots.
1046 When a string, use that string instead.
1047 When a face, use the standard 3 dots, but with the specified face.
1048 The change affects only Org-mode (which will then use its own display table).
1049 Changing this requires executing `M-x org-mode RET' in a buffer to become
1050 effective."
1051 :group 'org-startup
1052 :type '(choice (const :tag "Default" nil)
1053 (face :tag "Face" :value org-warning)
1054 (string :tag "String" :value "...#")))
1056 (defvar org-display-table nil
1057 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
1059 (defgroup org-keywords nil
1060 "Keywords in Org-mode."
1061 :tag "Org Keywords"
1062 :group 'org)
1064 (defcustom org-closed-keep-when-no-todo nil
1065 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1066 :group 'org-todo
1067 :group 'org-keywords
1068 :version "24.4"
1069 :package-version '(Org . "8.0")
1070 :type 'boolean)
1072 (defgroup org-structure nil
1073 "Options concerning the general structure of Org-mode files."
1074 :tag "Org Structure"
1075 :group 'org)
1077 (defgroup org-reveal-location nil
1078 "Options about how to make context of a location visible."
1079 :tag "Org Reveal Location"
1080 :group 'org-structure)
1082 (defconst org-context-choice
1083 '(choice
1084 (const :tag "Always" t)
1085 (const :tag "Never" nil)
1086 (repeat :greedy t :tag "Individual contexts"
1087 (cons
1088 (choice :tag "Context"
1089 (const agenda)
1090 (const org-goto)
1091 (const occur-tree)
1092 (const tags-tree)
1093 (const link-search)
1094 (const mark-goto)
1095 (const bookmark-jump)
1096 (const isearch)
1097 (const default))
1098 (boolean))))
1099 "Contexts for the reveal options.")
1101 (defcustom org-show-hierarchy-above '((default . t))
1102 "Non-nil means show full hierarchy when revealing a location.
1103 Org-mode often shows locations in an org-mode file which might have
1104 been invisible before. When this is set, the hierarchy of headings
1105 above the exposed location is shown.
1106 Turning this off for example for sparse trees makes them very compact.
1107 Instead of t, this can also be an alist specifying this option for different
1108 contexts. Valid contexts are
1109 agenda when exposing an entry from the agenda
1110 org-goto when using the command `org-goto' on key C-c C-j
1111 occur-tree when using the command `org-occur' on key C-c /
1112 tags-tree when constructing a sparse tree based on tags matches
1113 link-search when exposing search matches associated with a link
1114 mark-goto when exposing the jump goal of a mark
1115 bookmark-jump when exposing a bookmark location
1116 isearch when exiting from an incremental search
1117 default default for all contexts not set explicitly"
1118 :group 'org-reveal-location
1119 :type org-context-choice)
1121 (defcustom org-show-following-heading '((default . nil))
1122 "Non-nil means show following heading when revealing a location.
1123 Org-mode often shows locations in an org-mode file which might have
1124 been invisible before. When this is set, the heading following the
1125 match is shown.
1126 Turning this off for example for sparse trees makes them very compact,
1127 but makes it harder to edit the location of the match. In such a case,
1128 use the command \\[org-reveal] to show more context.
1129 Instead of t, this can also be an alist specifying this option for different
1130 contexts. See `org-show-hierarchy-above' for valid contexts."
1131 :group 'org-reveal-location
1132 :type org-context-choice)
1134 (defcustom org-show-siblings '((default . nil) (isearch t) (bookmark-jump t))
1135 "Non-nil means show all sibling heading 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 sibling of the current entry
1138 heading are all made visible. If `org-show-hierarchy-above' is t,
1139 the same happens on each level of the hierarchy above the current entry.
1141 By default this is on for the isearch context, off for all other contexts.
1142 Turning this off for example for sparse trees makes them very compact,
1143 but makes it harder to edit the location of the match. In such a case,
1144 use the command \\[org-reveal] to show more context.
1145 Instead of t, this can also be an alist specifying this option for different
1146 contexts. See `org-show-hierarchy-above' for valid contexts."
1147 :group 'org-reveal-location
1148 :type org-context-choice
1149 :version "24.4"
1150 :package-version '(Org . "8.0"))
1152 (defcustom org-show-entry-below '((default . nil))
1153 "Non-nil means show the entry below a headline when revealing a location.
1154 Org-mode often shows locations in an org-mode file which might have
1155 been invisible before. When this is set, the text below the headline that is
1156 exposed is also shown.
1158 By default this is off for all contexts.
1159 Instead of t, this can also be an alist specifying this option for different
1160 contexts. See `org-show-hierarchy-above' for valid contexts."
1161 :group 'org-reveal-location
1162 :type org-context-choice)
1164 (defcustom org-indirect-buffer-display 'other-window
1165 "How should indirect tree buffers be displayed?
1166 This applies to indirect buffers created with the commands
1167 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
1168 Valid values are:
1169 current-window Display in the current window
1170 other-window Just display in another window.
1171 dedicated-frame Create one new frame, and re-use it each time.
1172 new-frame Make a new frame each time. Note that in this case
1173 previously-made indirect buffers are kept, and you need to
1174 kill these buffers yourself."
1175 :group 'org-structure
1176 :group 'org-agenda-windows
1177 :type '(choice
1178 (const :tag "In current window" current-window)
1179 (const :tag "In current frame, other window" other-window)
1180 (const :tag "Each time a new frame" new-frame)
1181 (const :tag "One dedicated frame" dedicated-frame)))
1183 (defcustom org-use-speed-commands nil
1184 "Non-nil means activate single letter commands at beginning of a headline.
1185 This may also be a function to test for appropriate locations where speed
1186 commands should be active.
1188 For example, to activate speed commands when the point is on any
1189 star at the beginning of the headline, you can do this:
1191 (setq org-use-speed-commands
1192 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1193 :group 'org-structure
1194 :type '(choice
1195 (const :tag "Never" nil)
1196 (const :tag "At beginning of headline stars" t)
1197 (function)))
1199 (defcustom org-speed-commands-user nil
1200 "Alist of additional speed commands.
1201 This list will be checked before `org-speed-commands-default'
1202 when the variable `org-use-speed-commands' is non-nil
1203 and when the cursor is at the beginning of a headline.
1204 The car if each entry is a string with a single letter, which must
1205 be assigned to `self-insert-command' in the global map.
1206 The cdr is either a command to be called interactively, a function
1207 to be called, or a form to be evaluated.
1208 An entry that is just a list with a single string will be interpreted
1209 as a descriptive headline that will be added when listing the speed
1210 commands in the Help buffer using the `?' speed command."
1211 :group 'org-structure
1212 :type '(repeat :value ("k" . ignore)
1213 (choice :value ("k" . ignore)
1214 (list :tag "Descriptive Headline" (string :tag "Headline"))
1215 (cons :tag "Letter and Command"
1216 (string :tag "Command letter")
1217 (choice
1218 (function)
1219 (sexp))))))
1221 (defcustom org-bookmark-names-plist
1222 '(:last-capture "org-capture-last-stored"
1223 :last-refile "org-refile-last-stored"
1224 :last-capture-marker "org-capture-last-stored-marker")
1225 "Names for bookmarks automatically set by some Org commands.
1226 This can provide strings as names for a number of bookmarks Org sets
1227 automatically. The following keys are currently implemented:
1228 :last-capture
1229 :last-capture-marker
1230 :last-refile
1231 When a key does not show up in the property list, the corresponding bookmark
1232 is not set."
1233 :group 'org-structure
1234 :type 'plist)
1236 (defgroup org-cycle nil
1237 "Options concerning visibility cycling in Org-mode."
1238 :tag "Org Cycle"
1239 :group 'org-structure)
1241 (defcustom org-cycle-skip-children-state-if-no-children t
1242 "Non-nil means skip CHILDREN state in entries that don't have any."
1243 :group 'org-cycle
1244 :type 'boolean)
1246 (defcustom org-cycle-max-level nil
1247 "Maximum level which should still be subject to visibility cycling.
1248 Levels higher than this will, for cycling, be treated as text, not a headline.
1249 When `org-odd-levels-only' is set, a value of N in this variable actually
1250 means 2N-1 stars as the limiting headline.
1251 When nil, cycle all levels.
1252 Note that the limiting level of cycling is also influenced by
1253 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1254 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1255 than its value."
1256 :group 'org-cycle
1257 :type '(choice
1258 (const :tag "No limit" nil)
1259 (integer :tag "Maximum level")))
1261 (defcustom org-hide-block-startup nil
1262 "Non-nil means entering Org-mode will fold all blocks.
1263 This can also be set in on a per-file basis with
1265 #+STARTUP: hideblocks
1266 #+STARTUP: showblocks"
1267 :group 'org-startup
1268 :group 'org-cycle
1269 :type 'boolean)
1271 (defcustom org-cycle-global-at-bob nil
1272 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1273 This makes it possible to do global cycling without having to use S-TAB or
1274 \\[universal-argument] TAB. For this special case to work, the first line
1275 of the buffer must not be a headline -- it may be empty or some other text.
1276 When used in this way, `org-cycle-hook' is disabled temporarily to make
1277 sure the cursor stays at the beginning of the buffer. When this option is
1278 nil, don't do anything special at the beginning of the buffer."
1279 :group 'org-cycle
1280 :type 'boolean)
1282 (defcustom org-cycle-level-after-item/entry-creation t
1283 "Non-nil means cycle entry level or item indentation in new empty entries.
1285 When the cursor is at the end of an empty headline, i.e., with only stars
1286 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1287 and then all possible ancestor states, before returning to the original state.
1288 This makes data entry extremely fast: M-RET to create a new headline,
1289 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1291 When the cursor is at the end of an empty plain list item, one TAB will
1292 make it a subitem, two or more tabs will back up to make this an item
1293 higher up in the item hierarchy."
1294 :group 'org-cycle
1295 :type 'boolean)
1297 (defcustom org-cycle-emulate-tab t
1298 "Where should `org-cycle' emulate TAB.
1299 nil Never
1300 white Only in completely white lines
1301 whitestart Only at the beginning of lines, before the first non-white char
1302 t Everywhere except in headlines
1303 exc-hl-bol Everywhere except at the start of a headline
1304 If TAB is used in a place where it does not emulate TAB, the current subtree
1305 visibility is cycled."
1306 :group 'org-cycle
1307 :type '(choice (const :tag "Never" nil)
1308 (const :tag "Only in completely white lines" white)
1309 (const :tag "Before first char in a line" whitestart)
1310 (const :tag "Everywhere except in headlines" t)
1311 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1313 (defcustom org-cycle-separator-lines 2
1314 "Number of empty lines needed to keep an empty line between collapsed trees.
1315 If you leave an empty line between the end of a subtree and the following
1316 headline, this empty line is hidden when the subtree is folded.
1317 Org-mode will leave (exactly) one empty line visible if the number of
1318 empty lines is equal or larger to the number given in this variable.
1319 So the default 2 means at least 2 empty lines after the end of a subtree
1320 are needed to produce free space between a collapsed subtree and the
1321 following headline.
1323 If the number is negative, and the number of empty lines is at least -N,
1324 all empty lines are shown.
1326 Special case: when 0, never leave empty lines in collapsed view."
1327 :group 'org-cycle
1328 :type 'integer)
1329 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1331 (defcustom org-pre-cycle-hook nil
1332 "Hook that is run before visibility cycling is happening.
1333 The function(s) in this hook must accept a single argument which indicates
1334 the new state that will be set right after running this hook. The
1335 argument is a symbol. Before a global state change, it can have the values
1336 `overview', `content', or `all'. Before a local state change, it can have
1337 the values `folded', `children', or `subtree'."
1338 :group 'org-cycle
1339 :type 'hook)
1341 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1342 org-cycle-hide-drawers
1343 org-cycle-hide-inline-tasks
1344 org-cycle-show-empty-lines
1345 org-optimize-window-after-visibility-change)
1346 "Hook that is run after `org-cycle' has changed the buffer visibility.
1347 The function(s) in this hook must accept a single argument which indicates
1348 the new state that was set by the most recent `org-cycle' command. The
1349 argument is a symbol. After a global state change, it can have the values
1350 `overview', `contents', or `all'. After a local state change, it can have
1351 the values `folded', `children', or `subtree'."
1352 :group 'org-cycle
1353 :type 'hook)
1355 (defgroup org-edit-structure nil
1356 "Options concerning structure editing in Org-mode."
1357 :tag "Org Edit Structure"
1358 :group 'org-structure)
1360 (defcustom org-odd-levels-only nil
1361 "Non-nil means skip even levels and only use odd levels for the outline.
1362 This has the effect that two stars are being added/taken away in
1363 promotion/demotion commands. It also influences how levels are
1364 handled by the exporters.
1365 Changing it requires restart of `font-lock-mode' to become effective
1366 for fontification also in regions already fontified.
1367 You may also set this on a per-file basis by adding one of the following
1368 lines to the buffer:
1370 #+STARTUP: odd
1371 #+STARTUP: oddeven"
1372 :group 'org-edit-structure
1373 :group 'org-appearance
1374 :type 'boolean)
1376 (defcustom org-adapt-indentation t
1377 "Non-nil means adapt indentation to outline node level.
1379 When this variable is set, Org assumes that you write outlines by
1380 indenting text in each node to align with the headline (after the stars).
1381 The following issues are influenced by this variable:
1383 - When this is set and the *entire* text in an entry is indented, the
1384 indentation is increased by one space in a demotion command, and
1385 decreased by one in a promotion command. If any line in the entry
1386 body starts with text at column 0, indentation is not changed at all.
1388 - Property drawers and planning information is inserted indented when
1389 this variable s set. When nil, they will not be indented.
1391 - TAB indents a line relative to context. The lines below a headline
1392 will be indented when this variable is set.
1394 Note that this is all about true indentation, by adding and removing
1395 space characters. See also `org-indent.el' which does level-dependent
1396 indentation in a virtual way, i.e. at display time in Emacs."
1397 :group 'org-edit-structure
1398 :type 'boolean)
1400 (defcustom org-special-ctrl-a/e nil
1401 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1403 When t, `C-a' will bring back the cursor to the beginning of the
1404 headline text, i.e. after the stars and after a possible TODO
1405 keyword. In an item, this will be the position after bullet and
1406 check-box, if any. When the cursor is already at that position,
1407 another `C-a' will bring it to the beginning of the line.
1409 `C-e' will jump to the end of the headline, ignoring the presence
1410 of tags in the headline. A second `C-e' will then jump to the
1411 true end of the line, after any tags. This also means that, when
1412 this variable is non-nil, `C-e' also will never jump beyond the
1413 end of the heading of a folded section, i.e. not after the
1414 ellipses.
1416 When set to the symbol `reversed', the first `C-a' or `C-e' works
1417 normally, going to the true line boundary first. Only a directly
1418 following, identical keypress will bring the cursor to the
1419 special positions.
1421 This may also be a cons cell where the behavior for `C-a' and
1422 `C-e' is set separately."
1423 :group 'org-edit-structure
1424 :type '(choice
1425 (const :tag "off" nil)
1426 (const :tag "on: after stars/bullet and before tags first" t)
1427 (const :tag "reversed: true line boundary first" reversed)
1428 (cons :tag "Set C-a and C-e separately"
1429 (choice :tag "Special C-a"
1430 (const :tag "off" nil)
1431 (const :tag "on: after stars/bullet first" t)
1432 (const :tag "reversed: before stars/bullet first" reversed))
1433 (choice :tag "Special C-e"
1434 (const :tag "off" nil)
1435 (const :tag "on: before tags first" t)
1436 (const :tag "reversed: after tags first" reversed)))))
1437 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1439 (defcustom org-special-ctrl-k nil
1440 "Non-nil means `C-k' will behave specially in headlines.
1441 When nil, `C-k' will call the default `kill-line' command.
1442 When t, the following will happen while the cursor is in the headline:
1444 - When the cursor is at the beginning of a headline, kill the entire
1445 line and possible the folded subtree below the line.
1446 - When in the middle of the headline text, kill the headline up to the tags.
1447 - When after the headline text, kill the tags."
1448 :group 'org-edit-structure
1449 :type 'boolean)
1451 (defcustom org-ctrl-k-protect-subtree nil
1452 "Non-nil means, do not delete a hidden subtree with C-k.
1453 When set to the symbol `error', simply throw an error when C-k is
1454 used to kill (part-of) a headline that has hidden text behind it.
1455 Any other non-nil value will result in a query to the user, if it is
1456 OK to kill that hidden subtree. When nil, kill without remorse."
1457 :group 'org-edit-structure
1458 :version "24.1"
1459 :type '(choice
1460 (const :tag "Do not protect hidden subtrees" nil)
1461 (const :tag "Protect hidden subtrees with a security query" t)
1462 (const :tag "Never kill a hidden subtree with C-k" error)))
1464 (defcustom org-special-ctrl-o t
1465 "Non-nil means, make `C-o' insert a row in tables."
1466 :group 'org-edit-structure
1467 :type 'boolean)
1469 (defcustom org-catch-invisible-edits nil
1470 "Check if in invisible region before inserting or deleting a character.
1471 Valid values are:
1473 nil Do not check, so just do invisible edits.
1474 error Throw an error and do nothing.
1475 show Make point visible, and do the requested edit.
1476 show-and-error Make point visible, then throw an error and abort the edit.
1477 smart Make point visible, and do insertion/deletion if it is
1478 adjacent to visible text and the change feels predictable.
1479 Never delete a previously invisible character or add in the
1480 middle or right after an invisible region. Basically, this
1481 allows insertion and backward-delete right before ellipses.
1482 FIXME: maybe in this case we should not even show?"
1483 :group 'org-edit-structure
1484 :version "24.1"
1485 :type '(choice
1486 (const :tag "Do not check" nil)
1487 (const :tag "Throw error when trying to edit" error)
1488 (const :tag "Unhide, but do not do the edit" show-and-error)
1489 (const :tag "Show invisible part and do the edit" show)
1490 (const :tag "Be smart and do the right thing" smart)))
1492 (defcustom org-yank-folded-subtrees t
1493 "Non-nil means when yanking subtrees, fold them.
1494 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1495 it starts with a heading and all other headings in it are either children
1496 or siblings, then fold all the subtrees. However, do this only if no
1497 text after the yank would be swallowed into a folded tree by this action."
1498 :group 'org-edit-structure
1499 :type 'boolean)
1501 (defcustom org-yank-adjusted-subtrees nil
1502 "Non-nil means when yanking subtrees, adjust the level.
1503 With this setting, `org-paste-subtree' is used to insert the subtree, see
1504 this function for details."
1505 :group 'org-edit-structure
1506 :type 'boolean)
1508 (defcustom org-M-RET-may-split-line '((default . t))
1509 "Non-nil means M-RET will split the line at the cursor position.
1510 When nil, it will go to the end of the line before making a
1511 new line.
1512 You may also set this option in a different way for different
1513 contexts. Valid contexts are:
1515 headline when creating a new headline
1516 item when creating a new item
1517 table in a table field
1518 default the value to be used for all contexts not explicitly
1519 customized"
1520 :group 'org-structure
1521 :group 'org-table
1522 :type '(choice
1523 (const :tag "Always" t)
1524 (const :tag "Never" nil)
1525 (repeat :greedy t :tag "Individual contexts"
1526 (cons
1527 (choice :tag "Context"
1528 (const headline)
1529 (const item)
1530 (const table)
1531 (const default))
1532 (boolean)))))
1535 (defcustom org-insert-heading-respect-content nil
1536 "Non-nil means insert new headings after the current subtree.
1537 When nil, the new heading is created directly after the current line.
1538 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1539 this variable on for the duration of the command."
1540 :group 'org-structure
1541 :type 'boolean)
1543 (defcustom org-blank-before-new-entry '((heading . auto)
1544 (plain-list-item . auto))
1545 "Should `org-insert-heading' leave a blank line before new heading/item?
1546 The value is an alist, with `heading' and `plain-list-item' as CAR,
1547 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1548 which case Org will look at the surrounding headings/items and try to
1549 make an intelligent decision whether to insert a blank line or not.
1551 For plain lists, if `org-list-empty-line-terminates-plain-lists' is set,
1552 the setting here is ignored and no empty line is inserted to avoid breaking
1553 the list structure."
1554 :group 'org-edit-structure
1555 :type '(list
1556 (cons (const heading)
1557 (choice (const :tag "Never" nil)
1558 (const :tag "Always" t)
1559 (const :tag "Auto" auto)))
1560 (cons (const plain-list-item)
1561 (choice (const :tag "Never" nil)
1562 (const :tag "Always" t)
1563 (const :tag "Auto" auto)))))
1565 (defcustom org-insert-heading-hook nil
1566 "Hook being run after inserting a new heading."
1567 :group 'org-edit-structure
1568 :type 'hook)
1570 (defcustom org-enable-fixed-width-editor t
1571 "Non-nil means lines starting with \":\" are treated as fixed-width.
1572 This currently only means they are never auto-wrapped.
1573 When nil, such lines will be treated like ordinary lines."
1574 :group 'org-edit-structure
1575 :type 'boolean)
1577 (defcustom org-goto-auto-isearch t
1578 "Non-nil means typing characters in `org-goto' starts incremental search.
1579 When nil, you can use these keybindings to navigate the buffer:
1581 q Quit the org-goto interface
1582 n Go to the next visible heading
1583 p Go to the previous visible heading
1584 f Go one heading forward on same level
1585 b Go one heading backward on same level
1586 u Go one heading up"
1587 :group 'org-edit-structure
1588 :type 'boolean)
1590 (defgroup org-sparse-trees nil
1591 "Options concerning sparse trees in Org-mode."
1592 :tag "Org Sparse Trees"
1593 :group 'org-structure)
1595 (defcustom org-highlight-sparse-tree-matches t
1596 "Non-nil means highlight all matches that define a sparse tree.
1597 The highlights will automatically disappear the next time the buffer is
1598 changed by an edit command."
1599 :group 'org-sparse-trees
1600 :type 'boolean)
1602 (defcustom org-remove-highlights-with-change t
1603 "Non-nil means any change to the buffer will remove temporary highlights.
1604 Such highlights are created by `org-occur' and `org-clock-display'.
1605 When nil, `C-c C-c needs to be used to get rid of the highlights.
1606 The highlights created by `org-preview-latex-fragment' always need
1607 `C-c C-c' to be removed."
1608 :group 'org-sparse-trees
1609 :group 'org-time
1610 :type 'boolean)
1613 (defcustom org-occur-hook '(org-first-headline-recenter)
1614 "Hook that is run after `org-occur' has constructed a sparse tree.
1615 This can be used to recenter the window to show as much of the structure
1616 as possible."
1617 :group 'org-sparse-trees
1618 :type 'hook)
1620 (defgroup org-imenu-and-speedbar nil
1621 "Options concerning imenu and speedbar in Org-mode."
1622 :tag "Org Imenu and Speedbar"
1623 :group 'org-structure)
1625 (defcustom org-imenu-depth 2
1626 "The maximum level for Imenu access to Org-mode headlines.
1627 This also applied for speedbar access."
1628 :group 'org-imenu-and-speedbar
1629 :type 'integer)
1631 (defgroup org-table nil
1632 "Options concerning tables in Org-mode."
1633 :tag "Org Table"
1634 :group 'org)
1636 (defcustom org-enable-table-editor 'optimized
1637 "Non-nil means lines starting with \"|\" are handled by the table editor.
1638 When nil, such lines will be treated like ordinary lines.
1640 When equal to the symbol `optimized', the table editor will be optimized to
1641 do the following:
1642 - Automatic overwrite mode in front of whitespace in table fields.
1643 This makes the structure of the table stay in tact as long as the edited
1644 field does not exceed the column width.
1645 - Minimize the number of realigns. Normally, the table is aligned each time
1646 TAB or RET are pressed to move to another field. With optimization this
1647 happens only if changes to a field might have changed the column width.
1648 Optimization requires replacing the functions `self-insert-command',
1649 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1650 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1651 very good at guessing when a re-align will be necessary, but you can always
1652 force one with \\[org-ctrl-c-ctrl-c].
1654 If you would like to use the optimized version in Org-mode, but the
1655 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1657 This variable can be used to turn on and off the table editor during a session,
1658 but in order to toggle optimization, a restart is required.
1660 See also the variable `org-table-auto-blank-field'."
1661 :group 'org-table
1662 :type '(choice
1663 (const :tag "off" nil)
1664 (const :tag "on" t)
1665 (const :tag "on, optimized" optimized)))
1667 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1668 (version<= emacs-version "24.1"))
1669 "Non-nil means cluster self-insert commands for undo when possible.
1670 If this is set, then, like in the Emacs command loop, 20 consecutive
1671 characters will be undone together.
1672 This is configurable, because there is some impact on typing performance."
1673 :group 'org-table
1674 :type 'boolean)
1676 (defcustom org-table-tab-recognizes-table.el t
1677 "Non-nil means TAB will automatically notice a table.el table.
1678 When it sees such a table, it moves point into it and - if necessary -
1679 calls `table-recognize-table'."
1680 :group 'org-table-editing
1681 :type 'boolean)
1683 (defgroup org-link nil
1684 "Options concerning links in Org-mode."
1685 :tag "Org Link"
1686 :group 'org)
1688 (defvar org-link-abbrev-alist-local nil
1689 "Buffer-local version of `org-link-abbrev-alist', which see.
1690 The value of this is taken from the #+LINK lines.")
1691 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1693 (defcustom org-link-abbrev-alist nil
1694 "Alist of link abbreviations.
1695 The car of each element is a string, to be replaced at the start of a link.
1696 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1697 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1699 [[linkkey:tag][description]]
1701 The 'linkkey' must be a word word, starting with a letter, followed
1702 by letters, numbers, '-' or '_'.
1704 If REPLACE is a string, the tag will simply be appended to create the link.
1705 If the string contains \"%s\", the tag will be inserted there. If the string
1706 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1707 at that point (see the function `url-hexify-string'). If the string contains
1708 the specifier \"%(my-function)\", then the custom function `my-function' will
1709 be invoked: this function takes the tag as its only argument and must return
1710 a string.
1712 REPLACE may also be a function that will be called with the tag as the
1713 only argument to create the link, which should be returned as a string.
1715 See the manual for examples."
1716 :group 'org-link
1717 :type '(repeat
1718 (cons
1719 (string :tag "Protocol")
1720 (choice
1721 (string :tag "Format")
1722 (function)))))
1724 (defcustom org-descriptive-links t
1725 "Non-nil means Org will display descriptive links.
1726 E.g. [[http://orgmode.org][Org website]] will be displayed as
1727 \"Org Website\", hiding the link itself and just displaying its
1728 description. When set to `nil', Org will display the full links
1729 literally.
1731 You can interactively set the value of this variable by calling
1732 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1733 :group 'org-link
1734 :type 'boolean)
1736 (defcustom org-link-file-path-type 'adaptive
1737 "How the path name in file links should be stored.
1738 Valid values are:
1740 relative Relative to the current directory, i.e. the directory of the file
1741 into which the link is being inserted.
1742 absolute Absolute path, if possible with ~ for home directory.
1743 noabbrev Absolute path, no abbreviation of home directory.
1744 adaptive Use relative path for files in the current directory and sub-
1745 directories of it. For other files, use an absolute path."
1746 :group 'org-link
1747 :type '(choice
1748 (const relative)
1749 (const absolute)
1750 (const noabbrev)
1751 (const adaptive)))
1753 (defvaralias 'org-activate-links 'org-highlight-links)
1754 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1755 "Types of links that should be highlighted in Org-mode files.
1757 This is a list of symbols, each one of them leading to the
1758 highlighting of a certain link type.
1760 You can still open links that are not highlighted.
1762 In principle, it does not hurt to turn on highlighting for all
1763 link types. There may be a small gain when turning off unused
1764 link types. The types are:
1766 bracket The recommended [[link][description]] or [[link]] links with hiding.
1767 angle Links in angular brackets that may contain whitespace like
1768 <bbdb:Carsten Dominik>.
1769 plain Plain links in normal text, no whitespace, like http://google.com.
1770 radio Text that is matched by a radio target, see manual for details.
1771 tag Tag settings in a headline (link to tag search).
1772 date Time stamps (link to calendar).
1773 footnote Footnote labels.
1775 If you set this variable during an Emacs session, use `org-mode-restart'
1776 in the Org buffer so that the change takes effect."
1777 :group 'org-link
1778 :group 'org-appearance
1779 :type '(set :greedy t
1780 (const :tag "Double bracket links" bracket)
1781 (const :tag "Angular bracket links" angle)
1782 (const :tag "Plain text links" plain)
1783 (const :tag "Radio target matches" radio)
1784 (const :tag "Tags" tag)
1785 (const :tag "Timestamps" date)
1786 (const :tag "Footnotes" footnote)))
1788 (defcustom org-make-link-description-function nil
1789 "Function to use for generating link descriptions from links.
1790 When nil, the link location will be used. This function must take
1791 two parameters: the first one is the link, the second one is the
1792 description generated by `org-insert-link'. The function should
1793 return the description to use."
1794 :group 'org-link
1795 :type '(choice (const nil) (function)))
1797 (defgroup org-link-store nil
1798 "Options concerning storing links in Org-mode."
1799 :tag "Org Store Link"
1800 :group 'org-link)
1802 (defcustom org-url-hexify-p t
1803 "When non-nil, hexify URL when creating a link."
1804 :type 'boolean
1805 :version "24.3"
1806 :group 'org-link-store)
1808 (defcustom org-email-link-description-format "Email %c: %.30s"
1809 "Format of the description part of a link to an email or usenet message.
1810 The following %-escapes will be replaced by corresponding information:
1812 %F full \"From\" field
1813 %f name, taken from \"From\" field, address if no name
1814 %T full \"To\" field
1815 %t first name in \"To\" field, address if no name
1816 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1817 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1818 %s subject
1819 %d date
1820 %m message-id.
1822 You may use normal field width specification between the % and the letter.
1823 This is for example useful to limit the length of the subject.
1825 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1826 :group 'org-link-store
1827 :type 'string)
1829 (defcustom org-from-is-user-regexp
1830 (let (r1 r2)
1831 (when (and user-mail-address (not (string= user-mail-address "")))
1832 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1833 (when (and user-full-name (not (string= user-full-name "")))
1834 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1835 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1836 "Regexp matched against the \"From:\" header of an email or usenet message.
1837 It should match if the message is from the user him/herself."
1838 :group 'org-link-store
1839 :type 'regexp)
1841 (defcustom org-context-in-file-links t
1842 "Non-nil means file links from `org-store-link' contain context.
1843 A search string will be added to the file name with :: as separator and
1844 used to find the context when the link is activated by the command
1845 `org-open-at-point'. When this option is t, the entire active region
1846 will be placed in the search string of the file link. If set to a
1847 positive integer, only the first n lines of context will be stored.
1849 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1850 negates this setting for the duration of the command."
1851 :group 'org-link-store
1852 :type '(choice boolean integer))
1854 (defcustom org-keep-stored-link-after-insertion nil
1855 "Non-nil means keep link in list for entire session.
1857 The command `org-store-link' adds a link pointing to the current
1858 location to an internal list. These links accumulate during a session.
1859 The command `org-insert-link' can be used to insert links into any
1860 Org-mode file (offering completion for all stored links). When this
1861 option is nil, every link which has been inserted once using \\[org-insert-link]
1862 will be removed from the list, to make completing the unused links
1863 more efficient."
1864 :group 'org-link-store
1865 :type 'boolean)
1867 (defgroup org-link-follow nil
1868 "Options concerning following links in Org-mode."
1869 :tag "Org Follow Link"
1870 :group 'org-link)
1872 (defcustom org-link-translation-function nil
1873 "Function to translate links with different syntax to Org syntax.
1874 This can be used to translate links created for example by the Planner
1875 or emacs-wiki packages to Org syntax.
1876 The function must accept two parameters, a TYPE containing the link
1877 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1878 which is everything after the link protocol. It should return a cons
1879 with possibly modified values of type and path.
1880 Org contains a function for this, so if you set this variable to
1881 `org-translate-link-from-planner', you should be able follow many
1882 links created by planner."
1883 :group 'org-link-follow
1884 :type '(choice (const nil) (function)))
1886 (defcustom org-follow-link-hook nil
1887 "Hook that is run after a link has been followed."
1888 :group 'org-link-follow
1889 :type 'hook)
1891 (defcustom org-tab-follows-link nil
1892 "Non-nil means on links TAB will follow the link.
1893 Needs to be set before org.el is loaded.
1894 This really should not be used, it does not make sense, and the
1895 implementation is bad."
1896 :group 'org-link-follow
1897 :type 'boolean)
1899 (defcustom org-return-follows-link nil
1900 "Non-nil means on links RET will follow the link.
1901 In tables, the special behavior of RET has precedence."
1902 :group 'org-link-follow
1903 :type 'boolean)
1905 (defcustom org-mouse-1-follows-link
1906 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1907 "Non-nil means mouse-1 on a link will follow the link.
1908 A longer mouse click will still set point. Does not work on XEmacs.
1909 Needs to be set before org.el is loaded."
1910 :group 'org-link-follow
1911 :version "24.4"
1912 :package-version '(Org . "8.3")
1913 :type '(choice
1914 (const :tag "A double click follows the link" double)
1915 (const :tag "Unconditionally follow the link with mouse-1" t)
1916 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
1918 (defcustom org-mark-ring-length 4
1919 "Number of different positions to be recorded in the ring.
1920 Changing this requires a restart of Emacs to work correctly."
1921 :group 'org-link-follow
1922 :type 'integer)
1924 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1925 "Non-nil means internal links in Org files must exactly match a headline.
1926 When nil, the link search tries to match a phrase with all words
1927 in the search text."
1928 :group 'org-link-follow
1929 :version "24.1"
1930 :type '(choice
1931 (const :tag "Use fuzzy text search" nil)
1932 (const :tag "Match only exact headline" t)
1933 (const :tag "Match exact headline or query to create it"
1934 query-to-create)))
1936 (defcustom org-link-frame-setup
1937 '((vm . vm-visit-folder-other-frame)
1938 (vm-imap . vm-visit-imap-folder-other-frame)
1939 (gnus . org-gnus-no-new-news)
1940 (file . find-file-other-window)
1941 (wl . wl-other-frame))
1942 "Setup the frame configuration for following links.
1943 When following a link with Emacs, it may often be useful to display
1944 this link in another window or frame. This variable can be used to
1945 set this up for the different types of links.
1946 For VM, use any of
1947 `vm-visit-folder'
1948 `vm-visit-folder-other-window'
1949 `vm-visit-folder-other-frame'
1950 For Gnus, use any of
1951 `gnus'
1952 `gnus-other-frame'
1953 `org-gnus-no-new-news'
1954 For FILE, use any of
1955 `find-file'
1956 `find-file-other-window'
1957 `find-file-other-frame'
1958 For Wanderlust use any of
1959 `wl'
1960 `wl-other-frame'
1961 For the calendar, use the variable `calendar-setup'.
1962 For BBDB, it is currently only possible to display the matches in
1963 another window."
1964 :group 'org-link-follow
1965 :type '(list
1966 (cons (const vm)
1967 (choice
1968 (const vm-visit-folder)
1969 (const vm-visit-folder-other-window)
1970 (const vm-visit-folder-other-frame)))
1971 (cons (const vm-imap)
1972 (choice
1973 (const vm-visit-imap-folder)
1974 (const vm-visit-imap-folder-other-window)
1975 (const vm-visit-imap-folder-other-frame)))
1976 (cons (const gnus)
1977 (choice
1978 (const gnus)
1979 (const gnus-other-frame)
1980 (const org-gnus-no-new-news)))
1981 (cons (const file)
1982 (choice
1983 (const find-file)
1984 (const find-file-other-window)
1985 (const find-file-other-frame)))
1986 (cons (const wl)
1987 (choice
1988 (const wl)
1989 (const wl-other-frame)))))
1991 (defcustom org-display-internal-link-with-indirect-buffer nil
1992 "Non-nil means use indirect buffer to display infile links.
1993 Activating internal links (from one location in a file to another location
1994 in the same file) normally just jumps to the location. When the link is
1995 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1996 is displayed in
1997 another window. When this option is set, the other window actually displays
1998 an indirect buffer clone of the current buffer, to avoid any visibility
1999 changes to the current buffer."
2000 :group 'org-link-follow
2001 :type 'boolean)
2003 (defcustom org-open-non-existing-files nil
2004 "Non-nil means `org-open-file' will open non-existing files.
2005 When nil, an error will be generated.
2006 This variable applies only to external applications because they
2007 might choke on non-existing files. If the link is to a file that
2008 will be opened in Emacs, the variable is ignored."
2009 :group 'org-link-follow
2010 :type 'boolean)
2012 (defcustom org-open-directory-means-index-dot-org nil
2013 "Non-nil means a link to a directory really means to index.org.
2014 When nil, following a directory link will run dired or open a finder/explorer
2015 window on that directory."
2016 :group 'org-link-follow
2017 :type 'boolean)
2019 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2020 "Non-nil means ask for confirmation before executing shell links.
2021 Shell links can be dangerous: just think about a link
2023 [[shell:rm -rf ~/*][Google Search]]
2025 This link would show up in your Org-mode document as \"Google Search\",
2026 but really it would remove your entire home directory.
2027 Therefore we advise against setting this variable to nil.
2028 Just change it to `y-or-n-p' if you want to confirm with a
2029 single keystroke rather than having to type \"yes\"."
2030 :group 'org-link-follow
2031 :type '(choice
2032 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2033 (const :tag "with y-or-n (faster)" y-or-n-p)
2034 (const :tag "no confirmation (dangerous)" nil)))
2035 (put 'org-confirm-shell-link-function
2036 'safe-local-variable
2037 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2039 (defcustom org-confirm-shell-link-not-regexp ""
2040 "A regexp to skip confirmation for shell links."
2041 :group 'org-link-follow
2042 :version "24.1"
2043 :type 'regexp)
2045 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2046 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2047 Elisp links can be dangerous: just think about a link
2049 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2051 This link would show up in your Org-mode document as \"Google Search\",
2052 but really it would remove your entire home directory.
2053 Therefore we advise against setting this variable to nil.
2054 Just change it to `y-or-n-p' if you want to confirm with a
2055 single keystroke rather than having to type \"yes\"."
2056 :group 'org-link-follow
2057 :type '(choice
2058 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2059 (const :tag "with y-or-n (faster)" y-or-n-p)
2060 (const :tag "no confirmation (dangerous)" nil)))
2061 (put 'org-confirm-shell-link-function
2062 'safe-local-variable
2063 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2065 (defcustom org-confirm-elisp-link-not-regexp ""
2066 "A regexp to skip confirmation for Elisp links."
2067 :group 'org-link-follow
2068 :version "24.1"
2069 :type 'regexp)
2071 (defconst org-file-apps-defaults-gnu
2072 '((remote . emacs)
2073 (system . mailcap)
2074 (t . mailcap))
2075 "Default file applications on a UNIX or GNU/Linux system.
2076 See `org-file-apps'.")
2078 (defconst org-file-apps-defaults-macosx
2079 '((remote . emacs)
2080 (t . "open %s")
2081 (system . "open %s")
2082 ("ps.gz" . "gv %s")
2083 ("eps.gz" . "gv %s")
2084 ("dvi" . "xdvi %s")
2085 ("fig" . "xfig %s"))
2086 "Default file applications on a MacOS X system.
2087 The system \"open\" is known as a default, but we use X11 applications
2088 for some files for which the OS does not have a good default.
2089 See `org-file-apps'.")
2091 (defconst org-file-apps-defaults-windowsnt
2092 (list
2093 '(remote . emacs)
2094 (cons t
2095 (list (if (featurep 'xemacs)
2096 'mswindows-shell-execute
2097 'w32-shell-execute)
2098 "open" 'file))
2099 (cons 'system
2100 (list (if (featurep 'xemacs)
2101 'mswindows-shell-execute
2102 'w32-shell-execute)
2103 "open" 'file)))
2104 "Default file applications on a Windows NT system.
2105 The system \"open\" is used for most files.
2106 See `org-file-apps'.")
2108 (defcustom org-file-apps
2109 '((auto-mode . emacs)
2110 ("\\.mm\\'" . default)
2111 ("\\.x?html?\\'" . default)
2112 ("\\.pdf\\'" . default))
2113 "External applications for opening `file:path' items in a document.
2114 Org-mode uses system defaults for different file types, but
2115 you can use this variable to set the application for a given file
2116 extension. The entries in this list are cons cells where the car identifies
2117 files and the cdr the corresponding command. Possible values for the
2118 file identifier are
2119 \"string\" A string as a file identifier can be interpreted in different
2120 ways, depending on its contents:
2122 - Alphanumeric characters only:
2123 Match links with this file extension.
2124 Example: (\"pdf\" . \"evince %s\")
2125 to open PDFs with evince.
2127 - Regular expression: Match links where the
2128 filename matches the regexp. If you want to
2129 use groups here, use shy groups.
2131 Example: (\"\\.x?html\\'\" . \"firefox %s\")
2132 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
2133 to open *.html and *.xhtml with firefox.
2135 - Regular expression which contains (non-shy) groups:
2136 Match links where the whole link, including \"::\", and
2137 anything after that, matches the regexp.
2138 In a custom command string, %1, %2, etc. are replaced with
2139 the parts of the link that were matched by the groups.
2140 For backwards compatibility, if a command string is given
2141 that does not use any of the group matches, this case is
2142 handled identically to the second one (i.e. match against
2143 file name only).
2144 In a custom lisp form, you can access the group matches with
2145 (match-string n link).
2147 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
2148 to open [[file:document.pdf::5]] with evince at page 5.
2150 `directory' Matches a directory
2151 `remote' Matches a remote file, accessible through tramp or efs.
2152 Remote files most likely should be visited through Emacs
2153 because external applications cannot handle such paths.
2154 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2155 so all files Emacs knows how to handle. Using this with
2156 command `emacs' will open most files in Emacs. Beware that this
2157 will also open html files inside Emacs, unless you add
2158 (\"html\" . default) to the list as well.
2159 t Default for files not matched by any of the other options.
2160 `system' The system command to open files, like `open' on Windows
2161 and Mac OS X, and mailcap under GNU/Linux. This is the command
2162 that will be selected if you call `C-c C-o' with a double
2163 \\[universal-argument] \\[universal-argument] prefix.
2165 Possible values for the command are:
2166 `emacs' The file will be visited by the current Emacs process.
2167 `default' Use the default application for this file type, which is the
2168 association for t in the list, most likely in the system-specific
2169 part.
2170 This can be used to overrule an unwanted setting in the
2171 system-specific variable.
2172 `system' Use the system command for opening files, like \"open\".
2173 This command is specified by the entry whose car is `system'.
2174 Most likely, the system-specific version of this variable
2175 does define this command, but you can overrule/replace it
2176 here.
2177 string A command to be executed by a shell; %s will be replaced
2178 by the path to the file.
2179 sexp A Lisp form which will be evaluated. The file path will
2180 be available in the Lisp variable `file'.
2181 For more examples, see the system specific constants
2182 `org-file-apps-defaults-macosx'
2183 `org-file-apps-defaults-windowsnt'
2184 `org-file-apps-defaults-gnu'."
2185 :group 'org-link-follow
2186 :type '(repeat
2187 (cons (choice :value ""
2188 (string :tag "Extension")
2189 (const :tag "System command to open files" system)
2190 (const :tag "Default for unrecognized files" t)
2191 (const :tag "Remote file" remote)
2192 (const :tag "Links to a directory" directory)
2193 (const :tag "Any files that have Emacs modes"
2194 auto-mode))
2195 (choice :value ""
2196 (const :tag "Visit with Emacs" emacs)
2197 (const :tag "Use default" default)
2198 (const :tag "Use the system command" system)
2199 (string :tag "Command")
2200 (sexp :tag "Lisp form")))))
2202 (defcustom org-doi-server-url "http://dx.doi.org/"
2203 "The URL of the DOI server."
2204 :type 'string
2205 :version "24.3"
2206 :group 'org-link-follow)
2208 (defgroup org-refile nil
2209 "Options concerning refiling entries in Org-mode."
2210 :tag "Org Refile"
2211 :group 'org)
2213 (defcustom org-directory "~/org"
2214 "Directory with org files.
2215 This is just a default location to look for Org files. There is no need
2216 at all to put your files into this directory. It is only used in the
2217 following situations:
2219 1. When a capture template specifies a target file that is not an
2220 absolute path. The path will then be interpreted relative to
2221 `org-directory'
2222 2. When a capture note is filed away in an interactive way (when exiting the
2223 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2224 with `org-directory' as the default path."
2225 :group 'org-refile
2226 :group 'org-capture
2227 :type 'directory)
2229 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2230 "Default target for storing notes.
2231 Used as a fall back file for org-capture.el, for templates that
2232 do not specify a target file."
2233 :group 'org-refile
2234 :group 'org-capture
2235 :type '(choice
2236 (const :tag "Default from remember-data-file" nil)
2237 file))
2239 (defcustom org-goto-interface 'outline
2240 "The default interface to be used for `org-goto'.
2241 Allowed values are:
2242 outline The interface shows an outline of the relevant file
2243 and the correct heading is found by moving through
2244 the outline or by searching with incremental search.
2245 outline-path-completion Headlines in the current buffer are offered via
2246 completion. This is the interface also used by
2247 the refile command."
2248 :group 'org-refile
2249 :type '(choice
2250 (const :tag "Outline" outline)
2251 (const :tag "Outline-path-completion" outline-path-completion)))
2253 (defcustom org-goto-max-level 5
2254 "Maximum target level when running `org-goto' with refile interface."
2255 :group 'org-refile
2256 :type 'integer)
2258 (defcustom org-reverse-note-order nil
2259 "Non-nil means store new notes at the beginning of a file or entry.
2260 When nil, new notes will be filed to the end of a file or entry.
2261 This can also be a list with cons cells of regular expressions that
2262 are matched against file names, and values."
2263 :group 'org-capture
2264 :group 'org-refile
2265 :type '(choice
2266 (const :tag "Reverse always" t)
2267 (const :tag "Reverse never" nil)
2268 (repeat :tag "By file name regexp"
2269 (cons regexp boolean))))
2271 (defcustom org-log-refile nil
2272 "Information to record when a task is refiled.
2274 Possible values are:
2276 nil Don't add anything
2277 time Add a time stamp to the task
2278 note Prompt for a note and add it with template `org-log-note-headings'
2280 This option can also be set with on a per-file-basis with
2282 #+STARTUP: nologrefile
2283 #+STARTUP: logrefile
2284 #+STARTUP: lognoterefile
2286 You can have local logging settings for a subtree by setting the LOGGING
2287 property to one or more of these keywords.
2289 When bulk-refiling from the agenda, the value `note' is forbidden and
2290 will temporarily be changed to `time'."
2291 :group 'org-refile
2292 :group 'org-progress
2293 :version "24.1"
2294 :type '(choice
2295 (const :tag "No logging" nil)
2296 (const :tag "Record timestamp" time)
2297 (const :tag "Record timestamp with note." note)))
2299 (defcustom org-refile-targets nil
2300 "Targets for refiling entries with \\[org-refile].
2301 This is a list of cons cells. Each cell contains:
2302 - a specification of the files to be considered, either a list of files,
2303 or a symbol whose function or variable value will be used to retrieve
2304 a file name or a list of file names. If you use `org-agenda-files' for
2305 that, all agenda files will be scanned for targets. Nil means consider
2306 headings in the current buffer.
2307 - A specification of how to find candidate refile targets. This may be
2308 any of:
2309 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2310 This tag has to be present in all target headlines, inheritance will
2311 not be considered.
2312 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2313 todo keyword.
2314 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2315 headlines that are refiling targets.
2316 - a cons cell (:level . N). Any headline of level N is considered a target.
2317 Note that, when `org-odd-levels-only' is set, level corresponds to
2318 order in hierarchy, not to the number of stars.
2319 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2320 Note that, when `org-odd-levels-only' is set, level corresponds to
2321 order in hierarchy, not to the number of stars.
2323 Each element of this list generates a set of possible targets.
2324 The union of these sets is presented (with completion) to
2325 the user by `org-refile'.
2327 You can set the variable `org-refile-target-verify-function' to a function
2328 to verify each headline found by the simple criteria above.
2330 When this variable is nil, all top-level headlines in the current buffer
2331 are used, equivalent to the value `((nil . (:level . 1))'."
2332 :group 'org-refile
2333 :type '(repeat
2334 (cons
2335 (choice :value org-agenda-files
2336 (const :tag "All agenda files" org-agenda-files)
2337 (const :tag "Current buffer" nil)
2338 (function) (variable) (file))
2339 (choice :tag "Identify target headline by"
2340 (cons :tag "Specific tag" (const :value :tag) (string))
2341 (cons :tag "TODO keyword" (const :value :todo) (string))
2342 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2343 (cons :tag "Level number" (const :value :level) (integer))
2344 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2346 (defcustom org-refile-target-verify-function nil
2347 "Function to verify if the headline at point should be a refile target.
2348 The function will be called without arguments, with point at the
2349 beginning of the headline. It should return t and leave point
2350 where it is if the headline is a valid target for refiling.
2352 If the target should not be selected, the function must return nil.
2353 In addition to this, it may move point to a place from where the search
2354 should be continued. For example, the function may decide that the entire
2355 subtree of the current entry should be excluded and move point to the end
2356 of the subtree."
2357 :group 'org-refile
2358 :type '(choice
2359 (const nil)
2360 (function)))
2362 (defcustom org-refile-use-cache nil
2363 "Non-nil means cache refile targets to speed up the process.
2364 The cache for a particular file will be updated automatically when
2365 the buffer has been killed, or when any of the marker used for flagging
2366 refile targets no longer points at a live buffer.
2367 If you have added new entries to a buffer that might themselves be targets,
2368 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2369 find that easier, `C-u C-u C-u C-c C-w'."
2370 :group 'org-refile
2371 :version "24.1"
2372 :type 'boolean)
2374 (defcustom org-refile-use-outline-path nil
2375 "Non-nil means provide refile targets as paths.
2376 So a level 3 headline will be available as level1/level2/level3.
2378 When the value is `file', also include the file name (without directory)
2379 into the path. In this case, you can also stop the completion after
2380 the file name, to get entries inserted as top level in the file.
2382 When `full-file-path', include the full file path."
2383 :group 'org-refile
2384 :type '(choice
2385 (const :tag "Not" nil)
2386 (const :tag "Yes" t)
2387 (const :tag "Start with file name" file)
2388 (const :tag "Start with full file path" full-file-path)))
2390 (defcustom org-outline-path-complete-in-steps t
2391 "Non-nil means complete the outline path in hierarchical steps.
2392 When Org-mode uses the refile interface to select an outline path
2393 \(see variable `org-refile-use-outline-path'), the completion of
2394 the path can be done is a single go, or if can be done in steps down
2395 the headline hierarchy. Going in steps is probably the best if you
2396 do not use a special completion package like `ido' or `icicles'.
2397 However, when using these packages, going in one step can be very
2398 fast, while still showing the whole path to the entry."
2399 :group 'org-refile
2400 :type 'boolean)
2402 (defcustom org-refile-allow-creating-parent-nodes nil
2403 "Non-nil means allow to create new nodes as refile targets.
2404 New nodes are then created by adding \"/new node name\" to the completion
2405 of an existing node. When the value of this variable is `confirm',
2406 new node creation must be confirmed by the user (recommended).
2407 When nil, the completion must match an existing entry.
2409 Note that, if the new heading is not seen by the criteria
2410 listed in `org-refile-targets', multiple instances of the same
2411 heading would be created by trying again to file under the new
2412 heading."
2413 :group 'org-refile
2414 :type '(choice
2415 (const :tag "Never" nil)
2416 (const :tag "Always" t)
2417 (const :tag "Prompt for confirmation" confirm)))
2419 (defcustom org-refile-active-region-within-subtree nil
2420 "Non-nil means also refile active region within a subtree.
2422 By default `org-refile' doesn't allow refiling regions if they
2423 don't contain a set of subtrees, but it might be convenient to
2424 do so sometimes: in that case, the first line of the region is
2425 converted to a headline before refiling."
2426 :group 'org-refile
2427 :version "24.1"
2428 :type 'boolean)
2430 (defgroup org-todo nil
2431 "Options concerning TODO items in Org-mode."
2432 :tag "Org TODO"
2433 :group 'org)
2435 (defgroup org-progress nil
2436 "Options concerning Progress logging in Org-mode."
2437 :tag "Org Progress"
2438 :group 'org-time)
2440 (defvar org-todo-interpretation-widgets
2441 '((:tag "Sequence (cycling hits every state)" sequence)
2442 (:tag "Type (cycling directly to DONE)" type))
2443 "The available interpretation symbols for customizing `org-todo-keywords'.
2444 Interested libraries should add to this list.")
2446 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2447 "List of TODO entry keyword sequences and their interpretation.
2448 \\<org-mode-map>This is a list of sequences.
2450 Each sequence starts with a symbol, either `sequence' or `type',
2451 indicating if the keywords should be interpreted as a sequence of
2452 action steps, or as different types of TODO items. The first
2453 keywords are states requiring action - these states will select a headline
2454 for inclusion into the global TODO list Org-mode produces. If one of
2455 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2456 signify that no further action is necessary. If \"|\" is not found,
2457 the last keyword is treated as the only DONE state of the sequence.
2459 The command \\[org-todo] cycles an entry through these states, and one
2460 additional state where no keyword is present. For details about this
2461 cycling, see the manual.
2463 TODO keywords and interpretation can also be set on a per-file basis with
2464 the special #+SEQ_TODO and #+TYP_TODO lines.
2466 Each keyword can optionally specify a character for fast state selection
2467 \(in combination with the variable `org-use-fast-todo-selection')
2468 and specifiers for state change logging, using the same syntax that
2469 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2470 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2471 indicates to record a time stamp each time this state is selected.
2473 Each keyword may also specify if a timestamp or a note should be
2474 recorded when entering or leaving the state, by adding additional
2475 characters in the parenthesis after the keyword. This looks like this:
2476 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2477 record only the time of the state change. With X and Y being either
2478 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2479 Y when leaving the state if and only if the *target* state does not
2480 define X. You may omit any of the fast-selection key or X or /Y,
2481 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2483 For backward compatibility, this variable may also be just a list
2484 of keywords. In this case the interpretation (sequence or type) will be
2485 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2486 :group 'org-todo
2487 :group 'org-keywords
2488 :type '(choice
2489 (repeat :tag "Old syntax, just keywords"
2490 (string :tag "Keyword"))
2491 (repeat :tag "New syntax"
2492 (cons
2493 (choice
2494 :tag "Interpretation"
2495 ;;Quick and dirty way to see
2496 ;;`org-todo-interpretations'. This takes the
2497 ;;place of item arguments
2498 :convert-widget
2499 (lambda (widget)
2500 (widget-put widget
2501 :args (mapcar
2502 (lambda (x)
2503 (widget-convert
2504 (cons 'const x)))
2505 org-todo-interpretation-widgets))
2506 widget))
2507 (repeat
2508 (string :tag "Keyword"))))))
2510 (defvar org-todo-keywords-1 nil
2511 "All TODO and DONE keywords active in a buffer.")
2512 (make-variable-buffer-local 'org-todo-keywords-1)
2513 (defvar org-todo-keywords-for-agenda nil)
2514 (defvar org-done-keywords-for-agenda nil)
2515 (defvar org-todo-keyword-alist-for-agenda nil)
2516 (defvar org-tag-alist-for-agenda nil
2517 "Alist of all tags from all agenda files.")
2518 (defvar org-tag-groups-alist-for-agenda nil
2519 "Alist of all groups tags from all current agenda files.")
2520 (defvar org-tag-groups-alist nil)
2521 (make-variable-buffer-local 'org-tag-groups-alist)
2522 (defvar org-agenda-contributing-files nil)
2523 (defvar org-not-done-keywords nil)
2524 (make-variable-buffer-local 'org-not-done-keywords)
2525 (defvar org-done-keywords nil)
2526 (make-variable-buffer-local 'org-done-keywords)
2527 (defvar org-todo-heads nil)
2528 (make-variable-buffer-local 'org-todo-heads)
2529 (defvar org-todo-sets nil)
2530 (make-variable-buffer-local 'org-todo-sets)
2531 (defvar org-todo-log-states nil)
2532 (make-variable-buffer-local 'org-todo-log-states)
2533 (defvar org-todo-kwd-alist nil)
2534 (make-variable-buffer-local 'org-todo-kwd-alist)
2535 (defvar org-todo-key-alist nil)
2536 (make-variable-buffer-local 'org-todo-key-alist)
2537 (defvar org-todo-key-trigger nil)
2538 (make-variable-buffer-local 'org-todo-key-trigger)
2540 (defcustom org-todo-interpretation 'sequence
2541 "Controls how TODO keywords are interpreted.
2542 This variable is in principle obsolete and is only used for
2543 backward compatibility, if the interpretation of todo keywords is
2544 not given already in `org-todo-keywords'. See that variable for
2545 more information."
2546 :group 'org-todo
2547 :group 'org-keywords
2548 :type '(choice (const sequence)
2549 (const type)))
2551 (defcustom org-use-fast-todo-selection t
2552 "Non-nil means use the fast todo selection scheme with C-c C-t.
2553 This variable describes if and under what circumstances the cycling
2554 mechanism for TODO keywords will be replaced by a single-key, direct
2555 selection scheme.
2557 When nil, fast selection is never used.
2559 When the symbol `prefix', it will be used when `org-todo' is called
2560 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2561 `C-u t' in an agenda buffer.
2563 When t, fast selection is used by default. In this case, the prefix
2564 argument forces cycling instead.
2566 In all cases, the special interface is only used if access keys have
2567 actually been assigned by the user, i.e. if keywords in the configuration
2568 are followed by a letter in parenthesis, like TODO(t)."
2569 :group 'org-todo
2570 :type '(choice
2571 (const :tag "Never" nil)
2572 (const :tag "By default" t)
2573 (const :tag "Only with C-u C-c C-t" prefix)))
2575 (defcustom org-provide-todo-statistics t
2576 "Non-nil means update todo statistics after insert and toggle.
2577 ALL-HEADLINES means update todo statistics by including headlines
2578 with no TODO keyword as well, counting them as not done.
2579 A list of TODO keywords means the same, but skip keywords that are
2580 not in this list.
2581 When set to a list of two lists, the first list contains keywords
2582 to consider as TODO keywords, the second list contains keywords
2583 to consider as DONE keywords.
2585 When this is set, todo statistics is updated in the parent of the
2586 current entry each time a todo state is changed."
2587 :group 'org-todo
2588 :type '(choice
2589 (const :tag "Yes, only for TODO entries" t)
2590 (const :tag "Yes, including all entries" all-headlines)
2591 (repeat :tag "Yes, for TODOs in this list"
2592 (string :tag "TODO keyword"))
2593 (list :tag "Yes, for TODOs and DONEs in these lists"
2594 (repeat (string :tag "TODO keyword"))
2595 (repeat (string :tag "DONE keyword")))
2596 (other :tag "No TODO statistics" nil)))
2598 (defcustom org-hierarchical-todo-statistics t
2599 "Non-nil means TODO statistics covers just direct children.
2600 When nil, all entries in the subtree are considered.
2601 This has only an effect if `org-provide-todo-statistics' is set.
2602 To set this to nil for only a single subtree, use a COOKIE_DATA
2603 property and include the word \"recursive\" into the value."
2604 :group 'org-todo
2605 :type 'boolean)
2607 (defcustom org-after-todo-state-change-hook nil
2608 "Hook which is run after the state of a TODO item was changed.
2609 The new state (a string with a TODO keyword, or nil) is available in the
2610 Lisp variable `org-state'."
2611 :group 'org-todo
2612 :type 'hook)
2614 (defvar org-blocker-hook nil
2615 "Hook for functions that are allowed to block a state change.
2617 Functions in this hook should not modify the buffer.
2618 Each function gets as its single argument a property list,
2619 see `org-trigger-hook' for more information about this list.
2621 If any of the functions in this hook returns nil, the state change
2622 is blocked.")
2624 (defvar org-trigger-hook nil
2625 "Hook for functions that are triggered by a state change.
2627 Each function gets as its single argument a property list with at
2628 least the following elements:
2630 (:type type-of-change :position pos-at-entry-start
2631 :from old-state :to new-state)
2633 Depending on the type, more properties may be present.
2635 This mechanism is currently implemented for:
2637 TODO state changes
2638 ------------------
2639 :type todo-state-change
2640 :from previous state (keyword as a string), or nil, or a symbol
2641 'todo' or 'done', to indicate the general type of state.
2642 :to new state, like in :from")
2644 (defcustom org-enforce-todo-dependencies nil
2645 "Non-nil means undone TODO entries will block switching the parent to DONE.
2646 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2647 be blocked if any prior sibling is not yet done.
2648 Finally, if the parent is blocked because of ordered siblings of its own,
2649 the child will also be blocked."
2650 :set (lambda (var val)
2651 (set var val)
2652 (if val
2653 (add-hook 'org-blocker-hook
2654 'org-block-todo-from-children-or-siblings-or-parent)
2655 (remove-hook 'org-blocker-hook
2656 'org-block-todo-from-children-or-siblings-or-parent)))
2657 :group 'org-todo
2658 :type 'boolean)
2660 (defcustom org-enforce-todo-checkbox-dependencies nil
2661 "Non-nil means unchecked boxes will block switching the parent to DONE.
2662 When this is nil, checkboxes have no influence on switching TODO states.
2663 When non-nil, you first need to check off all check boxes before the TODO
2664 entry can be switched to DONE.
2665 This variable needs to be set before org.el is loaded, and you need to
2666 restart Emacs after a change to make the change effective. The only way
2667 to change is while Emacs is running is through the customize interface."
2668 :set (lambda (var val)
2669 (set var val)
2670 (if val
2671 (add-hook 'org-blocker-hook
2672 'org-block-todo-from-checkboxes)
2673 (remove-hook 'org-blocker-hook
2674 'org-block-todo-from-checkboxes)))
2675 :group 'org-todo
2676 :type 'boolean)
2678 (defcustom org-treat-insert-todo-heading-as-state-change nil
2679 "Non-nil means inserting a TODO heading is treated as state change.
2680 So when the command \\[org-insert-todo-heading] is used, state change
2681 logging will apply if appropriate. When nil, the new TODO item will
2682 be inserted directly, and no logging will take place."
2683 :group 'org-todo
2684 :type 'boolean)
2686 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2687 "Non-nil means switching TODO states with S-cursor counts as state change.
2688 This is the default behavior. However, setting this to nil allows a
2689 convenient way to select a TODO state and bypass any logging associated
2690 with that."
2691 :group 'org-todo
2692 :type 'boolean)
2694 (defcustom org-todo-state-tags-triggers nil
2695 "Tag changes that should be triggered by TODO state changes.
2696 This is a list. Each entry is
2698 (state-change (tag . flag) .......)
2700 State-change can be a string with a state, and empty string to indicate the
2701 state that has no TODO keyword, or it can be one of the symbols `todo'
2702 or `done', meaning any not-done or done state, respectively."
2703 :group 'org-todo
2704 :group 'org-tags
2705 :type '(repeat
2706 (cons (choice :tag "When changing to"
2707 (const :tag "Not-done state" todo)
2708 (const :tag "Done state" done)
2709 (string :tag "State"))
2710 (repeat
2711 (cons :tag "Tag action"
2712 (string :tag "Tag")
2713 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2715 (defcustom org-log-done nil
2716 "Information to record when a task moves to the DONE state.
2718 Possible values are:
2720 nil Don't add anything, just change the keyword
2721 time Add a time stamp to the task
2722 note Prompt for a note and add it with template `org-log-note-headings'
2724 This option can also be set with on a per-file-basis with
2726 #+STARTUP: nologdone
2727 #+STARTUP: logdone
2728 #+STARTUP: lognotedone
2730 You can have local logging settings for a subtree by setting the LOGGING
2731 property to one or more of these keywords."
2732 :group 'org-todo
2733 :group 'org-progress
2734 :type '(choice
2735 (const :tag "No logging" nil)
2736 (const :tag "Record CLOSED timestamp" time)
2737 (const :tag "Record CLOSED timestamp with note." note)))
2739 ;; Normalize old uses of org-log-done.
2740 (cond
2741 ((eq org-log-done t) (setq org-log-done 'time))
2742 ((and (listp org-log-done) (memq 'done org-log-done))
2743 (setq org-log-done 'note)))
2745 (defcustom org-log-reschedule nil
2746 "Information to record when the scheduling date of a tasks is modified.
2748 Possible values are:
2750 nil Don't add anything, just change the date
2751 time Add a time stamp to the task
2752 note Prompt for a note and add it with template `org-log-note-headings'
2754 This option can also be set with on a per-file-basis with
2756 #+STARTUP: nologreschedule
2757 #+STARTUP: logreschedule
2758 #+STARTUP: lognotereschedule"
2759 :group 'org-todo
2760 :group 'org-progress
2761 :type '(choice
2762 (const :tag "No logging" nil)
2763 (const :tag "Record timestamp" time)
2764 (const :tag "Record timestamp with note." note)))
2766 (defcustom org-log-redeadline nil
2767 "Information to record when the deadline date of a tasks is modified.
2769 Possible values are:
2771 nil Don't add anything, just change the date
2772 time Add a time stamp to the task
2773 note Prompt for a note and add it with template `org-log-note-headings'
2775 This option can also be set with on a per-file-basis with
2777 #+STARTUP: nologredeadline
2778 #+STARTUP: logredeadline
2779 #+STARTUP: lognoteredeadline
2781 You can have local logging settings for a subtree by setting the LOGGING
2782 property to one or more of these keywords."
2783 :group 'org-todo
2784 :group 'org-progress
2785 :type '(choice
2786 (const :tag "No logging" nil)
2787 (const :tag "Record timestamp" time)
2788 (const :tag "Record timestamp with note." note)))
2790 (defcustom org-log-note-clock-out nil
2791 "Non-nil means record a note when clocking out of an item.
2792 This can also be configured on a per-file basis by adding one of
2793 the following lines anywhere in the buffer:
2795 #+STARTUP: lognoteclock-out
2796 #+STARTUP: nolognoteclock-out"
2797 :group 'org-todo
2798 :group 'org-progress
2799 :type 'boolean)
2801 (defcustom org-log-done-with-time t
2802 "Non-nil means the CLOSED time stamp will contain date and time.
2803 When nil, only the date will be recorded."
2804 :group 'org-progress
2805 :type 'boolean)
2807 (defcustom org-log-note-headings
2808 '((done . "CLOSING NOTE %t")
2809 (state . "State %-12s from %-12S %t")
2810 (note . "Note taken on %t")
2811 (reschedule . "Rescheduled from %S on %t")
2812 (delschedule . "Not scheduled, was %S on %t")
2813 (redeadline . "New deadline from %S on %t")
2814 (deldeadline . "Removed deadline, was %S on %t")
2815 (refile . "Refiled on %t")
2816 (clock-out . ""))
2817 "Headings for notes added to entries.
2818 The value is an alist, with the car being a symbol indicating the note
2819 context, and the cdr is the heading to be used. The heading may also be the
2820 empty string.
2821 %t in the heading will be replaced by a time stamp.
2822 %T will be an active time stamp instead the default inactive one
2823 %d will be replaced by a short-format time stamp.
2824 %D will be replaced by an active short-format time stamp.
2825 %s will be replaced by the new TODO state, in double quotes.
2826 %S will be replaced by the old TODO state, in double quotes.
2827 %u will be replaced by the user name.
2828 %U will be replaced by the full user name.
2830 In fact, it is not a good idea to change the `state' entry, because
2831 agenda log mode depends on the format of these entries."
2832 :group 'org-todo
2833 :group 'org-progress
2834 :type '(list :greedy t
2835 (cons (const :tag "Heading when closing an item" done) string)
2836 (cons (const :tag
2837 "Heading when changing todo state (todo sequence only)"
2838 state) string)
2839 (cons (const :tag "Heading when just taking a note" note) string)
2840 (cons (const :tag "Heading when rescheduling" reschedule) string)
2841 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2842 (cons (const :tag "Heading when changing deadline" redeadline) string)
2843 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2844 (cons (const :tag "Heading when refiling" refile) string)
2845 (cons (const :tag "Heading when clocking out" clock-out) string)))
2847 (unless (assq 'note org-log-note-headings)
2848 (push '(note . "%t") org-log-note-headings))
2850 (defcustom org-log-into-drawer nil
2851 "Non-nil means insert state change notes and time stamps into a drawer.
2852 When nil, state changes notes will be inserted after the headline and
2853 any scheduling and clock lines, but not inside a drawer.
2855 The value of this variable should be the name of the drawer to use.
2856 LOGBOOK is proposed as the default drawer for this purpose, you can
2857 also set this to a string to define the drawer of your choice.
2859 A value of t is also allowed, representing \"LOGBOOK\".
2861 A value of t or nil can also be set with on a per-file-basis with
2863 #+STARTUP: logdrawer
2864 #+STARTUP: nologdrawer
2866 If this variable is set, `org-log-state-notes-insert-after-drawers'
2867 will be ignored.
2869 You can set the property LOG_INTO_DRAWER to overrule this setting for
2870 a subtree."
2871 :group 'org-todo
2872 :group 'org-progress
2873 :type '(choice
2874 (const :tag "Not into a drawer" nil)
2875 (const :tag "LOGBOOK" t)
2876 (string :tag "Other")))
2878 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2880 (defun org-log-into-drawer ()
2881 "Return the value of `org-log-into-drawer', but let properties overrule.
2882 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2883 used instead of the default value."
2884 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2885 (cond
2886 ((not p) org-log-into-drawer)
2887 ((equal p "nil") nil)
2888 ((equal p "t") "LOGBOOK")
2889 (t p))))
2891 (defcustom org-log-state-notes-insert-after-drawers nil
2892 "Non-nil means insert state change notes after any drawers in entry.
2893 Only the drawers that *immediately* follow the headline and the
2894 deadline/scheduled line are skipped.
2895 When nil, insert notes right after the heading and perhaps the line
2896 with deadline/scheduling if present.
2898 This variable will have no effect if `org-log-into-drawer' is
2899 set."
2900 :group 'org-todo
2901 :group 'org-progress
2902 :type 'boolean)
2904 (defcustom org-log-states-order-reversed t
2905 "Non-nil means the latest state note will be directly after heading.
2906 When nil, the state change notes will be ordered according to time.
2908 This option can also be set with on a per-file-basis with
2910 #+STARTUP: logstatesreversed
2911 #+STARTUP: nologstatesreversed"
2912 :group 'org-todo
2913 :group 'org-progress
2914 :type 'boolean)
2916 (defcustom org-todo-repeat-to-state nil
2917 "The TODO state to which a repeater should return the repeating task.
2918 By default this is the first task in a TODO sequence, or the previous state
2919 in a TODO_TYP set. But you can specify another task here.
2920 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2921 :group 'org-todo
2922 :version "24.1"
2923 :type '(choice (const :tag "Head of sequence" nil)
2924 (string :tag "Specific state")))
2926 (defcustom org-log-repeat 'time
2927 "Non-nil means record moving through the DONE state when triggering repeat.
2928 An auto-repeating task is immediately switched back to TODO when
2929 marked DONE. If you are not logging state changes (by adding \"@\"
2930 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2931 record a closing note, there will be no record of the task moving
2932 through DONE. This variable forces taking a note anyway.
2934 nil Don't force a record
2935 time Record a time stamp
2936 note Prompt for a note and add it with template `org-log-note-headings'
2938 This option can also be set with on a per-file-basis with
2940 #+STARTUP: nologrepeat
2941 #+STARTUP: logrepeat
2942 #+STARTUP: lognoterepeat
2944 You can have local logging settings for a subtree by setting the LOGGING
2945 property to one or more of these keywords."
2946 :group 'org-todo
2947 :group 'org-progress
2948 :type '(choice
2949 (const :tag "Don't force a record" nil)
2950 (const :tag "Force recording the DONE state" time)
2951 (const :tag "Force recording a note with the DONE state" note)))
2954 (defgroup org-priorities nil
2955 "Priorities in Org-mode."
2956 :tag "Org Priorities"
2957 :group 'org-todo)
2959 (defcustom org-enable-priority-commands t
2960 "Non-nil means priority commands are active.
2961 When nil, these commands will be disabled, so that you never accidentally
2962 set a priority."
2963 :group 'org-priorities
2964 :type 'boolean)
2966 (defcustom org-highest-priority ?A
2967 "The highest priority of TODO items. A character like ?A, ?B etc.
2968 Must have a smaller ASCII number than `org-lowest-priority'."
2969 :group 'org-priorities
2970 :type 'character)
2972 (defcustom org-lowest-priority ?C
2973 "The lowest priority of TODO items. A character like ?A, ?B etc.
2974 Must have a larger ASCII number than `org-highest-priority'."
2975 :group 'org-priorities
2976 :type 'character)
2978 (defcustom org-default-priority ?B
2979 "The default priority of TODO items.
2980 This is the priority an item gets if no explicit priority is given.
2981 When starting to cycle on an empty priority the first step in the cycle
2982 depends on `org-priority-start-cycle-with-default'. The resulting first
2983 step priority must not exceed the range from `org-highest-priority' to
2984 `org-lowest-priority' which means that `org-default-priority' has to be
2985 in this range exclusive or inclusive the range boundaries. Else the
2986 first step refuses to set the default and the second will fall back
2987 to (depending on the command used) the highest or lowest priority."
2988 :group 'org-priorities
2989 :type 'character)
2991 (defcustom org-priority-start-cycle-with-default t
2992 "Non-nil means start with default priority when starting to cycle.
2993 When this is nil, the first step in the cycle will be (depending on the
2994 command used) one higher or lower than the default priority.
2995 See also `org-default-priority'."
2996 :group 'org-priorities
2997 :type 'boolean)
2999 (defcustom org-get-priority-function nil
3000 "Function to extract the priority from a string.
3001 The string is normally the headline. If this is nil Org computes the
3002 priority from the priority cookie like [#A] in the headline. It returns
3003 an integer, increasing by 1000 for each priority level.
3004 The user can set a different function here, which should take a string
3005 as an argument and return the numeric priority."
3006 :group 'org-priorities
3007 :version "24.1"
3008 :type '(choice
3009 (const nil)
3010 (function)))
3012 (defgroup org-time nil
3013 "Options concerning time stamps and deadlines in Org-mode."
3014 :tag "Org Time"
3015 :group 'org)
3017 (defcustom org-insert-labeled-timestamps-at-point nil
3018 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
3019 When nil, these labeled time stamps are forces into the second line of an
3020 entry, just after the headline. When scheduling from the global TODO list,
3021 the time stamp will always be forced into the second line."
3022 :group 'org-time
3023 :type 'boolean)
3025 (defcustom org-time-stamp-rounding-minutes '(0 5)
3026 "Number of minutes to round time stamps to.
3027 These are two values, the first applies when first creating a time stamp.
3028 The second applies when changing it with the commands `S-up' and `S-down'.
3029 When changing the time stamp, this means that it will change in steps
3030 of N minutes, as given by the second value.
3032 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3033 numbers should be factors of 60, so for example 5, 10, 15.
3035 When this is larger than 1, you can still force an exact time stamp by using
3036 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
3037 and by using a prefix arg to `S-up/down' to specify the exact number
3038 of minutes to shift."
3039 :group 'org-time
3040 :get (lambda (var) ; Make sure both elements are there
3041 (if (integerp (default-value var))
3042 (list (default-value var) 5)
3043 (default-value var)))
3044 :type '(list
3045 (integer :tag "when inserting times")
3046 (integer :tag "when modifying times")))
3048 ;; Normalize old customizations of this variable.
3049 (when (integerp org-time-stamp-rounding-minutes)
3050 (setq org-time-stamp-rounding-minutes
3051 (list org-time-stamp-rounding-minutes
3052 org-time-stamp-rounding-minutes)))
3054 (defcustom org-display-custom-times nil
3055 "Non-nil means overlay custom formats over all time stamps.
3056 The formats are defined through the variable `org-time-stamp-custom-formats'.
3057 To turn this on on a per-file basis, insert anywhere in the file:
3058 #+STARTUP: customtime"
3059 :group 'org-time
3060 :set 'set-default
3061 :type 'sexp)
3062 (make-variable-buffer-local 'org-display-custom-times)
3064 (defcustom org-time-stamp-custom-formats
3065 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3066 "Custom formats for time stamps. See `format-time-string' for the syntax.
3067 These are overlaid over the default ISO format if the variable
3068 `org-display-custom-times' is set. Time like %H:%M should be at the
3069 end of the second format. The custom formats are also honored by export
3070 commands, if custom time display is turned on at the time of export."
3071 :group 'org-time
3072 :type 'sexp)
3074 (defun org-time-stamp-format (&optional long inactive)
3075 "Get the right format for a time string."
3076 (let ((f (if long (cdr org-time-stamp-formats)
3077 (car org-time-stamp-formats))))
3078 (if inactive
3079 (concat "[" (substring f 1 -1) "]")
3080 f)))
3082 (defcustom org-time-clocksum-format
3083 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
3084 "The format string used when creating CLOCKSUM lines.
3085 This is also used when Org mode generates a time duration.
3087 The value can be a single format string containing two
3088 %-sequences, which will be filled with the number of hours and
3089 minutes in that order.
3091 Alternatively, the value can be a plist associating any of the
3092 keys :years, :months, :weeks, :days, :hours or :minutes with
3093 format strings. The time duration is formatted using only the
3094 time components that are needed and concatenating the results.
3095 If a time unit in absent, it falls back to the next smallest
3096 unit.
3098 The keys :require-years, :require-months, :require-days,
3099 :require-weeks, :require-hours, :require-minutes are also
3100 meaningful. A non-nil value for these keys indicates that the
3101 corresponding time component should always be included, even if
3102 its value is 0.
3105 For example,
3107 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
3108 :require-minutes t)
3110 means durations longer than a day will be expressed in days,
3111 hours and minutes, and durations less than a day will always be
3112 expressed in hours and minutes (even for durations less than an
3113 hour).
3115 The value
3117 \(:days \"%dd\" :minutes \"%dm\")
3119 means durations longer than a day will be expressed in days and
3120 minutes, and durations less than a day will be expressed entirely
3121 in minutes (even for durations longer than an hour)."
3122 :group 'org-time
3123 :group 'org-clock
3124 :version "24.4"
3125 :package-version '(Org . "8.0")
3126 :type '(choice (string :tag "Format string")
3127 (set :tag "Plist"
3128 (group :inline t (const :tag "Years" :years)
3129 (string :tag "Format string"))
3130 (group :inline t
3131 (const :tag "Always show years" :require-years)
3132 (const t))
3133 (group :inline t (const :tag "Months" :months)
3134 (string :tag "Format string"))
3135 (group :inline t
3136 (const :tag "Always show months" :require-months)
3137 (const t))
3138 (group :inline t (const :tag "Weeks" :weeks)
3139 (string :tag "Format string"))
3140 (group :inline t
3141 (const :tag "Always show weeks" :require-weeks)
3142 (const t))
3143 (group :inline t (const :tag "Days" :days)
3144 (string :tag "Format string"))
3145 (group :inline t
3146 (const :tag "Always show days" :require-days)
3147 (const t))
3148 (group :inline t (const :tag "Hours" :hours)
3149 (string :tag "Format string"))
3150 (group :inline t
3151 (const :tag "Always show hours" :require-hours)
3152 (const t))
3153 (group :inline t (const :tag "Minutes" :minutes)
3154 (string :tag "Format string"))
3155 (group :inline t
3156 (const :tag "Always show minutes" :require-minutes)
3157 (const t)))))
3159 (defcustom org-time-clocksum-use-fractional nil
3160 "When non-nil, \\[org-clock-display] uses fractional times.
3161 See `org-time-clocksum-format' for more on time clock formats."
3162 :group 'org-time
3163 :group 'org-clock
3164 :version "24.3"
3165 :type 'boolean)
3167 (defcustom org-time-clocksum-use-effort-durations nil
3168 "When non-nil, \\[org-clock-display] uses effort durations.
3169 E.g. by default, one day is considered to be a 8 hours effort,
3170 so a task that has been clocked for 16 hours will be displayed
3171 as during 2 days in the clock display or in the clocktable.
3173 See `org-effort-durations' on how to set effort durations
3174 and `org-time-clocksum-format' for more on time clock formats."
3175 :group 'org-time
3176 :group 'org-clock
3177 :version "24.4"
3178 :package-version '(Org . "8.0")
3179 :type 'boolean)
3181 (defcustom org-time-clocksum-fractional-format "%.2f"
3182 "The format string used when creating CLOCKSUM lines,
3183 or when Org mode generates a time duration, if
3184 `org-time-clocksum-use-fractional' is enabled.
3186 The value can be a single format string containing one
3187 %-sequence, which will be filled with the number of hours as
3188 a float.
3190 Alternatively, the value can be a plist associating any of the
3191 keys :years, :months, :weeks, :days, :hours or :minutes with
3192 a format string. The time duration is formatted using the
3193 largest time unit which gives a non-zero integer part. If all
3194 specified formats have zero integer part, the smallest time unit
3195 is used."
3196 :group 'org-time
3197 :type '(choice (string :tag "Format string")
3198 (set (group :inline t (const :tag "Years" :years)
3199 (string :tag "Format string"))
3200 (group :inline t (const :tag "Months" :months)
3201 (string :tag "Format string"))
3202 (group :inline t (const :tag "Weeks" :weeks)
3203 (string :tag "Format string"))
3204 (group :inline t (const :tag "Days" :days)
3205 (string :tag "Format string"))
3206 (group :inline t (const :tag "Hours" :hours)
3207 (string :tag "Format string"))
3208 (group :inline t (const :tag "Minutes" :minutes)
3209 (string :tag "Format string")))))
3211 (defcustom org-deadline-warning-days 14
3212 "Number of days before expiration during which a deadline becomes active.
3213 This variable governs the display in sparse trees and in the agenda.
3214 When 0 or negative, it means use this number (the absolute value of it)
3215 even if a deadline has a different individual lead time specified.
3217 Custom commands can set this variable in the options section."
3218 :group 'org-time
3219 :group 'org-agenda-daily/weekly
3220 :type 'integer)
3222 (defcustom org-scheduled-delay-days 0
3223 "Number of days before a scheduled item becomes active.
3224 This variable governs the display in sparse trees and in the agenda.
3225 The default value (i.e. 0) means: don't delay scheduled item.
3226 When negative, it means use this number (the absolute value of it)
3227 even if a scheduled item has a different individual delay time
3228 specified.
3230 Custom commands can set this variable in the options section."
3231 :group 'org-time
3232 :group 'org-agenda-daily/weekly
3233 :version "24.4"
3234 :package-version '(Org . "8.0")
3235 :type 'integer)
3237 (defcustom org-read-date-prefer-future t
3238 "Non-nil means assume future for incomplete date input from user.
3239 This affects the following situations:
3240 1. The user gives a month but not a year.
3241 For example, if it is April and you enter \"feb 2\", this will be read
3242 as Feb 2, *next* year. \"May 5\", however, will be this year.
3243 2. The user gives a day, but no month.
3244 For example, if today is the 15th, and you enter \"3\", Org-mode will
3245 read this as the third of *next* month. However, if you enter \"17\",
3246 it will be considered as *this* month.
3248 If you set this variable to the symbol `time', then also the following
3249 will work:
3251 3. If the user gives a time.
3252 If the time is before now, it will be interpreted as tomorrow.
3254 Currently none of this works for ISO week specifications.
3256 When this option is nil, the current day, month and year will always be
3257 used as defaults.
3259 See also `org-agenda-jump-prefer-future'."
3260 :group 'org-time
3261 :type '(choice
3262 (const :tag "Never" nil)
3263 (const :tag "Check month and day" t)
3264 (const :tag "Check month, day, and time" time)))
3266 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3267 "Should the agenda jump command prefer the future for incomplete dates?
3268 The default is to do the same as configured in `org-read-date-prefer-future'.
3269 But you can also set a deviating value here.
3270 This may t or nil, or the symbol `org-read-date-prefer-future'."
3271 :group 'org-agenda
3272 :group 'org-time
3273 :version "24.1"
3274 :type '(choice
3275 (const :tag "Use org-read-date-prefer-future"
3276 org-read-date-prefer-future)
3277 (const :tag "Never" nil)
3278 (const :tag "Always" t)))
3280 (defcustom org-read-date-force-compatible-dates t
3281 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3283 Depending on the system Emacs is running on, certain dates cannot
3284 be represented with the type used internally to represent time.
3285 Dates between 1970-1-1 and 2038-1-1 can always be represented
3286 correctly. Some systems allow for earlier dates, some for later,
3287 some for both. One way to find out it to insert any date into an
3288 Org buffer, putting the cursor on the year and hitting S-up and
3289 S-down to test the range.
3291 When this variable is set to t, the date/time prompt will not let
3292 you specify dates outside the 1970-2037 range, so it is certain that
3293 these dates will work in whatever version of Emacs you are
3294 running, and also that you can move a file from one Emacs implementation
3295 to another. WHenever Org is forcing the year for you, it will display
3296 a message and beep.
3298 When this variable is nil, Org will check if the date is
3299 representable in the specific Emacs implementation you are using.
3300 If not, it will force a year, usually the current year, and beep
3301 to remind you. Currently this setting is not recommended because
3302 the likelihood that you will open your Org files in an Emacs that
3303 has limited date range is not negligible.
3305 A workaround for this problem is to use diary sexp dates for time
3306 stamps outside of this range."
3307 :group 'org-time
3308 :version "24.1"
3309 :type 'boolean)
3311 (defcustom org-read-date-display-live t
3312 "Non-nil means display current interpretation of date prompt live.
3313 This display will be in an overlay, in the minibuffer."
3314 :group 'org-time
3315 :type 'boolean)
3317 (defcustom org-read-date-popup-calendar t
3318 "Non-nil means pop up a calendar when prompting for a date.
3319 In the calendar, the date can be selected with mouse-1. However, the
3320 minibuffer will also be active, and you can simply enter the date as well.
3321 When nil, only the minibuffer will be available."
3322 :group 'org-time
3323 :type 'boolean)
3324 (org-defvaralias 'org-popup-calendar-for-date-prompt
3325 'org-read-date-popup-calendar)
3327 (make-obsolete-variable
3328 'org-read-date-minibuffer-setup-hook
3329 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3330 (defcustom org-read-date-minibuffer-setup-hook nil
3331 "Hook to be used to set up keys for the date/time interface.
3332 Add key definitions to `minibuffer-local-map', which will be a
3333 temporary copy.
3335 WARNING: This option is obsolete, you should use
3336 `org-read-date-minibuffer-local-map' to set up keys."
3337 :group 'org-time
3338 :type 'hook)
3340 (defcustom org-extend-today-until 0
3341 "The hour when your day really ends. Must be an integer.
3342 This has influence for the following applications:
3343 - When switching the agenda to \"today\". It it is still earlier than
3344 the time given here, the day recognized as TODAY is actually yesterday.
3345 - When a date is read from the user and it is still before the time given
3346 here, the current date and time will be assumed to be yesterday, 23:59.
3347 Also, timestamps inserted in capture templates follow this rule.
3349 IMPORTANT: This is a feature whose implementation is and likely will
3350 remain incomplete. Really, it is only here because past midnight seems to
3351 be the favorite working time of John Wiegley :-)"
3352 :group 'org-time
3353 :type 'integer)
3355 (defcustom org-use-effective-time nil
3356 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3357 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3358 \"effective time\" of any timestamps between midnight and 8am will be
3359 23:59 of the previous day."
3360 :group 'org-time
3361 :version "24.1"
3362 :type 'boolean)
3364 (defcustom org-use-last-clock-out-time-as-effective-time nil
3365 "When non-nil, use the last clock out time for `org-todo'.
3366 Note that this option has precedence over the combined use of
3367 `org-use-effective-time' and `org-extend-today-until'."
3368 :group 'org-time
3369 :version "24.4"
3370 :package-version '(Org . "8.0")
3371 :type 'boolean)
3373 (defcustom org-edit-timestamp-down-means-later nil
3374 "Non-nil means S-down will increase the time in a time stamp.
3375 When nil, S-up will increase."
3376 :group 'org-time
3377 :type 'boolean)
3379 (defcustom org-calendar-follow-timestamp-change t
3380 "Non-nil means make the calendar window follow timestamp changes.
3381 When a timestamp is modified and the calendar window is visible, it will be
3382 moved to the new date."
3383 :group 'org-time
3384 :type 'boolean)
3386 (defgroup org-tags nil
3387 "Options concerning tags in Org-mode."
3388 :tag "Org Tags"
3389 :group 'org)
3391 (defcustom org-tag-alist nil
3392 "List of tags allowed in Org-mode files.
3393 When this list is nil, Org-mode will base TAG input on what is already in the
3394 buffer.
3395 The value of this variable is an alist, the car of each entry must be a
3396 keyword as a string, the cdr may be a character that is used to select
3397 that tag through the fast-tag-selection interface.
3398 See the manual for details."
3399 :group 'org-tags
3400 :type '(repeat
3401 (choice
3402 (cons (string :tag "Tag name")
3403 (character :tag "Access char"))
3404 (list :tag "Start radio group"
3405 (const :startgroup)
3406 (option (string :tag "Group description")))
3407 (list :tag "Group tags delimiter"
3408 (const :grouptags))
3409 (list :tag "End radio group"
3410 (const :endgroup)
3411 (option (string :tag "Group description")))
3412 (const :tag "New line" (:newline)))))
3414 (defcustom org-tag-persistent-alist nil
3415 "List of tags that will always appear in all Org-mode files.
3416 This is in addition to any in buffer settings or customizations
3417 of `org-tag-alist'.
3418 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3419 The value of this variable is an alist, the car of each entry must be a
3420 keyword as a string, the cdr may be a character that is used to select
3421 that tag through the fast-tag-selection interface.
3422 See the manual for details.
3423 To disable these tags on a per-file basis, insert anywhere in the file:
3424 #+STARTUP: noptag"
3425 :group 'org-tags
3426 :type '(repeat
3427 (choice
3428 (cons (string :tag "Tag name")
3429 (character :tag "Access char"))
3430 (const :tag "Start radio group" (:startgroup))
3431 (const :tag "Group tags delimiter" (:grouptags))
3432 (const :tag "End radio group" (:endgroup))
3433 (const :tag "New line" (:newline)))))
3435 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3436 "If non-nil, always offer completion for all tags of all agenda files.
3437 Instead of customizing this variable directly, you might want to
3438 set it locally for capture buffers, because there no list of
3439 tags in that file can be created dynamically (there are none).
3441 (add-hook 'org-capture-mode-hook
3442 (lambda ()
3443 (set (make-local-variable
3444 'org-complete-tags-always-offer-all-agenda-tags)
3445 t)))"
3446 :group 'org-tags
3447 :version "24.1"
3448 :type 'boolean)
3450 (defvar org-file-tags nil
3451 "List of tags that can be inherited by all entries in the file.
3452 The tags will be inherited if the variable `org-use-tag-inheritance'
3453 says they should be.
3454 This variable is populated from #+FILETAGS lines.")
3456 (defcustom org-use-fast-tag-selection 'auto
3457 "Non-nil means use fast tag selection scheme.
3458 This is a special interface to select and deselect tags with single keys.
3459 When nil, fast selection is never used.
3460 When the symbol `auto', fast selection is used if and only if selection
3461 characters for tags have been configured, either through the variable
3462 `org-tag-alist' or through a #+TAGS line in the buffer.
3463 When t, fast selection is always used and selection keys are assigned
3464 automatically if necessary."
3465 :group 'org-tags
3466 :type '(choice
3467 (const :tag "Always" t)
3468 (const :tag "Never" nil)
3469 (const :tag "When selection characters are configured" auto)))
3471 (defcustom org-fast-tag-selection-single-key nil
3472 "Non-nil means fast tag selection exits after first change.
3473 When nil, you have to press RET to exit it.
3474 During fast tag selection, you can toggle this flag with `C-c'.
3475 This variable can also have the value `expert'. In this case, the window
3476 displaying the tags menu is not even shown, until you press C-c again."
3477 :group 'org-tags
3478 :type '(choice
3479 (const :tag "No" nil)
3480 (const :tag "Yes" t)
3481 (const :tag "Expert" expert)))
3483 (defvar org-fast-tag-selection-include-todo nil
3484 "Non-nil means fast tags selection interface will also offer TODO states.
3485 This is an undocumented feature, you should not rely on it.")
3487 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3488 "The column to which tags should be indented in a headline.
3489 If this number is positive, it specifies the column. If it is negative,
3490 it means that the tags should be flushright to that column. For example,
3491 -80 works well for a normal 80 character screen.
3492 When 0, place tags directly after headline text, with only one space in
3493 between."
3494 :group 'org-tags
3495 :type 'integer)
3497 (defcustom org-auto-align-tags t
3498 "Non-nil keeps tags aligned when modifying headlines.
3499 Some operations (i.e. demoting) change the length of a headline and
3500 therefore shift the tags around. With this option turned on, after
3501 each such operation the tags are again aligned to `org-tags-column'."
3502 :group 'org-tags
3503 :type 'boolean)
3505 (defcustom org-use-tag-inheritance t
3506 "Non-nil means tags in levels apply also for sublevels.
3507 When nil, only the tags directly given in a specific line apply there.
3508 This may also be a list of tags that should be inherited, or a regexp that
3509 matches tags that should be inherited. Additional control is possible
3510 with the variable `org-tags-exclude-from-inheritance' which gives an
3511 explicit list of tags to be excluded from inheritance, even if the value of
3512 `org-use-tag-inheritance' would select it for inheritance.
3514 If this option is t, a match early-on in a tree can lead to a large
3515 number of matches in the subtree when constructing the agenda or creating
3516 a sparse tree. If you only want to see the first match in a tree during
3517 a search, check out the variable `org-tags-match-list-sublevels'."
3518 :group 'org-tags
3519 :type '(choice
3520 (const :tag "Not" nil)
3521 (const :tag "Always" t)
3522 (repeat :tag "Specific tags" (string :tag "Tag"))
3523 (regexp :tag "Tags matched by regexp")))
3525 (defcustom org-tags-exclude-from-inheritance nil
3526 "List of tags that should never be inherited.
3527 This is a way to exclude a few tags from inheritance. For way to do
3528 the opposite, to actively allow inheritance for selected tags,
3529 see the variable `org-use-tag-inheritance'."
3530 :group 'org-tags
3531 :type '(repeat (string :tag "Tag")))
3533 (defun org-tag-inherit-p (tag)
3534 "Check if TAG is one that should be inherited."
3535 (cond
3536 ((member tag org-tags-exclude-from-inheritance) nil)
3537 ((eq org-use-tag-inheritance t) t)
3538 ((not org-use-tag-inheritance) nil)
3539 ((stringp org-use-tag-inheritance)
3540 (string-match org-use-tag-inheritance tag))
3541 ((listp org-use-tag-inheritance)
3542 (member tag org-use-tag-inheritance))
3543 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3545 (defcustom org-tags-match-list-sublevels t
3546 "Non-nil means list also sublevels of headlines matching a search.
3547 This variable applies to tags/property searches, and also to stuck
3548 projects because this search is based on a tags match as well.
3550 When set to the symbol `indented', sublevels are indented with
3551 leading dots.
3553 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3554 the sublevels of a headline matching a tag search often also match
3555 the same search. Listing all of them can create very long lists.
3556 Setting this variable to nil causes subtrees of a match to be skipped.
3558 This variable is semi-obsolete and probably should always be true. It
3559 is better to limit inheritance to certain tags using the variables
3560 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3561 :group 'org-tags
3562 :type '(choice
3563 (const :tag "No, don't list them" nil)
3564 (const :tag "Yes, do list them" t)
3565 (const :tag "List them, indented with leading dots" indented)))
3567 (defcustom org-tags-sort-function nil
3568 "When set, tags are sorted using this function as a comparator."
3569 :group 'org-tags
3570 :type '(choice
3571 (const :tag "No sorting" nil)
3572 (const :tag "Alphabetical" string<)
3573 (const :tag "Reverse alphabetical" string>)
3574 (function :tag "Custom function" nil)))
3576 (defvar org-tags-history nil
3577 "History of minibuffer reads for tags.")
3578 (defvar org-last-tags-completion-table nil
3579 "The last used completion table for tags.")
3580 (defvar org-after-tags-change-hook nil
3581 "Hook that is run after the tags in a line have changed.")
3583 (defgroup org-properties nil
3584 "Options concerning properties in Org-mode."
3585 :tag "Org Properties"
3586 :group 'org)
3588 (defcustom org-property-format "%-10s %s"
3589 "How property key/value pairs should be formatted by `indent-line'.
3590 When `indent-line' hits a property definition, it will format the line
3591 according to this format, mainly to make sure that the values are
3592 lined-up with respect to each other."
3593 :group 'org-properties
3594 :type 'string)
3596 (defcustom org-properties-postprocess-alist nil
3597 "Alist of properties and functions to adjust inserted values.
3598 Elements of this alist must be of the form
3600 ([string] [function])
3602 where [string] must be a property name and [function] must be a
3603 lambda expression: this lambda expression must take one argument,
3604 the value to adjust, and return the new value as a string.
3606 For example, this element will allow the property \"Remaining\"
3607 to be updated wrt the relation between the \"Effort\" property
3608 and the clock summary:
3610 ((\"Remaining\" (lambda(value)
3611 (let ((clocksum (org-clock-sum-current-item))
3612 (effort (org-duration-string-to-minutes
3613 (org-entry-get (point) \"Effort\"))))
3614 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3615 :group 'org-properties
3616 :version "24.1"
3617 :type '(alist :key-type (string :tag "Property")
3618 :value-type (function :tag "Function")))
3620 (defcustom org-use-property-inheritance nil
3621 "Non-nil means properties apply also for sublevels.
3623 This setting is chiefly used during property searches. Turning it on can
3624 cause significant overhead when doing a search, which is why it is not
3625 on by default.
3627 When nil, only the properties directly given in the current entry count.
3628 When t, every property is inherited. The value may also be a list of
3629 properties that should have inheritance, or a regular expression matching
3630 properties that should be inherited.
3632 However, note that some special properties use inheritance under special
3633 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3634 and the properties ending in \"_ALL\" when they are used as descriptor
3635 for valid values of a property.
3637 Note for programmers:
3638 When querying an entry with `org-entry-get', you can control if inheritance
3639 should be used. By default, `org-entry-get' looks only at the local
3640 properties. You can request inheritance by setting the inherit argument
3641 to t (to force inheritance) or to `selective' (to respect the setting
3642 in this variable)."
3643 :group 'org-properties
3644 :type '(choice
3645 (const :tag "Not" nil)
3646 (const :tag "Always" t)
3647 (repeat :tag "Specific properties" (string :tag "Property"))
3648 (regexp :tag "Properties matched by regexp")))
3650 (defun org-property-inherit-p (property)
3651 "Check if PROPERTY is one that should be inherited."
3652 (cond
3653 ((eq org-use-property-inheritance t) t)
3654 ((not org-use-property-inheritance) nil)
3655 ((stringp org-use-property-inheritance)
3656 (string-match org-use-property-inheritance property))
3657 ((listp org-use-property-inheritance)
3658 (member property org-use-property-inheritance))
3659 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3661 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3662 "The default column format, if no other format has been defined.
3663 This variable can be set on the per-file basis by inserting a line
3665 #+COLUMNS: %25ITEM ....."
3666 :group 'org-properties
3667 :type 'string)
3669 (defcustom org-columns-ellipses ".."
3670 "The ellipses to be used when a field in column view is truncated.
3671 When this is the empty string, as many characters as possible are shown,
3672 but then there will be no visual indication that the field has been truncated.
3673 When this is a string of length N, the last N characters of a truncated
3674 field are replaced by this string. If the column is narrower than the
3675 ellipses string, only part of the ellipses string will be shown."
3676 :group 'org-properties
3677 :type 'string)
3679 (defcustom org-columns-modify-value-for-display-function nil
3680 "Function that modifies values for display in column view.
3681 For example, it can be used to cut out a certain part from a time stamp.
3682 The function must take 2 arguments:
3684 column-title The title of the column (*not* the property name)
3685 value The value that should be modified.
3687 The function should return the value that should be displayed,
3688 or nil if the normal value should be used."
3689 :group 'org-properties
3690 :type '(choice (const nil) (function)))
3692 (defconst org-global-properties-fixed
3693 '(("VISIBILITY_ALL" . "folded children content all")
3694 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3695 "List of property/value pairs that can be inherited by any entry.
3697 These are fixed values, for the preset properties. The user variable
3698 that can be used to add to this list is `org-global-properties'.
3700 The entries in this list are cons cells where the car is a property
3701 name and cdr is a string with the value. If the value represents
3702 multiple items like an \"_ALL\" property, separate the items by
3703 spaces.")
3705 (defcustom org-global-properties nil
3706 "List of property/value pairs that can be inherited by any entry.
3708 This list will be combined with the constant `org-global-properties-fixed'.
3710 The entries in this list are cons cells where the car is a property
3711 name and cdr is a string with the value.
3713 You can set buffer-local values for the same purpose in the variable
3714 `org-file-properties' this by adding lines like
3716 #+PROPERTY: NAME VALUE"
3717 :group 'org-properties
3718 :type '(repeat
3719 (cons (string :tag "Property")
3720 (string :tag "Value"))))
3722 (defvar org-file-properties nil
3723 "List of property/value pairs that can be inherited by any entry.
3724 Valid for the current buffer.
3725 This variable is populated from #+PROPERTY lines.")
3726 (make-variable-buffer-local 'org-file-properties)
3728 (defgroup org-agenda nil
3729 "Options concerning agenda views in Org-mode."
3730 :tag "Org Agenda"
3731 :group 'org)
3733 (defvar org-category nil
3734 "Variable used by org files to set a category for agenda display.
3735 Such files should use a file variable to set it, for example
3737 # -*- mode: org; org-category: \"ELisp\"
3739 or contain a special line
3741 #+CATEGORY: ELisp
3743 If the file does not specify a category, then file's base name
3744 is used instead.")
3745 (make-variable-buffer-local 'org-category)
3746 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3748 (defcustom org-agenda-files nil
3749 "The files to be used for agenda display.
3750 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3751 \\[org-remove-file]. You can also use customize to edit the list.
3753 If an entry is a directory, all files in that directory that are matched by
3754 `org-agenda-file-regexp' will be part of the file list.
3756 If the value of the variable is not a list but a single file name, then
3757 the list of agenda files is actually stored and maintained in that file, one
3758 agenda file per line. In this file paths can be given relative to
3759 `org-directory'. Tilde expansion and environment variable substitution
3760 are also made."
3761 :group 'org-agenda
3762 :type '(choice
3763 (repeat :tag "List of files and directories" file)
3764 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3766 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3767 "Regular expression to match files for `org-agenda-files'.
3768 If any element in the list in that variable contains a directory instead
3769 of a normal file, all files in that directory that are matched by this
3770 regular expression will be included."
3771 :group 'org-agenda
3772 :type 'regexp)
3774 (defcustom org-agenda-text-search-extra-files nil
3775 "List of extra files to be searched by text search commands.
3776 These files will be searched in addition to the agenda files by the
3777 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3778 Note that these files will only be searched for text search commands,
3779 not for the other agenda views like todo lists, tag searches or the weekly
3780 agenda. This variable is intended to list notes and possibly archive files
3781 that should also be searched by these two commands.
3782 In fact, if the first element in the list is the symbol `agenda-archives',
3783 then all archive files of all agenda files will be added to the search
3784 scope."
3785 :group 'org-agenda
3786 :type '(set :greedy t
3787 (const :tag "Agenda Archives" agenda-archives)
3788 (repeat :inline t (file))))
3790 (org-defvaralias 'org-agenda-multi-occur-extra-files
3791 'org-agenda-text-search-extra-files)
3793 (defcustom org-agenda-skip-unavailable-files nil
3794 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3795 A nil value means to remove them, after a query, from the list."
3796 :group 'org-agenda
3797 :type 'boolean)
3799 (defcustom org-calendar-to-agenda-key [?c]
3800 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3801 The command `org-calendar-goto-agenda' will be bound to this key. The
3802 default is the character `c' because then `c' can be used to switch back and
3803 forth between agenda and calendar."
3804 :group 'org-agenda
3805 :type 'sexp)
3807 (defcustom org-calendar-insert-diary-entry-key [?i]
3808 "The key to be installed in `calendar-mode-map' for adding diary entries.
3809 This option is irrelevant until `org-agenda-diary-file' has been configured
3810 to point to an Org-mode file. When that is the case, the command
3811 `org-agenda-diary-entry' will be bound to the key given here, by default
3812 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3813 if you want to continue doing this, you need to change this to a different
3814 key."
3815 :group 'org-agenda
3816 :type 'sexp)
3818 (defcustom org-agenda-diary-file 'diary-file
3819 "File to which to add new entries with the `i' key in agenda and calendar.
3820 When this is the symbol `diary-file', the functionality in the Emacs
3821 calendar will be used to add entries to the `diary-file'. But when this
3822 points to a file, `org-agenda-diary-entry' will be used instead."
3823 :group 'org-agenda
3824 :type '(choice
3825 (const :tag "The standard Emacs diary file" diary-file)
3826 (file :tag "Special Org file diary entries")))
3828 (eval-after-load "calendar"
3829 '(progn
3830 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3831 'org-calendar-goto-agenda)
3832 (add-hook 'calendar-mode-hook
3833 (lambda ()
3834 (unless (eq org-agenda-diary-file 'diary-file)
3835 (define-key calendar-mode-map
3836 org-calendar-insert-diary-entry-key
3837 'org-agenda-diary-entry))))))
3839 (defgroup org-latex nil
3840 "Options for embedding LaTeX code into Org-mode."
3841 :tag "Org LaTeX"
3842 :group 'org)
3844 (defcustom org-format-latex-options
3845 '(:foreground default :background default :scale 1.0
3846 :html-foreground "Black" :html-background "Transparent"
3847 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3848 "Options for creating images from LaTeX fragments.
3849 This is a property list with the following properties:
3850 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3851 `default' means use the foreground of the default face.
3852 `auto' means use the foreground from the text face.
3853 :background the background color, or \"Transparent\".
3854 `default' means use the background of the default face.
3855 `auto' means use the background from the text face.
3856 :scale a scaling factor for the size of the images, to get more pixels
3857 :html-foreground, :html-background, :html-scale
3858 the same numbers for HTML export.
3859 :matchers a list indicating which matchers should be used to
3860 find LaTeX fragments. Valid members of this list are:
3861 \"begin\" find environments
3862 \"$1\" find single characters surrounded by $.$
3863 \"$\" find math expressions surrounded by $...$
3864 \"$$\" find math expressions surrounded by $$....$$
3865 \"\\(\" find math expressions surrounded by \\(...\\)
3866 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3867 :group 'org-latex
3868 :type 'plist)
3870 (defcustom org-format-latex-signal-error t
3871 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3872 When nil, just push out a message."
3873 :group 'org-latex
3874 :version "24.1"
3875 :type 'boolean)
3877 (defcustom org-latex-to-mathml-jar-file nil
3878 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3879 Use this to specify additional executable file say a jar file.
3881 When using MathToWeb as the converter, specify the full-path to
3882 your mathtoweb.jar file."
3883 :group 'org-latex
3884 :version "24.1"
3885 :type '(choice
3886 (const :tag "None" nil)
3887 (file :tag "JAR file" :must-match t)))
3889 (defcustom org-latex-to-mathml-convert-command nil
3890 "Command to convert LaTeX fragments to MathML.
3891 Replace format-specifiers in the command as noted below and use
3892 `shell-command' to convert LaTeX to MathML.
3893 %j: Executable file in fully expanded form as specified by
3894 `org-latex-to-mathml-jar-file'.
3895 %I: Input LaTeX file in fully expanded form
3896 %o: Output MathML file
3897 This command is used by `org-create-math-formula'.
3899 When using MathToWeb as the converter, set this to
3900 \"java -jar %j -unicode -force -df %o %I\"."
3901 :group 'org-latex
3902 :version "24.1"
3903 :type '(choice
3904 (const :tag "None" nil)
3905 (string :tag "\nShell command")))
3907 (defcustom org-latex-create-formula-image-program 'dvipng
3908 "Program to convert LaTeX fragments with.
3910 dvipng Process the LaTeX fragments to dvi file, then convert
3911 dvi files to png files using dvipng.
3912 This will also include processing of non-math environments.
3913 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3914 to convert pdf files to png files"
3915 :group 'org-latex
3916 :version "24.1"
3917 :type '(choice
3918 (const :tag "dvipng" dvipng)
3919 (const :tag "imagemagick" imagemagick)))
3921 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3922 "Path to store latex preview images.
3923 A relative path here creates many directories relative to the
3924 processed org files paths. An absolute path puts all preview
3925 images at the same place."
3926 :group 'org-latex
3927 :version "24.3"
3928 :type 'string)
3930 (defun org-format-latex-mathml-available-p ()
3931 "Return t if `org-latex-to-mathml-convert-command' is usable."
3932 (save-match-data
3933 (when (and (boundp 'org-latex-to-mathml-convert-command)
3934 org-latex-to-mathml-convert-command)
3935 (let ((executable (car (split-string
3936 org-latex-to-mathml-convert-command))))
3937 (when (executable-find executable)
3938 (if (string-match
3939 "%j" org-latex-to-mathml-convert-command)
3940 (file-readable-p org-latex-to-mathml-jar-file)
3941 t))))))
3943 (defcustom org-format-latex-header "\\documentclass{article}
3944 \\usepackage[usenames]{color}
3945 \[PACKAGES]
3946 \[DEFAULT-PACKAGES]
3947 \\pagestyle{empty} % do not remove
3948 % The settings below are copied from fullpage.sty
3949 \\setlength{\\textwidth}{\\paperwidth}
3950 \\addtolength{\\textwidth}{-3cm}
3951 \\setlength{\\oddsidemargin}{1.5cm}
3952 \\addtolength{\\oddsidemargin}{-2.54cm}
3953 \\setlength{\\evensidemargin}{\\oddsidemargin}
3954 \\setlength{\\textheight}{\\paperheight}
3955 \\addtolength{\\textheight}{-\\headheight}
3956 \\addtolength{\\textheight}{-\\headsep}
3957 \\addtolength{\\textheight}{-\\footskip}
3958 \\addtolength{\\textheight}{-3cm}
3959 \\setlength{\\topmargin}{1.5cm}
3960 \\addtolength{\\topmargin}{-2.54cm}"
3961 "The document header used for processing LaTeX fragments.
3962 It is imperative that this header make sure that no page number
3963 appears on the page. The package defined in the variables
3964 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3965 will either replace the placeholder \"[PACKAGES]\" in this
3966 header, or they will be appended."
3967 :group 'org-latex
3968 :type 'string)
3970 (defun org-set-packages-alist (var val)
3971 "Set the packages alist and make sure it has 3 elements per entry."
3972 (set var (mapcar (lambda (x)
3973 (if (and (consp x) (= (length x) 2))
3974 (list (car x) (nth 1 x) t)
3976 val)))
3978 (defun org-get-packages-alist (var)
3979 "Get the packages alist and make sure it has 3 elements per entry."
3980 (mapcar (lambda (x)
3981 (if (and (consp x) (= (length x) 2))
3982 (list (car x) (nth 1 x) t)
3984 (default-value var)))
3986 (defcustom org-latex-default-packages-alist
3987 '(("AUTO" "inputenc" t)
3988 ("T1" "fontenc" t)
3989 ("" "fixltx2e" nil)
3990 ("" "graphicx" t)
3991 ("" "longtable" nil)
3992 ("" "float" nil)
3993 ("" "wrapfig" nil)
3994 ("" "rotating" nil)
3995 ("normalem" "ulem" t)
3996 ("" "amsmath" t)
3997 ("" "textcomp" t)
3998 ("" "marvosym" t)
3999 ("" "wasysym" t)
4000 ("" "amssymb" t)
4001 ("" "hyperref" nil)
4002 "\\tolerance=1000")
4003 "Alist of default packages to be inserted in the header.
4005 Change this only if one of the packages here causes an
4006 incompatibility with another package you are using.
4008 The packages in this list are needed by one part or another of
4009 Org mode to function properly:
4011 - inputenc, fontenc: for basic font and character selection
4012 - fixltx2e: Important patches of LaTeX itself
4013 - graphicx: for including images
4014 - longtable: For multipage tables
4015 - float, wrapfig: for figure placement
4016 - rotating: for sideways figures and tables
4017 - ulem: for underline and strike-through
4018 - amsmath: for subscript and superscript and math environments
4019 - textcomp, marvosymb, wasysym, amssymb: for various symbols used
4020 for interpreting the entities in `org-entities'. You can skip
4021 some of these packages if you don't use any of their symbols.
4022 - hyperref: for cross references
4024 Therefore you should not modify this variable unless you know
4025 what you are doing. The one reason to change it anyway is that
4026 you might be loading some other package that conflicts with one
4027 of the default packages. Each element is either a cell or
4028 a string.
4030 A cell is of the format:
4032 \( \"options\" \"package\" SNIPPET-FLAG).
4034 If SNIPPET-FLAG is non-nil, the package also needs to be included
4035 when compiling LaTeX snippets into images for inclusion into
4036 non-LaTeX output.
4038 A string will be inserted as-is in the header of the document."
4039 :group 'org-latex
4040 :group 'org-export-latex
4041 :set 'org-set-packages-alist
4042 :get 'org-get-packages-alist
4043 :version "24.1"
4044 :type '(repeat
4045 (choice
4046 (list :tag "options/package pair"
4047 (string :tag "options")
4048 (string :tag "package")
4049 (boolean :tag "Snippet"))
4050 (string :tag "A line of LaTeX"))))
4052 (defcustom org-latex-packages-alist nil
4053 "Alist of packages to be inserted in every LaTeX header.
4055 These will be inserted after `org-latex-default-packages-alist'.
4056 Each element is either a cell or a string.
4058 A cell is of the format:
4060 \(\"options\" \"package\" SNIPPET-FLAG)
4062 SNIPPET-FLAG, when non-nil, indicates that this package is also
4063 needed when turning LaTeX snippets into images for inclusion into
4064 non-LaTeX output.
4066 A string will be inserted as-is in the header of the document.
4068 Make sure that you only list packages here which:
4070 - you want in every file;
4071 - do not conflict with the setup in `org-format-latex-header';
4072 - do not conflict with the default packages in
4073 `org-latex-default-packages-alist'."
4074 :group 'org-latex
4075 :group 'org-export-latex
4076 :set 'org-set-packages-alist
4077 :get 'org-get-packages-alist
4078 :type '(repeat
4079 (choice
4080 (list :tag "options/package pair"
4081 (string :tag "options")
4082 (string :tag "package")
4083 (boolean :tag "Snippet"))
4084 (string :tag "A line of LaTeX"))))
4086 (defgroup org-appearance nil
4087 "Settings for Org-mode appearance."
4088 :tag "Org Appearance"
4089 :group 'org)
4091 (defcustom org-level-color-stars-only nil
4092 "Non-nil means fontify only the stars in each headline.
4093 When nil, the entire headline is fontified.
4094 Changing it requires restart of `font-lock-mode' to become effective
4095 also in regions already fontified."
4096 :group 'org-appearance
4097 :type 'boolean)
4099 (defcustom org-hide-leading-stars nil
4100 "Non-nil means hide the first N-1 stars in a headline.
4101 This works by using the face `org-hide' for these stars. This
4102 face is white for a light background, and black for a dark
4103 background. You may have to customize the face `org-hide' to
4104 make this work.
4105 Changing it requires restart of `font-lock-mode' to become effective
4106 also in regions already fontified.
4107 You may also set this on a per-file basis by adding one of the following
4108 lines to the buffer:
4110 #+STARTUP: hidestars
4111 #+STARTUP: showstars"
4112 :group 'org-appearance
4113 :type 'boolean)
4115 (defcustom org-hidden-keywords nil
4116 "List of symbols corresponding to keywords to be hidden the org buffer.
4117 For example, a value '(title) for this list will make the document's title
4118 appear in the buffer without the initial #+TITLE: keyword."
4119 :group 'org-appearance
4120 :version "24.1"
4121 :type '(set (const :tag "#+AUTHOR" author)
4122 (const :tag "#+DATE" date)
4123 (const :tag "#+EMAIL" email)
4124 (const :tag "#+TITLE" title)))
4126 (defcustom org-custom-properties nil
4127 "List of properties (as strings) with a special meaning.
4128 The default use of these custom properties is to let the user
4129 hide them with `org-toggle-custom-properties-visibility'."
4130 :group 'org-properties
4131 :group 'org-appearance
4132 :version "24.3"
4133 :type '(repeat (string :tag "Property Name")))
4135 (defcustom org-fontify-done-headline nil
4136 "Non-nil means change the face of a headline if it is marked DONE.
4137 Normally, only the TODO/DONE keyword indicates the state of a headline.
4138 When this is non-nil, the headline after the keyword is set to the
4139 `org-headline-done' as an additional indication."
4140 :group 'org-appearance
4141 :type 'boolean)
4143 (defcustom org-fontify-emphasized-text t
4144 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4145 Changing this variable requires a restart of Emacs to take effect."
4146 :group 'org-appearance
4147 :type 'boolean)
4149 (defcustom org-fontify-whole-heading-line nil
4150 "Non-nil means fontify the whole line for headings.
4151 This is useful when setting a background color for the
4152 org-level-* faces."
4153 :group 'org-appearance
4154 :type 'boolean)
4156 (defcustom org-highlight-latex-and-related nil
4157 "Non-nil means highlight LaTeX related syntax in the buffer.
4158 When non nil, the value should be a list containing any of the
4159 following symbols:
4160 `latex' Highlight LaTeX snippets and environments.
4161 `script' Highlight subscript and superscript.
4162 `entities' Highlight entities."
4163 :group 'org-appearance
4164 :version "24.4"
4165 :package-version '(Org . "8.0")
4166 :type '(choice
4167 (const :tag "No highlighting" nil)
4168 (set :greedy t :tag "Highlight"
4169 (const :tag "LaTeX snippets and environments" latex)
4170 (const :tag "Subscript and superscript" script)
4171 (const :tag "Entities" entities))))
4173 (defcustom org-hide-emphasis-markers nil
4174 "Non-nil mean font-lock should hide the emphasis marker characters."
4175 :group 'org-appearance
4176 :type 'boolean)
4178 (defcustom org-hide-macro-markers nil
4179 "Non-nil mean font-lock should hide the brackets marking macro calls."
4180 :group 'org-appearance
4181 :type 'boolean)
4183 (defcustom org-pretty-entities nil
4184 "Non-nil means show entities as UTF8 characters.
4185 When nil, the \\name form remains in the buffer."
4186 :group 'org-appearance
4187 :version "24.1"
4188 :type 'boolean)
4190 (defcustom org-pretty-entities-include-sub-superscripts t
4191 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4192 :group 'org-appearance
4193 :version "24.1"
4194 :type 'boolean)
4196 (defvar org-emph-re nil
4197 "Regular expression for matching emphasis.
4198 After a match, the match groups contain these elements:
4199 0 The match of the full regular expression, including the characters
4200 before and after the proper match
4201 1 The character before the proper match, or empty at beginning of line
4202 2 The proper match, including the leading and trailing markers
4203 3 The leading marker like * or /, indicating the type of highlighting
4204 4 The text between the emphasis markers, not including the markers
4205 5 The character after the match, empty at the end of a line")
4206 (defvar org-verbatim-re nil
4207 "Regular expression for matching verbatim text.")
4208 (defvar org-emphasis-regexp-components) ; defined just below
4209 (defvar org-emphasis-alist) ; defined just below
4210 (defun org-set-emph-re (var val)
4211 "Set variable and compute the emphasis regular expression."
4212 (set var val)
4213 (when (and (boundp 'org-emphasis-alist)
4214 (boundp 'org-emphasis-regexp-components)
4215 org-emphasis-alist org-emphasis-regexp-components)
4216 (let* ((e org-emphasis-regexp-components)
4217 (pre (car e))
4218 (post (nth 1 e))
4219 (border (nth 2 e))
4220 (body (nth 3 e))
4221 (nl (nth 4 e))
4222 (body1 (concat body "*?"))
4223 (markers (mapconcat 'car org-emphasis-alist ""))
4224 (vmarkers (mapconcat
4225 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4226 org-emphasis-alist "")))
4227 ;; make sure special characters appear at the right position in the class
4228 (if (string-match "\\^" markers)
4229 (setq markers (concat (replace-match "" t t markers) "^")))
4230 (if (string-match "-" markers)
4231 (setq markers (concat (replace-match "" t t markers) "-")))
4232 (if (string-match "\\^" vmarkers)
4233 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4234 (if (string-match "-" vmarkers)
4235 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4236 (if (> nl 0)
4237 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4238 (int-to-string nl) "\\}")))
4239 ;; Make the regexp
4240 (setq org-emph-re
4241 (concat "\\([" pre "]\\|^\\)"
4242 "\\("
4243 "\\([" markers "]\\)"
4244 "\\("
4245 "[^" border "]\\|"
4246 "[^" border "]"
4247 body1
4248 "[^" border "]"
4249 "\\)"
4250 "\\3\\)"
4251 "\\([" post "]\\|$\\)"))
4252 (setq org-verbatim-re
4253 (concat "\\([" pre "]\\|^\\)"
4254 "\\("
4255 "\\([" vmarkers "]\\)"
4256 "\\("
4257 "[^" border "]\\|"
4258 "[^" border "]"
4259 body1
4260 "[^" border "]"
4261 "\\)"
4262 "\\3\\)"
4263 "\\([" post "]\\|$\\)")))))
4265 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4266 ;; set this option proved cumbersome. See this message/thread:
4267 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4268 (defvar org-emphasis-regexp-components
4269 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4270 "Components used to build the regular expression for emphasis.
4271 This is a list with five entries. Terminology: In an emphasis string
4272 like \" *strong word* \", we call the initial space PREMATCH, the final
4273 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4274 and \"trong wor\" is the body. The different components in this variable
4275 specify what is allowed/forbidden in each part:
4277 pre Chars allowed as prematch. Beginning of line will be allowed too.
4278 post Chars allowed as postmatch. End of line will be allowed too.
4279 border The chars *forbidden* as border characters.
4280 body-regexp A regexp like \".\" to match a body character. Don't use
4281 non-shy groups here, and don't allow newline here.
4282 newline The maximum number of newlines allowed in an emphasis exp.
4284 You need to reload Org or to restart Emacs after customizing this.")
4286 (defcustom org-emphasis-alist
4287 `(("*" bold)
4288 ("/" italic)
4289 ("_" underline)
4290 ("=" org-verbatim verbatim)
4291 ("~" org-code verbatim)
4292 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4293 "Alist of characters and faces to emphasize text.
4294 Text starting and ending with a special character will be emphasized,
4295 for example *bold*, _underlined_ and /italic/. This variable sets the
4296 marker characters and the face to be used by font-lock for highlighting
4297 in Org-mode Emacs buffers.
4299 You need to reload Org or to restart Emacs after customizing this."
4300 :group 'org-appearance
4301 :set 'org-set-emph-re
4302 :version "24.4"
4303 :package-version '(Org . "8.0")
4304 :type '(repeat
4305 (list
4306 (string :tag "Marker character")
4307 (choice
4308 (face :tag "Font-lock-face")
4309 (plist :tag "Face property list"))
4310 (option (const verbatim)))))
4312 (defvar org-protecting-blocks
4313 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4314 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4315 This is needed for font-lock setup.")
4317 ;;; Miscellaneous options
4319 (defgroup org-completion nil
4320 "Completion in Org-mode."
4321 :tag "Org Completion"
4322 :group 'org)
4324 (defcustom org-completion-use-ido nil
4325 "Non-nil means use ido completion wherever possible.
4326 Note that `ido-mode' must be active for this variable to be relevant.
4327 If you decide to turn this variable on, you might well want to turn off
4328 `org-outline-path-complete-in-steps'.
4329 See also `org-completion-use-iswitchb'."
4330 :group 'org-completion
4331 :type 'boolean)
4333 (defcustom org-completion-use-iswitchb nil
4334 "Non-nil means use iswitchb completion wherever possible.
4335 Note that `iswitchb-mode' must be active for this variable to be relevant.
4336 If you decide to turn this variable on, you might well want to turn off
4337 `org-outline-path-complete-in-steps'.
4338 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4339 :group 'org-completion
4340 :type 'boolean)
4342 (defcustom org-completion-fallback-command 'hippie-expand
4343 "The expansion command called by \\[pcomplete] in normal context.
4344 Normal means, no org-mode-specific context."
4345 :group 'org-completion
4346 :type 'function)
4348 ;;; Functions and variables from their packages
4349 ;; Declared here to avoid compiler warnings
4351 ;; XEmacs only
4352 (defvar outline-mode-menu-heading)
4353 (defvar outline-mode-menu-show)
4354 (defvar outline-mode-menu-hide)
4355 (defvar zmacs-regions) ; XEmacs regions
4357 ;; Emacs only
4358 (defvar mark-active)
4360 ;; Various packages
4361 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4362 (declare-function calendar-forward-day "cal-move" (arg))
4363 (declare-function calendar-goto-date "cal-move" (date))
4364 (declare-function calendar-goto-today "cal-move" ())
4365 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4366 (defvar calc-embedded-close-formula)
4367 (defvar calc-embedded-open-formula)
4368 (declare-function cdlatex-tab "ext:cdlatex" ())
4369 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4370 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4371 (defvar font-lock-unfontify-region-function)
4372 (declare-function iswitchb-read-buffer "iswitchb"
4373 (prompt &optional default require-match start matches-set))
4374 (defvar iswitchb-temp-buflist)
4375 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4376 (defvar org-agenda-tags-todo-honor-ignore-options)
4377 (declare-function org-agenda-skip "org-agenda" ())
4378 (declare-function
4379 org-agenda-format-item "org-agenda"
4380 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4381 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4382 (declare-function org-agenda-change-all-lines "org-agenda"
4383 (newhead hdmarker &optional fixface just-this))
4384 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4385 (declare-function org-agenda-maybe-redo "org-agenda" ())
4386 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4387 (beg end))
4388 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4389 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4390 "org-agenda" (&optional end))
4391 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4392 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4393 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4394 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4395 (declare-function org-indent-mode "org-indent" (&optional arg))
4396 (declare-function parse-time-string "parse-time" (string))
4397 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4398 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4399 (defvar remember-data-file)
4400 (defvar texmathp-why)
4401 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4402 (declare-function table--at-cell-p "table" (position &optional object at-column))
4403 (declare-function calc-eval "calc" (str &optional separator &rest args))
4405 ;;;###autoload
4406 (defun turn-on-orgtbl ()
4407 "Unconditionally turn on `orgtbl-mode'."
4408 (require 'org-table)
4409 (orgtbl-mode 1))
4411 (defun org-at-table-p (&optional table-type)
4412 "Return t if the cursor is inside an org-type table.
4413 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4414 (if org-enable-table-editor
4415 (save-excursion
4416 (beginning-of-line 1)
4417 (looking-at (if table-type org-table-any-line-regexp
4418 org-table-line-regexp)))
4419 nil))
4420 (defsubst org-table-p () (org-at-table-p))
4422 (defun org-at-table.el-p ()
4423 "Return t if and only if we are at a table.el table."
4424 (and (org-at-table-p 'any)
4425 (save-excursion
4426 (goto-char (org-table-begin 'any))
4427 (looking-at org-table1-hline-regexp))))
4429 (defun org-table-recognize-table.el ()
4430 "If there is a table.el table nearby, recognize it and move into it."
4431 (if org-table-tab-recognizes-table.el
4432 (if (org-at-table.el-p)
4433 (progn
4434 (beginning-of-line 1)
4435 (if (looking-at org-table-dataline-regexp)
4437 (if (looking-at org-table1-hline-regexp)
4438 (progn
4439 (beginning-of-line 2)
4440 (if (looking-at org-table-any-border-regexp)
4441 (beginning-of-line -1)))))
4442 (if (re-search-forward "|" (org-table-end t) t)
4443 (progn
4444 (require 'table)
4445 (if (table--at-cell-p (point))
4447 (message "recognizing table.el table...")
4448 (table-recognize-table)
4449 (message "recognizing table.el table...done")))
4450 (error "This should not happen"))
4452 nil)
4453 nil))
4455 (defun org-at-table-hline-p ()
4456 "Return t if the cursor is inside a hline in a table."
4457 (if org-enable-table-editor
4458 (save-excursion
4459 (beginning-of-line 1)
4460 (looking-at org-table-hline-regexp))
4461 nil))
4463 (defun org-table-map-tables (function &optional quietly)
4464 "Apply FUNCTION to the start of all tables in the buffer."
4465 (save-excursion
4466 (save-restriction
4467 (widen)
4468 (goto-char (point-min))
4469 (while (re-search-forward org-table-any-line-regexp nil t)
4470 (unless quietly
4471 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4472 (beginning-of-line 1)
4473 (when (and (looking-at org-table-line-regexp)
4474 ;; Exclude tables in src/example/verbatim/clocktable blocks
4475 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4476 (save-excursion (funcall function))
4477 (or (looking-at org-table-line-regexp)
4478 (forward-char 1)))
4479 (re-search-forward org-table-any-border-regexp nil 1))))
4480 (unless quietly (message "Mapping tables: done")))
4482 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4483 (declare-function org-clock-update-mode-line "org-clock" ())
4484 (declare-function org-resolve-clocks "org-clock"
4485 (&optional also-non-dangling-p prompt last-valid))
4487 (defun org-at-TBLFM-p (&optional pos)
4488 "Return t when point (or POS) is in #+TBLFM line."
4489 (save-excursion
4490 (let ((pos pos)))
4491 (goto-char (or pos (point)))
4492 (beginning-of-line 1)
4493 (looking-at org-TBLFM-regexp)))
4495 (defvar org-clock-start-time)
4496 (defvar org-clock-marker (make-marker)
4497 "Marker recording the last clock-in.")
4498 (defvar org-clock-hd-marker (make-marker)
4499 "Marker recording the last clock-in, but the headline position.")
4500 (defvar org-clock-heading ""
4501 "The heading of the current clock entry.")
4502 (defun org-clock-is-active ()
4503 "Return the buffer where the clock is currently running.
4504 Return nil if no clock is running."
4505 (marker-buffer org-clock-marker))
4507 (defun org-check-running-clock ()
4508 "Check if the current buffer contains the running clock.
4509 If yes, offer to stop it and to save the buffer with the changes."
4510 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4511 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4512 (buffer-name))))
4513 (org-clock-out)
4514 (when (y-or-n-p "Save changed buffer?")
4515 (save-buffer))))
4517 (defun org-clocktable-try-shift (dir n)
4518 "Check if this line starts a clock table, if yes, shift the time block."
4519 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4520 (org-clocktable-shift dir n)))
4522 ;;;###autoload
4523 (defun org-clock-persistence-insinuate ()
4524 "Set up hooks for clock persistence."
4525 (require 'org-clock)
4526 (add-hook 'org-mode-hook 'org-clock-load)
4527 (add-hook 'kill-emacs-hook 'org-clock-save))
4529 (defgroup org-archive nil
4530 "Options concerning archiving in Org-mode."
4531 :tag "Org Archive"
4532 :group 'org-structure)
4534 (defcustom org-archive-location "%s_archive::"
4535 "The location where subtrees should be archived.
4537 The value of this variable is a string, consisting of two parts,
4538 separated by a double-colon. The first part is a filename and
4539 the second part is a headline.
4541 When the filename is omitted, archiving happens in the same file.
4542 %s in the filename will be replaced by the current file
4543 name (without the directory part). Archiving to a different file
4544 is useful to keep archived entries from contributing to the
4545 Org-mode Agenda.
4547 The archived entries will be filed as subtrees of the specified
4548 headline. When the headline is omitted, the subtrees are simply
4549 filed away at the end of the file, as top-level entries. Also in
4550 the heading you can use %s to represent the file name, this can be
4551 useful when using the same archive for a number of different files.
4553 Here are a few examples:
4554 \"%s_archive::\"
4555 If the current file is Projects.org, archive in file
4556 Projects.org_archive, as top-level trees. This is the default.
4558 \"::* Archived Tasks\"
4559 Archive in the current file, under the top-level headline
4560 \"* Archived Tasks\".
4562 \"~/org/archive.org::\"
4563 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4565 \"~/org/archive.org::* From %s\"
4566 Archive in file ~/org/archive.org (absolute path), under headlines
4567 \"From FILENAME\" where file name is the current file name.
4569 \"~/org/datetree.org::datetree/* Finished Tasks\"
4570 The \"datetree/\" string is special, signifying to archive
4571 items to the datetree. Items are placed in either the CLOSED
4572 date of the item, or the current date if there is no CLOSED date.
4573 The heading will be a subentry to the current date. There doesn't
4574 need to be a heading, but there always needs to be a slash after
4575 datetree. For example, to store archived items directly in the
4576 datetree, use \"~/org/datetree.org::datetree/\".
4578 \"basement::** Finished Tasks\"
4579 Archive in file ./basement (relative path), as level 3 trees
4580 below the level 2 heading \"** Finished Tasks\".
4582 You may set this option on a per-file basis by adding to the buffer a
4583 line like
4585 #+ARCHIVE: basement::** Finished Tasks
4587 You may also define it locally for a subtree by setting an ARCHIVE property
4588 in the entry. If such a property is found in an entry, or anywhere up
4589 the hierarchy, it will be used."
4590 :group 'org-archive
4591 :type 'string)
4593 (defcustom org-agenda-skip-archived-trees t
4594 "Non-nil means the agenda will skip any items located in archived trees.
4595 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4596 variable is no longer recommended, you should leave it at the value t.
4597 Instead, use the key `v' to cycle the archives-mode in the agenda."
4598 :group 'org-archive
4599 :group 'org-agenda-skip
4600 :type 'boolean)
4602 (defcustom org-columns-skip-archived-trees t
4603 "Non-nil means ignore archived trees when creating column view."
4604 :group 'org-archive
4605 :group 'org-properties
4606 :type 'boolean)
4608 (defcustom org-cycle-open-archived-trees nil
4609 "Non-nil means `org-cycle' will open archived trees.
4610 An archived tree is a tree marked with the tag ARCHIVE.
4611 When nil, archived trees will stay folded. You can still open them with
4612 normal outline commands like `show-all', but not with the cycling commands."
4613 :group 'org-archive
4614 :group 'org-cycle
4615 :type 'boolean)
4617 (defcustom org-sparse-tree-open-archived-trees nil
4618 "Non-nil means sparse tree construction shows matches in archived trees.
4619 When nil, matches in these trees are highlighted, but the trees are kept in
4620 collapsed state."
4621 :group 'org-archive
4622 :group 'org-sparse-trees
4623 :type 'boolean)
4625 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4626 "The default date type when building a sparse tree.
4627 When this is nil, a date is a scheduled or a deadline timestamp.
4628 Otherwise, these types are allowed:
4630 all: all timestamps
4631 active: only active timestamps (<...>)
4632 inactive: only inactive timestamps (<...)
4633 scheduled: only scheduled timestamps
4634 deadline: only deadline timestamps"
4635 :type '(choice (const :tag "Scheduled or deadline" scheduled-or-deadline)
4636 (const :tag "All timestamps" all)
4637 (const :tag "Only active timestamps" active)
4638 (const :tag "Only inactive timestamps" inactive)
4639 (const :tag "Only scheduled timestamps" scheduled)
4640 (const :tag "Only deadline timestamps" deadline)
4641 (const :tag "Only closed timestamps" closed))
4642 :version "24.3"
4643 :group 'org-sparse-trees)
4645 (defun org-cycle-hide-archived-subtrees (state)
4646 "Re-hide all archived subtrees after a visibility state change."
4647 (when (and (not org-cycle-open-archived-trees)
4648 (not (memq state '(overview folded))))
4649 (save-excursion
4650 (let* ((globalp (memq state '(contents all)))
4651 (beg (if globalp (point-min) (point)))
4652 (end (if globalp (point-max) (org-end-of-subtree t))))
4653 (org-hide-archived-subtrees beg end)
4654 (goto-char beg)
4655 (if (looking-at (concat ".*:" org-archive-tag ":"))
4656 (message "%s" (substitute-command-keys
4657 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4659 (defun org-force-cycle-archived ()
4660 "Cycle subtree even if it is archived."
4661 (interactive)
4662 (setq this-command 'org-cycle)
4663 (let ((org-cycle-open-archived-trees t))
4664 (call-interactively 'org-cycle)))
4666 (defun org-hide-archived-subtrees (beg end)
4667 "Re-hide all archived subtrees after a visibility state change."
4668 (save-excursion
4669 (let* ((re (concat ":" org-archive-tag ":")))
4670 (goto-char beg)
4671 (while (re-search-forward re end t)
4672 (when (org-at-heading-p)
4673 (org-flag-subtree t)
4674 (org-end-of-subtree t))))))
4676 (declare-function outline-end-of-heading "outline" ())
4677 (declare-function outline-flag-region "outline" (from to flag))
4678 (defun org-flag-subtree (flag)
4679 (save-excursion
4680 (org-back-to-heading t)
4681 (outline-end-of-heading)
4682 (outline-flag-region (point)
4683 (progn (org-end-of-subtree t) (point))
4684 flag)))
4686 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4688 ;; Declare Column View Code
4690 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4691 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4692 (declare-function org-columns-compute "org-colview" (property))
4694 ;; Declare ID code
4696 (declare-function org-id-store-link "org-id")
4697 (declare-function org-id-locations-load "org-id")
4698 (declare-function org-id-locations-save "org-id")
4699 (defvar org-id-track-globally)
4701 ;;; Variables for pre-computed regular expressions, all buffer local
4703 (defvar org-todo-regexp nil
4704 "Matches any of the TODO state keywords.")
4705 (make-variable-buffer-local 'org-todo-regexp)
4706 (defvar org-not-done-regexp nil
4707 "Matches any of the TODO state keywords except the last one.")
4708 (make-variable-buffer-local 'org-not-done-regexp)
4709 (defvar org-not-done-heading-regexp nil
4710 "Matches a TODO headline that is not done.")
4711 (make-variable-buffer-local 'org-not-done-regexp)
4712 (defvar org-todo-line-regexp nil
4713 "Matches a headline and puts TODO state into group 2 if present.")
4714 (make-variable-buffer-local 'org-todo-line-regexp)
4715 (defvar org-complex-heading-regexp nil
4716 "Matches a headline and puts everything into groups:
4717 group 1: the stars
4718 group 2: The todo keyword, maybe
4719 group 3: Priority cookie
4720 group 4: True headline
4721 group 5: Tags")
4722 (make-variable-buffer-local 'org-complex-heading-regexp)
4723 (defvar org-complex-heading-regexp-format nil
4724 "Printf format to make regexp to match an exact headline.
4725 This regexp will match the headline of any node which has the
4726 exact headline text that is put into the format, but may have any
4727 TODO state, priority and tags.")
4728 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4729 (defvar org-todo-line-tags-regexp nil
4730 "Matches a headline and puts TODO state into group 2 if present.
4731 Also put tags into group 4 if tags are present.")
4732 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4733 (defvar org-ds-keyword-length 12
4734 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4735 (make-variable-buffer-local 'org-ds-keyword-length)
4736 (defvar org-deadline-regexp nil
4737 "Matches the DEADLINE keyword.")
4738 (make-variable-buffer-local 'org-deadline-regexp)
4739 (defvar org-deadline-time-regexp nil
4740 "Matches the DEADLINE keyword together with a time stamp.")
4741 (make-variable-buffer-local 'org-deadline-time-regexp)
4742 (defvar org-deadline-time-hour-regexp nil
4743 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4744 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4745 (defvar org-deadline-line-regexp nil
4746 "Matches the DEADLINE keyword and the rest of the line.")
4747 (make-variable-buffer-local 'org-deadline-line-regexp)
4748 (defvar org-scheduled-regexp nil
4749 "Matches the SCHEDULED keyword.")
4750 (make-variable-buffer-local 'org-scheduled-regexp)
4751 (defvar org-scheduled-time-regexp nil
4752 "Matches the SCHEDULED keyword together with a time stamp.")
4753 (make-variable-buffer-local 'org-scheduled-time-regexp)
4754 (defvar org-scheduled-time-hour-regexp nil
4755 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4756 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4757 (defvar org-closed-time-regexp nil
4758 "Matches the CLOSED keyword together with a time stamp.")
4759 (make-variable-buffer-local 'org-closed-time-regexp)
4761 (defvar org-keyword-time-regexp nil
4762 "Matches any of the 4 keywords, together with the time stamp.")
4763 (make-variable-buffer-local 'org-keyword-time-regexp)
4764 (defvar org-keyword-time-not-clock-regexp nil
4765 "Matches any of the 3 keywords, together with the time stamp.")
4766 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4767 (defvar org-maybe-keyword-time-regexp nil
4768 "Matches a timestamp, possibly preceded by a keyword.")
4769 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4770 (defvar org-all-time-keywords nil
4771 "List of time keywords.")
4772 (make-variable-buffer-local 'org-all-time-keywords)
4774 (defconst org-plain-time-of-day-regexp
4775 (concat
4776 "\\(\\<[012]?[0-9]"
4777 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4778 "\\(--?"
4779 "\\(\\<[012]?[0-9]"
4780 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4781 "\\)?")
4782 "Regular expression to match a plain time or time range.
4783 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4784 groups carry important information:
4785 0 the full match
4786 1 the first time, range or not
4787 8 the second time, if it is a range.")
4789 (defconst org-plain-time-extension-regexp
4790 (concat
4791 "\\(\\<[012]?[0-9]"
4792 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4793 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4794 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4795 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4796 groups carry important information:
4797 0 the full match
4798 7 hours of duration
4799 9 minutes of duration")
4801 (defconst org-stamp-time-of-day-regexp
4802 (concat
4803 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4804 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4805 "\\(--?"
4806 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4807 "Regular expression to match a timestamp time or time range.
4808 After a match, the following groups carry important information:
4809 0 the full match
4810 1 date plus weekday, for back referencing to make sure both times are on the same day
4811 2 the first time, range or not
4812 4 the second time, if it is a range.")
4814 (defconst org-startup-options
4815 '(("fold" org-startup-folded t)
4816 ("overview" org-startup-folded t)
4817 ("nofold" org-startup-folded nil)
4818 ("showall" org-startup-folded nil)
4819 ("showeverything" org-startup-folded showeverything)
4820 ("content" org-startup-folded content)
4821 ("indent" org-startup-indented t)
4822 ("noindent" org-startup-indented nil)
4823 ("hidestars" org-hide-leading-stars t)
4824 ("showstars" org-hide-leading-stars nil)
4825 ("odd" org-odd-levels-only t)
4826 ("oddeven" org-odd-levels-only nil)
4827 ("align" org-startup-align-all-tables t)
4828 ("noalign" org-startup-align-all-tables nil)
4829 ("inlineimages" org-startup-with-inline-images t)
4830 ("noinlineimages" org-startup-with-inline-images nil)
4831 ("latexpreview" org-startup-with-latex-preview t)
4832 ("nolatexpreview" org-startup-with-latex-preview nil)
4833 ("customtime" org-display-custom-times t)
4834 ("logdone" org-log-done time)
4835 ("lognotedone" org-log-done note)
4836 ("nologdone" org-log-done nil)
4837 ("lognoteclock-out" org-log-note-clock-out t)
4838 ("nolognoteclock-out" org-log-note-clock-out nil)
4839 ("logrepeat" org-log-repeat state)
4840 ("lognoterepeat" org-log-repeat note)
4841 ("logdrawer" org-log-into-drawer t)
4842 ("nologdrawer" org-log-into-drawer nil)
4843 ("logstatesreversed" org-log-states-order-reversed t)
4844 ("nologstatesreversed" org-log-states-order-reversed nil)
4845 ("nologrepeat" org-log-repeat nil)
4846 ("logreschedule" org-log-reschedule time)
4847 ("lognotereschedule" org-log-reschedule note)
4848 ("nologreschedule" org-log-reschedule nil)
4849 ("logredeadline" org-log-redeadline time)
4850 ("lognoteredeadline" org-log-redeadline note)
4851 ("nologredeadline" org-log-redeadline nil)
4852 ("logrefile" org-log-refile time)
4853 ("lognoterefile" org-log-refile note)
4854 ("nologrefile" org-log-refile nil)
4855 ("fninline" org-footnote-define-inline t)
4856 ("nofninline" org-footnote-define-inline nil)
4857 ("fnlocal" org-footnote-section nil)
4858 ("fnauto" org-footnote-auto-label t)
4859 ("fnprompt" org-footnote-auto-label nil)
4860 ("fnconfirm" org-footnote-auto-label confirm)
4861 ("fnplain" org-footnote-auto-label plain)
4862 ("fnadjust" org-footnote-auto-adjust t)
4863 ("nofnadjust" org-footnote-auto-adjust nil)
4864 ("constcgs" constants-unit-system cgs)
4865 ("constSI" constants-unit-system SI)
4866 ("noptag" org-tag-persistent-alist nil)
4867 ("hideblocks" org-hide-block-startup t)
4868 ("nohideblocks" org-hide-block-startup nil)
4869 ("beamer" org-startup-with-beamer-mode t)
4870 ("entitiespretty" org-pretty-entities t)
4871 ("entitiesplain" org-pretty-entities nil))
4872 "Variable associated with STARTUP options for org-mode.
4873 Each element is a list of three items: the startup options (as written
4874 in the #+STARTUP line), the corresponding variable, and the value to set
4875 this variable to if the option is found. An optional forth element PUSH
4876 means to push this value onto the list in the variable.")
4878 (defun org-update-property-plist (key val props)
4879 "Update PROPS with KEY and VAL."
4880 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4881 (key (if appending (substring key 0 (- (length key) 1)) key))
4882 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4883 (previous (cdr (assoc key props))))
4884 (if appending
4885 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4886 (cons (cons key val) remainder))))
4888 (defcustom org-group-tags t
4889 "When non-nil (the default), use group tags.
4890 This can be turned on/off through `org-toggle-tags-groups'."
4891 :group 'org-tags
4892 :group 'org-startup
4893 :type 'boolean)
4895 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4897 (defun org-toggle-tags-groups ()
4898 "Toggle support for group tags.
4899 Support for group tags is controlled by the option
4900 `org-group-tags', which is non-nil by default."
4901 (interactive)
4902 (setq org-group-tags (not org-group-tags))
4903 (cond ((and (derived-mode-p 'org-agenda-mode)
4904 org-group-tags)
4905 (org-agenda-redo))
4906 ((derived-mode-p 'org-mode)
4907 (let ((org-inhibit-startup t)) (org-mode))))
4908 (message "Groups tags support has been turned %s"
4909 (if org-group-tags "on" "off")))
4911 (defun org-set-regexps-and-options-for-tags ()
4912 "Precompute variables used for tags."
4913 (when (derived-mode-p 'org-mode)
4914 (org-set-local 'org-file-tags nil)
4915 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4916 (splitre "[ \t]+")
4917 (start 0)
4918 tags ftags key value)
4919 (save-excursion
4920 (save-restriction
4921 (widen)
4922 (goto-char (point-min))
4923 (while (re-search-forward re nil t)
4924 (setq key (upcase (org-match-string-no-properties 1))
4925 value (org-match-string-no-properties 2))
4926 (if (stringp value) (setq value (org-trim value)))
4927 (cond
4928 ((equal key "TAGS")
4929 (setq tags (append tags (if tags '("\\n") nil)
4930 (org-split-string value splitre))))
4931 ((equal key "FILETAGS")
4932 (when (string-match "\\S-" value)
4933 (setq ftags
4934 (append
4935 ftags
4936 (apply 'append
4937 (mapcar (lambda (x) (org-split-string x ":"))
4938 (org-split-string value)))))))))))
4939 ;; Process the file tags.
4940 (and ftags (org-set-local 'org-file-tags
4941 (mapcar 'org-add-prop-inherited ftags)))
4942 (org-set-local 'org-tag-groups-alist nil)
4943 ;; Process the tags.
4944 (when (and (not tags) org-tag-alist)
4945 (setq tags
4946 (mapcar
4947 (lambda (tg) (cond ((eq (car tg) :startgroup) "{")
4948 ((eq (car tg) :endgroup) "}")
4949 ((eq (car tg) :grouptags) ":")
4950 ((eq (car tg) :newline) "\n")
4951 (t (concat (car tg)
4952 (if (characterp (cdr tg))
4953 (format "(%s)" (char-to-string (cdr tg))) "")))))
4954 org-tag-alist)))
4955 (let (e tgs g)
4956 (while (setq e (pop tags))
4957 (cond
4958 ((equal e "{")
4959 (progn (push '(:startgroup) tgs)
4960 (when (equal (nth 1 tags) ":")
4961 (push (list (replace-regexp-in-string
4962 "(.+)$" "" (nth 0 tags)))
4963 org-tag-groups-alist)
4964 (setq g 0))))
4965 ((equal e ":") (push '(:grouptags) tgs))
4966 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4967 ((equal e "\\n") (push '(:newline) tgs))
4968 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4969 (push (cons (match-string 1 e)
4970 (string-to-char (match-string 2 e))) tgs)
4971 (if (and g (> g 0))
4972 (setcar org-tag-groups-alist
4973 (append (car org-tag-groups-alist)
4974 (list (match-string 1 e)))))
4975 (if g (setq g (1+ g))))
4976 (t (push (list e) tgs)
4977 (if (and g (> g 0))
4978 (setcar org-tag-groups-alist
4979 (append (car org-tag-groups-alist) (list e))))
4980 (if g (setq g (1+ g))))))
4981 (org-set-local 'org-tag-alist nil)
4982 (while (setq e (pop tgs))
4983 (or (and (stringp (car e))
4984 (assoc (car e) org-tag-alist))
4985 (push e org-tag-alist)))
4986 ;; Return a list with tag variables
4987 (list org-file-tags org-tag-alist org-tag-groups-alist)))))
4989 (defvar org-ota nil)
4990 (defun org-set-regexps-and-options ()
4991 "Precompute regular expressions used in the current buffer."
4992 (when (derived-mode-p 'org-mode)
4993 (org-set-local 'org-todo-kwd-alist nil)
4994 (org-set-local 'org-todo-key-alist nil)
4995 (org-set-local 'org-todo-key-trigger nil)
4996 (org-set-local 'org-todo-keywords-1 nil)
4997 (org-set-local 'org-done-keywords nil)
4998 (org-set-local 'org-todo-heads nil)
4999 (org-set-local 'org-todo-sets nil)
5000 (org-set-local 'org-todo-log-states nil)
5001 (org-set-local 'org-file-properties nil)
5002 (let ((re (org-make-options-regexp
5003 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
5004 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
5005 "SETUPFILE" "OPTIONS")
5006 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
5007 (splitre "[ \t]+")
5008 (scripts org-use-sub-superscripts)
5009 kwds kws0 kwsa key log value cat arch const links hw dws
5010 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
5011 (start 0))
5012 (save-excursion
5013 (save-restriction
5014 (widen)
5015 (goto-char (point-min))
5016 (while
5017 (or (and
5018 ext-setup-or-nil
5019 (not org-ota)
5020 (let (ret)
5021 (with-temp-buffer
5022 (insert ext-setup-or-nil)
5023 (let ((major-mode 'org-mode) org-ota)
5024 (setq ret (save-match-data
5025 (org-set-regexps-and-options-for-tags)))))
5026 ;; Append setupfile tags to existing tags
5027 (setq org-ota t)
5028 (setq org-file-tags
5029 (delq nil (append org-file-tags (nth 0 ret)))
5030 org-tag-alist
5031 (delq nil (append org-tag-alist (nth 1 ret)))
5032 org-tag-groups-alist
5033 (delq nil (append org-tag-groups-alist (nth 2 ret))))))
5034 (and ext-setup-or-nil
5035 (string-match re ext-setup-or-nil start)
5036 (setq start (match-end 0)))
5037 (and (setq ext-setup-or-nil nil start 0)
5038 (re-search-forward re nil t)))
5039 (setq key (upcase (match-string 1 ext-setup-or-nil))
5040 value (org-match-string-no-properties 2 ext-setup-or-nil))
5041 (if (stringp value) (setq value (org-trim value)))
5042 (cond
5043 ((equal key "CATEGORY")
5044 (setq cat value))
5045 ((member key '("SEQ_TODO" "TODO"))
5046 (push (cons 'sequence (org-split-string value splitre)) kwds))
5047 ((equal key "TYP_TODO")
5048 (push (cons 'type (org-split-string value splitre)) kwds))
5049 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
5050 ;; general TODO-like setup
5051 (push (cons (intern (downcase (match-string 1 key)))
5052 (org-split-string value splitre)) kwds))
5053 ((equal key "COLUMNS")
5054 (org-set-local 'org-columns-default-format value))
5055 ((equal key "LINK")
5056 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5057 (push (cons (match-string 1 value)
5058 (org-trim (match-string 2 value)))
5059 links)))
5060 ((equal key "PRIORITIES")
5061 (setq prio (org-split-string value " +")))
5062 ((equal key "PROPERTY")
5063 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
5064 (setq props (org-update-property-plist (match-string 1 value)
5065 (match-string 2 value)
5066 props))))
5067 ((equal key "CONSTANTS")
5068 (org-table-set-constants))
5069 ((equal key "STARTUP")
5070 (let ((opts (org-split-string value splitre))
5071 l var val)
5072 (while (setq l (pop opts))
5073 (when (setq l (assoc l org-startup-options))
5074 (setq var (nth 1 l) val (nth 2 l))
5075 (if (not (nth 3 l))
5076 (set (make-local-variable var) val)
5077 (if (not (listp (symbol-value var)))
5078 (set (make-local-variable var) nil))
5079 (set (make-local-variable var) (symbol-value var))
5080 (add-to-list var val))))))
5081 ((equal key "ARCHIVE")
5082 (setq arch value)
5083 (remove-text-properties 0 (length arch)
5084 '(face t fontified t) arch))
5085 ((equal key "OPTIONS")
5086 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
5087 (setq scripts (read (match-string 2 value)))))
5088 ((and (equal key "SETUPFILE")
5089 ;; Prevent checking in Gnus messages
5090 (not buffer-read-only))
5091 (setq setup-contents (org-file-contents
5092 (expand-file-name
5093 (org-remove-double-quotes value))
5094 'noerror))
5095 (if (not ext-setup-or-nil)
5096 (setq ext-setup-or-nil setup-contents start 0)
5097 (setq ext-setup-or-nil
5098 (concat (substring ext-setup-or-nil 0 start)
5099 "\n" setup-contents "\n"
5100 (substring ext-setup-or-nil start)))))))
5101 ;; search for property blocks
5102 (goto-char (point-min))
5103 (while (re-search-forward org-block-regexp nil t)
5104 (when (equal "PROPERTY" (upcase (match-string 1)))
5105 (setq value (replace-regexp-in-string
5106 "[\n\r]" " " (match-string 4)))
5107 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
5108 (setq props (org-update-property-plist (match-string 1 value)
5109 (match-string 2 value)
5110 props)))))))
5111 (org-set-local 'org-use-sub-superscripts scripts)
5112 (when cat
5113 (org-set-local 'org-category (intern cat))
5114 (push (cons "CATEGORY" cat) props))
5115 (when prio
5116 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
5117 (setq prio (mapcar 'string-to-char prio))
5118 (org-set-local 'org-highest-priority (nth 0 prio))
5119 (org-set-local 'org-lowest-priority (nth 1 prio))
5120 (org-set-local 'org-default-priority (nth 2 prio)))
5121 (and props (org-set-local 'org-file-properties (nreverse props)))
5122 (and arch (org-set-local 'org-archive-location arch))
5123 (and links (setq org-link-abbrev-alist-local (nreverse links)))
5124 ;; Process the TODO keywords
5125 (unless kwds
5126 ;; Use the global values as if they had been given locally.
5127 (setq kwds (default-value 'org-todo-keywords))
5128 (if (stringp (car kwds))
5129 (setq kwds (list (cons org-todo-interpretation
5130 (default-value 'org-todo-keywords)))))
5131 (setq kwds (reverse kwds)))
5132 (setq kwds (nreverse kwds))
5133 (let (inter kws kw)
5134 (while (setq kws (pop kwds))
5135 (let ((kws (or
5136 (run-hook-with-args-until-success
5137 'org-todo-setup-filter-hook kws)
5138 kws)))
5139 (setq inter (pop kws) sep (member "|" kws)
5140 kws0 (delete "|" (copy-sequence kws))
5141 kwsa nil
5142 kws1 (mapcar
5143 (lambda (x)
5144 ;; 1 2
5145 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
5146 (progn
5147 (setq kw (match-string 1 x)
5148 key (and (match-end 2) (match-string 2 x))
5149 log (org-extract-log-state-settings x))
5150 (push (cons kw (and key (string-to-char key))) kwsa)
5151 (and log (push log org-todo-log-states))
5153 (error "Invalid TODO keyword %s" x)))
5154 kws0)
5155 kwsa (if kwsa (append '((:startgroup))
5156 (nreverse kwsa)
5157 '((:endgroup))))
5158 hw (car kws1)
5159 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
5160 tail (list inter hw (car dws) (org-last dws))))
5161 (add-to-list 'org-todo-heads hw 'append)
5162 (push kws1 org-todo-sets)
5163 (setq org-done-keywords (append org-done-keywords dws nil))
5164 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
5165 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
5166 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
5167 (setq org-todo-sets (nreverse org-todo-sets)
5168 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5169 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
5170 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
5171 ;; Compute the regular expressions and other local variables.
5172 ;; Using `org-outline-regexp-bol' would complicate them much,
5173 ;; because of the fixed white space at the end of that string.
5174 (if (not org-done-keywords)
5175 (setq org-done-keywords (and org-todo-keywords-1
5176 (list (org-last org-todo-keywords-1)))))
5177 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5178 (length org-scheduled-string)
5179 (length org-clock-string)
5180 (length org-closed-string)))
5181 org-not-done-keywords
5182 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5183 org-todo-regexp
5184 (concat "\\("
5185 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5186 "\\)")
5187 org-not-done-regexp
5188 (concat "\\("
5189 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5190 "\\)")
5191 org-not-done-heading-regexp
5192 (format org-heading-keyword-regexp-format org-not-done-regexp)
5193 org-todo-line-regexp
5194 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5195 org-complex-heading-regexp
5196 (concat "^\\(\\*+\\)"
5197 "\\(?: +" org-todo-regexp "\\)?"
5198 "\\(?: +\\(\\[#.\\]\\)\\)?"
5199 "\\(?: +\\(.*?\\)\\)??"
5200 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5201 "[ \t]*$")
5202 org-complex-heading-regexp-format
5203 (concat "^\\(\\*+\\)"
5204 "\\(?: +" org-todo-regexp "\\)?"
5205 "\\(?: +\\(\\[#.\\]\\)\\)?"
5206 "\\(?: +"
5207 ;; Stats cookies can be stuck to body.
5208 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5209 "\\(%s\\)"
5210 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5211 "\\)"
5212 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5213 "[ \t]*$")
5214 org-todo-line-tags-regexp
5215 (concat "^\\(\\*+\\)"
5216 "\\(?: +" org-todo-regexp "\\)?"
5217 "\\(?: +\\(.*?\\)\\)??"
5218 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5219 "[ \t]*$")
5220 org-deadline-regexp (concat "\\<" org-deadline-string)
5221 org-deadline-time-regexp
5222 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5223 org-deadline-time-hour-regexp
5224 (concat "\\<" org-deadline-string
5225 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5226 org-deadline-line-regexp
5227 (concat "\\<\\(" org-deadline-string "\\).*")
5228 org-scheduled-regexp
5229 (concat "\\<" org-scheduled-string)
5230 org-scheduled-time-regexp
5231 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5232 org-scheduled-time-hour-regexp
5233 (concat "\\<" org-scheduled-string
5234 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5235 org-closed-time-regexp
5236 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5237 org-keyword-time-regexp
5238 (concat "\\<\\(" org-scheduled-string
5239 "\\|" org-deadline-string
5240 "\\|" org-closed-string
5241 "\\|" org-clock-string "\\)"
5242 " *[[<]\\([^]>]+\\)[]>]")
5243 org-keyword-time-not-clock-regexp
5244 (concat "\\<\\(" org-scheduled-string
5245 "\\|" org-deadline-string
5246 "\\|" org-closed-string
5247 "\\)"
5248 " *[[<]\\([^]>]+\\)[]>]")
5249 org-maybe-keyword-time-regexp
5250 (concat "\\(\\<\\(" org-scheduled-string
5251 "\\|" org-deadline-string
5252 "\\|" org-closed-string
5253 "\\|" org-clock-string "\\)\\)?"
5254 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5255 org-all-time-keywords
5256 (mapcar (lambda (w) (substring w 0 -1))
5257 (list org-scheduled-string org-deadline-string
5258 org-clock-string org-closed-string)))
5259 (setq org-ota nil)
5260 (org-compute-latex-and-related-regexp))))
5262 (defun org-file-contents (file &optional noerror)
5263 "Return the contents of FILE, as a string."
5264 (if (and file (file-readable-p file))
5265 (with-temp-buffer
5266 (insert-file-contents file)
5267 (buffer-string))
5268 (funcall (if noerror 'message 'error)
5269 "Cannot read file \"%s\"%s"
5270 file
5271 (let ((from (buffer-file-name (buffer-base-buffer))))
5272 (if from (concat " (referenced in file \"" from "\")") "")))))
5274 (defun org-extract-log-state-settings (x)
5275 "Extract the log state setting from a TODO keyword string.
5276 This will extract info from a string like \"WAIT(w@/!)\"."
5277 (let (kw key log1 log2)
5278 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5279 (setq kw (match-string 1 x)
5280 key (and (match-end 2) (match-string 2 x))
5281 log1 (and (match-end 3) (match-string 3 x))
5282 log2 (and (match-end 4) (match-string 4 x)))
5283 (and (or log1 log2)
5284 (list kw
5285 (and log1 (if (equal log1 "!") 'time 'note))
5286 (and log2 (if (equal log2 "!") 'time 'note)))))))
5288 (defun org-remove-keyword-keys (list)
5289 "Remove a pair of parenthesis at the end of each string in LIST."
5290 (mapcar (lambda (x)
5291 (if (string-match "(.*)$" x)
5292 (substring x 0 (match-beginning 0))
5294 list))
5296 (defun org-assign-fast-keys (alist)
5297 "Assign fast keys to a keyword-key alist.
5298 Respect keys that are already there."
5299 (let (new e (alt ?0))
5300 (while (setq e (pop alist))
5301 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5302 (cdr e)) ;; Key already assigned.
5303 (push e new)
5304 (let ((clist (string-to-list (downcase (car e))))
5305 (used (append new alist)))
5306 (when (= (car clist) ?@)
5307 (pop clist))
5308 (while (and clist (rassoc (car clist) used))
5309 (pop clist))
5310 (unless clist
5311 (while (rassoc alt used)
5312 (incf alt)))
5313 (push (cons (car e) (or (car clist) alt)) new))))
5314 (nreverse new)))
5316 ;;; Some variables used in various places
5318 (defvar org-window-configuration nil
5319 "Used in various places to store a window configuration.")
5320 (defvar org-selected-window nil
5321 "Used in various places to store a window configuration.")
5322 (defvar org-finish-function nil
5323 "Function to be called when `C-c C-c' is used.
5324 This is for getting out of special buffers like capture.")
5327 ;; FIXME: Occasionally check by commenting these, to make sure
5328 ;; no other functions uses these, forgetting to let-bind them.
5329 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5330 (defvar org-last-state)
5331 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5333 ;; Defined somewhere in this file, but used before definition.
5334 (defvar org-entities) ;; defined in org-entities.el
5335 (defvar org-struct-menu)
5336 (defvar org-org-menu)
5337 (defvar org-tbl-menu)
5339 ;;;; Define the Org-mode
5341 ;; We use a before-change function to check if a table might need
5342 ;; an update.
5343 (defvar org-table-may-need-update t
5344 "Indicates that a table might need an update.
5345 This variable is set by `org-before-change-function'.
5346 `org-table-align' sets it back to nil.")
5347 (defun org-before-change-function (beg end)
5348 "Every change indicates that a table might need an update."
5349 (setq org-table-may-need-update t))
5350 (defvar org-mode-map)
5351 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5352 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5353 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5354 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5355 (defvar org-table-buffer-is-an nil)
5357 (defvar bidi-paragraph-direction)
5358 (defvar buffer-face-mode-face)
5360 (require 'outline)
5361 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5362 (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"))
5363 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5365 ;; Other stuff we need.
5366 (require 'time-date)
5367 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5368 (require 'easymenu)
5369 (require 'overlay)
5371 ;; (require 'org-macs) moved higher up in the file before it is first used
5372 (require 'org-entities)
5373 ;; (require 'org-compat) moved higher up in the file before it is first used
5374 (require 'org-faces)
5375 (require 'org-list)
5376 (require 'org-pcomplete)
5377 (require 'org-src)
5378 (require 'org-footnote)
5379 (require 'org-macro)
5381 ;; babel
5382 (require 'ob)
5384 ;;;###autoload
5385 (define-derived-mode org-mode outline-mode "Org"
5386 "Outline-based notes management and organizer, alias
5387 \"Carsten's outline-mode for keeping track of everything.\"
5389 Org-mode develops organizational tasks around a NOTES file which
5390 contains information about projects as plain text. Org-mode is
5391 implemented on top of outline-mode, which is ideal to keep the content
5392 of large files well structured. It supports ToDo items, deadlines and
5393 time stamps, which magically appear in the diary listing of the Emacs
5394 calendar. Tables are easily created with a built-in table editor.
5395 Plain text URL-like links connect to websites, emails (VM), Usenet
5396 messages (Gnus), BBDB entries, and any files related to the project.
5397 For printing and sharing of notes, an Org-mode file (or a part of it)
5398 can be exported as a structured ASCII or HTML file.
5400 The following commands are available:
5402 \\{org-mode-map}"
5404 ;; Get rid of Outline menus, they are not needed
5405 ;; Need to do this here because define-derived-mode sets up
5406 ;; the keymap so late. Still, it is a waste to call this each time
5407 ;; we switch another buffer into org-mode.
5408 (if (featurep 'xemacs)
5409 (when (boundp 'outline-mode-menu-heading)
5410 ;; Assume this is Greg's port, it uses easymenu
5411 (easy-menu-remove outline-mode-menu-heading)
5412 (easy-menu-remove outline-mode-menu-show)
5413 (easy-menu-remove outline-mode-menu-hide))
5414 (define-key org-mode-map [menu-bar headings] 'undefined)
5415 (define-key org-mode-map [menu-bar hide] 'undefined)
5416 (define-key org-mode-map [menu-bar show] 'undefined))
5418 (org-load-modules-maybe)
5419 (easy-menu-add org-org-menu)
5420 (easy-menu-add org-tbl-menu)
5421 (org-install-agenda-files-menu)
5422 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5423 (add-to-invisibility-spec '(org-cwidth))
5424 (add-to-invisibility-spec '(org-hide-block . t))
5425 (when (featurep 'xemacs)
5426 (org-set-local 'line-move-ignore-invisible t))
5427 (org-set-local 'outline-regexp org-outline-regexp)
5428 (org-set-local 'outline-level 'org-outline-level)
5429 (setq bidi-paragraph-direction 'left-to-right)
5430 (when (and org-ellipsis
5431 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5432 (fboundp 'make-glyph-code))
5433 (unless org-display-table
5434 (setq org-display-table (make-display-table)))
5435 (set-display-table-slot
5436 org-display-table 4
5437 (vconcat (mapcar
5438 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5439 org-ellipsis)))
5440 (if (stringp org-ellipsis) org-ellipsis "..."))))
5441 (setq buffer-display-table org-display-table))
5442 (org-set-regexps-and-options-for-tags)
5443 (org-set-regexps-and-options)
5444 (org-set-font-lock-defaults)
5445 (when (and org-tag-faces (not org-tags-special-faces-re))
5446 ;; tag faces set outside customize.... force initialization.
5447 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5448 ;; Calc embedded
5449 (org-set-local 'calc-embedded-open-mode "# ")
5450 ;; Modify a few syntax entries
5451 (modify-syntax-entry ?@ "w")
5452 (modify-syntax-entry ?\" "\"")
5453 (modify-syntax-entry ?\\ "_")
5454 (modify-syntax-entry ?~ "_")
5455 (if org-startup-truncated (setq truncate-lines t))
5456 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5457 (org-set-local 'font-lock-unfontify-region-function
5458 'org-unfontify-region)
5459 ;; Activate before-change-function
5460 (org-set-local 'org-table-may-need-update t)
5461 (org-add-hook 'before-change-functions 'org-before-change-function nil
5462 'local)
5463 ;; Check for running clock before killing a buffer
5464 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5465 ;; Initialize macros templates.
5466 (org-macro-initialize-templates)
5467 ;; Initialize radio targets.
5468 (org-update-radio-target-regexp)
5469 ;; Indentation.
5470 (org-set-local 'indent-line-function 'org-indent-line)
5471 (org-set-local 'indent-region-function 'org-indent-region)
5472 ;; Filling and auto-filling.
5473 (org-setup-filling)
5474 ;; Comments.
5475 (org-setup-comments-handling)
5476 ;; Initialize cache.
5477 (org-element-cache-reset)
5478 ;; Beginning/end of defun
5479 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5480 (org-set-local 'end-of-defun-function
5481 (lambda ()
5482 (if (not (org-at-heading-p))
5483 (org-forward-element)
5484 (org-forward-element)
5485 (forward-char -1))))
5486 ;; Next error for sparse trees
5487 (org-set-local 'next-error-function 'org-occur-next-match)
5488 ;; Make sure dependence stuff works reliably, even for users who set it
5489 ;; too late :-(
5490 (if org-enforce-todo-dependencies
5491 (add-hook 'org-blocker-hook
5492 'org-block-todo-from-children-or-siblings-or-parent)
5493 (remove-hook 'org-blocker-hook
5494 'org-block-todo-from-children-or-siblings-or-parent))
5495 (if org-enforce-todo-checkbox-dependencies
5496 (add-hook 'org-blocker-hook
5497 'org-block-todo-from-checkboxes)
5498 (remove-hook 'org-blocker-hook
5499 'org-block-todo-from-checkboxes))
5501 ;; Align options lines
5502 (org-set-local
5503 'align-mode-rules-list
5504 '((org-in-buffer-settings
5505 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5506 (modes . '(org-mode)))))
5508 ;; Imenu
5509 (org-set-local 'imenu-create-index-function
5510 'org-imenu-get-tree)
5512 ;; Make isearch reveal context
5513 (if (or (featurep 'xemacs)
5514 (not (boundp 'outline-isearch-open-invisible-function)))
5515 ;; Emacs 21 and XEmacs make use of the hook
5516 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5517 ;; Emacs 22 deals with this through a special variable
5518 (org-set-local 'outline-isearch-open-invisible-function
5519 (lambda (&rest ignore) (org-show-context 'isearch)))
5520 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5522 ;; Setup the pcomplete hooks
5523 (set (make-local-variable 'pcomplete-command-completion-function)
5524 'org-pcomplete-initial)
5525 (set (make-local-variable 'pcomplete-command-name-function)
5526 'org-command-at-point)
5527 (set (make-local-variable 'pcomplete-default-completion-function)
5528 'ignore)
5529 (set (make-local-variable 'pcomplete-parse-arguments-function)
5530 'org-parse-arguments)
5531 (set (make-local-variable 'pcomplete-termination-string) "")
5532 (when (>= emacs-major-version 23)
5533 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5535 ;; If empty file that did not turn on org-mode automatically, make it to.
5536 (if (and org-insert-mode-line-in-empty-file
5537 (org-called-interactively-p 'any)
5538 (= (point-min) (point-max)))
5539 (insert "# -*- mode: org -*-\n\n"))
5540 (unless org-inhibit-startup
5541 (org-unmodified
5542 (and org-startup-with-beamer-mode (org-beamer-mode))
5543 (when org-startup-align-all-tables
5544 (org-table-map-tables 'org-table-align 'quietly))
5545 (when org-startup-with-inline-images
5546 (org-display-inline-images))
5547 (when org-startup-with-latex-preview
5548 (org-preview-latex-fragment))
5549 (unless org-inhibit-startup-visibility-stuff
5550 (org-set-startup-visibility))
5551 (org-refresh-effort-properties)))
5552 ;; Try to set org-hide correctly
5553 (let ((foreground (org-find-invisible-foreground)))
5554 (if foreground
5555 (set-face-foreground 'org-hide foreground))))
5557 ;; Update `customize-package-emacs-version-alist'
5558 (add-to-list 'customize-package-emacs-version-alist
5559 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5560 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5561 ("8.2.6" . "24.4")))
5563 (defvar org-mode-transpose-word-syntax-table
5564 (let ((st (make-syntax-table)))
5565 (mapc (lambda(c) (modify-syntax-entry
5566 (string-to-char (car c)) "w p" st))
5567 org-emphasis-alist)
5568 st))
5570 (when (fboundp 'abbrev-table-put)
5571 (abbrev-table-put org-mode-abbrev-table
5572 :parents (list text-mode-abbrev-table)))
5574 (defsubst org-fix-ellipsis-at-bol ()
5575 (save-excursion (goto-char (window-start)) (recenter 0)))
5577 (defun org-find-invisible-foreground ()
5578 (let ((candidates (remove
5579 "unspecified-bg"
5580 (nconc
5581 (list (face-background 'default)
5582 (face-background 'org-default))
5583 (mapcar
5584 (lambda (alist)
5585 (when (boundp alist)
5586 (cdr (assoc 'background-color (symbol-value alist)))))
5587 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5588 (list (face-foreground 'org-hide))))))
5589 (car (remove nil candidates))))
5591 (defun org-current-time (&optional rounding-minutes past)
5592 "Current time, possibly rounded to ROUNDING-MINUTES.
5593 When ROUNDING-MINUTES is not an integer, fall back on the car of
5594 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5595 the rounding returns a past time."
5596 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5597 (car org-time-stamp-rounding-minutes)))
5598 (time (decode-time)) res)
5599 (if (< r 1)
5600 (current-time)
5601 (setq res
5602 (apply 'encode-time
5603 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5604 (nthcdr 2 time))))
5605 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5606 (seconds-to-time (- (org-float-time res) (* r 60)))
5607 res))))
5609 (defun org-today ()
5610 "Return today date, considering `org-extend-today-until'."
5611 (time-to-days
5612 (time-subtract (current-time)
5613 (list 0 (* 3600 org-extend-today-until) 0))))
5615 ;;;; Font-Lock stuff, including the activators
5617 (defvar org-mouse-map (make-sparse-keymap))
5618 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5619 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5620 (when org-mouse-1-follows-link
5621 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5622 (when org-tab-follows-link
5623 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5624 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5626 (require 'font-lock)
5628 (defconst org-non-link-chars "]\t\n\r<>")
5629 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "file+emacs"
5630 "file+sys" "news" "shell" "elisp" "doi" "message"
5631 "help"))
5632 (defvar org-link-types-re nil
5633 "Matches a link that has a url-like prefix like \"http:\"")
5634 (defvar org-link-re-with-space nil
5635 "Matches a link with spaces, optional angular brackets around it.")
5636 (defvar org-link-re-with-space2 nil
5637 "Matches a link with spaces, optional angular brackets around it.")
5638 (defvar org-link-re-with-space3 nil
5639 "Matches a link with spaces, only for internal part in bracket links.")
5640 (defvar org-angle-link-re nil
5641 "Matches link with angular brackets, spaces are allowed.")
5642 (defvar org-plain-link-re nil
5643 "Matches plain link, without spaces.")
5644 (defvar org-bracket-link-regexp nil
5645 "Matches a link in double brackets.")
5646 (defvar org-bracket-link-analytic-regexp nil
5647 "Regular expression used to analyze links.
5648 Here is what the match groups contain after a match:
5649 1: http:
5650 2: http
5651 3: path
5652 4: [desc]
5653 5: desc")
5654 (defvar org-bracket-link-analytic-regexp++ nil
5655 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5656 (defvar org-any-link-re nil
5657 "Regular expression matching any link.")
5659 (defconst org-match-sexp-depth 3
5660 "Number of stacked braces for sub/superscript matching.")
5662 (defun org-create-multibrace-regexp (left right n)
5663 "Create a regular expression which will match a balanced sexp.
5664 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5665 as single character strings.
5666 The regexp returned will match the entire expression including the
5667 delimiters. It will also define a single group which contains the
5668 match except for the outermost delimiters. The maximum depth of
5669 stacked delimiters is N. Escaping delimiters is not possible."
5670 (let* ((nothing (concat "[^" left right "]*?"))
5671 (or "\\|")
5672 (re nothing)
5673 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5674 (while (> n 1)
5675 (setq n (1- n)
5676 re (concat re or next)
5677 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5678 (concat left "\\(" re "\\)" right)))
5680 (defconst org-match-substring-regexp
5681 (concat
5682 "\\(\\S-\\)\\([_^]\\)\\("
5683 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5684 "\\|"
5685 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5686 "\\|"
5687 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5688 "The regular expression matching a sub- or superscript.")
5690 (defconst org-match-substring-with-braces-regexp
5691 (concat
5692 "\\(\\S-\\)\\([_^]\\)"
5693 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5694 "The regular expression matching a sub- or superscript, forcing braces.")
5696 (defun org-make-link-regexps ()
5697 "Update the link regular expressions.
5698 This should be called after the variable `org-link-types' has changed."
5699 (let ((types-re (regexp-opt org-link-types t)))
5700 (setq org-link-types-re
5701 (concat "\\`" types-re ":")
5702 org-link-re-with-space
5703 (concat "<?" types-re ":"
5704 "\\([^" org-non-link-chars " ]"
5705 "[^" org-non-link-chars "]*"
5706 "[^" org-non-link-chars " ]\\)>?")
5707 org-link-re-with-space2
5708 (concat "<?" types-re ":"
5709 "\\([^" org-non-link-chars " ]"
5710 "[^\t\n\r]*"
5711 "[^" org-non-link-chars " ]\\)>?")
5712 org-link-re-with-space3
5713 (concat "<?" types-re ":"
5714 "\\([^" org-non-link-chars " ]"
5715 "[^\t\n\r]*\\)")
5716 org-angle-link-re
5717 (concat "<" types-re ":"
5718 "\\([^" org-non-link-chars " ]"
5719 "[^" org-non-link-chars "]*"
5720 "\\)>")
5721 org-plain-link-re
5722 (concat
5723 "\\<" types-re ":"
5724 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5725 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5726 org-bracket-link-regexp
5727 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5728 org-bracket-link-analytic-regexp
5729 (concat
5730 "\\[\\["
5731 "\\(" types-re ":\\)?"
5732 "\\([^]]+\\)"
5733 "\\]"
5734 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5735 "\\]")
5736 org-bracket-link-analytic-regexp++
5737 (concat
5738 "\\[\\["
5739 "\\(" (regexp-opt (cons "coderef" org-link-types) t) ":\\)?"
5740 "\\([^]]+\\)"
5741 "\\]"
5742 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5743 "\\]")
5744 org-any-link-re
5745 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5746 org-angle-link-re "\\)\\|\\("
5747 org-plain-link-re "\\)"))))
5749 (org-make-link-regexps)
5751 (defvar org-emph-face nil)
5753 (defun org-do-emphasis-faces (limit)
5754 "Run through the buffer and emphasize strings."
5755 (let (rtn a)
5756 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5757 (let* ((border (char-after (match-beginning 3)))
5758 (bre (regexp-quote (char-to-string border))))
5759 (if (and (not (= border (char-after (match-beginning 4))))
5760 (not (save-match-data
5761 (string-match (concat bre ".*" bre)
5762 (replace-regexp-in-string
5763 "\n" " "
5764 (substring (match-string 2) 1 -1))))))
5765 (progn
5766 (setq rtn t)
5767 (setq a (assoc (match-string 3) org-emphasis-alist))
5768 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5769 'face
5770 (nth 1 a))
5771 (and (nth 2 a)
5772 (org-remove-flyspell-overlays-in
5773 (match-beginning 0) (match-end 0)))
5774 (add-text-properties (match-beginning 2) (match-end 2)
5775 '(font-lock-multiline t org-emphasis t))
5776 (when org-hide-emphasis-markers
5777 (add-text-properties (match-end 4) (match-beginning 5)
5778 '(invisible org-link))
5779 (add-text-properties (match-beginning 3) (match-end 3)
5780 '(invisible org-link))))))
5781 (goto-char (1+ (match-beginning 0))))
5782 rtn))
5784 (defun org-emphasize (&optional char)
5785 "Insert or change an emphasis, i.e. a font like bold or italic.
5786 If there is an active region, change that region to a new emphasis.
5787 If there is no region, just insert the marker characters and position
5788 the cursor between them.
5789 CHAR should be the marker character. If it is a space, it means to
5790 remove the emphasis of the selected region.
5791 If CHAR is not given (for example in an interactive call) it will be
5792 prompted for."
5793 (interactive)
5794 (let ((erc org-emphasis-regexp-components)
5795 (prompt "")
5796 (string "") beg end move c s)
5797 (if (org-region-active-p)
5798 (setq beg (region-beginning) end (region-end)
5799 string (buffer-substring beg end))
5800 (setq move t))
5802 (unless char
5803 (message "Emphasis marker or tag: [%s]"
5804 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5805 (setq char (read-char-exclusive)))
5806 (if (equal char ?\ )
5807 (setq s "" move nil)
5808 (unless (assoc (char-to-string char) org-emphasis-alist)
5809 (user-error "No such emphasis marker: \"%c\"" char))
5810 (setq s (char-to-string char)))
5811 (while (and (> (length string) 1)
5812 (equal (substring string 0 1) (substring string -1))
5813 (assoc (substring string 0 1) org-emphasis-alist))
5814 (setq string (substring string 1 -1)))
5815 (setq string (concat s string s))
5816 (if beg (delete-region beg end))
5817 (unless (or (bolp)
5818 (string-match (concat "[" (nth 0 erc) "\n]")
5819 (char-to-string (char-before (point)))))
5820 (insert " "))
5821 (unless (or (eobp)
5822 (string-match (concat "[" (nth 1 erc) "\n]")
5823 (char-to-string (char-after (point)))))
5824 (insert " ") (backward-char 1))
5825 (insert string)
5826 (and move (backward-char 1))))
5828 (defconst org-nonsticky-props
5829 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5831 (defsubst org-rear-nonsticky-at (pos)
5832 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5834 (defun org-activate-plain-links (limit)
5835 "Run through the buffer and add overlays to links."
5836 (let (f hl)
5837 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5838 (not (org-in-src-block-p)))
5839 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5840 (setq f (get-text-property (match-beginning 0) 'face))
5841 (setq hl (org-match-string-no-properties 0))
5842 (if (or (eq f 'org-tag)
5843 (and (listp f) (memq 'org-tag f)))
5845 (add-text-properties (match-beginning 0) (match-end 0)
5846 (list 'mouse-face 'highlight
5847 'face 'org-link
5848 'htmlize-link `(:uri ,hl)
5849 'keymap org-mouse-map))
5850 (org-rear-nonsticky-at (match-end 0)))
5851 t)))
5853 (defun org-activate-code (limit)
5854 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5855 (progn
5856 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5857 (remove-text-properties (match-beginning 0) (match-end 0)
5858 '(display t invisible t intangible t))
5859 t)))
5861 (defcustom org-src-fontify-natively t
5862 "When non-nil, fontify code in code blocks."
5863 :type 'boolean
5864 :version "24.4"
5865 :package-version '(Org . "8.3")
5866 :group 'org-appearance
5867 :group 'org-babel)
5869 (defcustom org-allow-promoting-top-level-subtree nil
5870 "When non-nil, allow promoting a top level subtree.
5871 The leading star of the top level headline will be replaced
5872 by a #."
5873 :type 'boolean
5874 :version "24.1"
5875 :group 'org-appearance)
5877 (defun org-fontify-meta-lines-and-blocks (limit)
5878 (condition-case nil
5879 (org-fontify-meta-lines-and-blocks-1 limit)
5880 (error (message "org-mode fontification error"))))
5882 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5883 "Fontify #+ lines and blocks."
5884 (let ((case-fold-search t))
5885 (if (re-search-forward
5886 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5887 limit t)
5888 (let ((beg (match-beginning 0))
5889 (block-start (match-end 0))
5890 (block-end nil)
5891 (lang (match-string 7))
5892 (beg1 (line-beginning-position 2))
5893 (dc1 (downcase (match-string 2)))
5894 (dc3 (downcase (match-string 3)))
5895 end end1 quoting block-type ovl)
5896 (cond
5897 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5898 ;; a single line of backend-specific content
5899 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5900 (remove-text-properties (match-beginning 0) (match-end 0)
5901 '(display t invisible t intangible t))
5902 (add-text-properties (match-beginning 1) (match-end 3)
5903 '(font-lock-fontified t face org-meta-line))
5904 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5905 '(font-lock-fontified t face org-block))
5906 ; for backend-specific code
5908 ((and (match-end 4) (equal dc3 "+begin"))
5909 ;; Truly a block
5910 (setq block-type (downcase (match-string 5))
5911 quoting (member block-type org-protecting-blocks))
5912 (when (re-search-forward
5913 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5914 nil t) ;; on purpose, we look further than LIMIT
5915 (setq end (min (point-max) (match-end 0))
5916 end1 (min (point-max) (1- (match-beginning 0))))
5917 (setq block-end (match-beginning 0))
5918 (when quoting
5919 (org-remove-flyspell-overlays-in beg1 end1)
5920 (remove-text-properties beg end
5921 '(display t invisible t intangible t)))
5922 (add-text-properties
5923 beg end '(font-lock-fontified t font-lock-multiline t))
5924 (add-text-properties beg beg1 '(face org-meta-line))
5925 (org-remove-flyspell-overlays-in beg beg1)
5926 (add-text-properties ; For end_src
5927 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5928 (org-remove-flyspell-overlays-in end1 end)
5929 (cond
5930 ((and lang (not (string= lang "")) org-src-fontify-natively)
5931 (org-src-font-lock-fontify-block lang block-start block-end)
5932 ;; remove old background overlays
5933 (mapc (lambda (ov)
5934 (if (eq (overlay-get ov 'face) 'org-block-background)
5935 (delete-overlay ov)))
5936 (overlays-at (/ (+ beg1 block-end) 2)))
5937 ;; add a background overlay
5938 (setq ovl (make-overlay beg1 block-end))
5939 (overlay-put ovl 'face 'org-block-background)
5940 (overlay-put ovl 'evaporate t)) ; make it go away when empty
5941 (quoting
5942 (add-text-properties beg1 (min (point-max) (1+ end1))
5943 '(face org-block))) ; end of source block
5944 ((not org-fontify-quote-and-verse-blocks))
5945 ((string= block-type "quote")
5946 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5947 ((string= block-type "verse")
5948 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5949 (add-text-properties beg beg1 '(face org-block-begin-line))
5950 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5951 '(face org-block-end-line))
5953 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5954 (org-remove-flyspell-overlays-in
5955 (match-beginning 0)
5956 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5957 (add-text-properties
5958 beg (match-end 3)
5959 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5960 '(font-lock-fontified t invisible t)
5961 '(font-lock-fontified t face org-document-info-keyword)))
5962 (add-text-properties
5963 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5964 (if (string-equal dc1 "+title:")
5965 '(font-lock-fontified t face org-document-title)
5966 '(font-lock-fontified t face org-document-info))))
5967 ((or (equal dc1 "+results")
5968 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5969 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5970 "+call:" "+header:" "+headers:" "+name:"))
5971 (and (match-end 4) (equal dc3 "+attr")))
5972 (org-remove-flyspell-overlays-in
5973 (match-beginning 0)
5974 (if (equal "+caption:" dc1) (match-end 2) (match-end 0)))
5975 (add-text-properties
5976 beg (match-end 0)
5977 '(font-lock-fontified t face org-meta-line))
5979 ((member dc3 '(" " ""))
5980 (org-remove-flyspell-overlays-in beg (match-end 0))
5981 (add-text-properties
5982 beg (match-end 0)
5983 '(font-lock-fontified t face font-lock-comment-face)))
5984 (t ;; just any other in-buffer setting, but not indented
5985 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5986 (add-text-properties
5987 beg (match-end 0)
5988 '(font-lock-fontified t face org-meta-line))
5989 t))))))
5991 (defun org-fontify-drawers (limit)
5992 "Fontify drawers."
5993 (when (re-search-forward org-drawer-regexp limit t)
5994 (add-text-properties
5995 (match-beginning 0) (match-end 0)
5996 '(font-lock-fontified t face org-special-keyword))
5997 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6000 (defun org-fontify-macros (limit)
6001 "Fontify macros."
6002 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
6003 (add-text-properties
6004 (match-beginning 0) (match-end 0)
6005 '(font-lock-fontified t face org-macro))
6006 (when org-hide-macro-markers
6007 (add-text-properties (match-end 2) (match-beginning 2)
6008 '(invisible t))
6009 (add-text-properties (match-beginning 1) (match-end 1)
6010 '(invisible t)))
6011 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6014 (defun org-activate-angle-links (limit)
6015 "Run through the buffer and add overlays to links."
6016 (if (and (re-search-forward org-angle-link-re limit t)
6017 (not (org-in-src-block-p)))
6018 (progn
6019 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6020 (add-text-properties (match-beginning 0) (match-end 0)
6021 (list 'mouse-face 'highlight
6022 'keymap org-mouse-map))
6023 (org-rear-nonsticky-at (match-end 0))
6024 t)))
6026 (defun org-activate-footnote-links (limit)
6027 "Run through the buffer and add overlays to footnotes."
6028 (let ((fn (org-footnote-next-reference-or-definition limit)))
6029 (when fn
6030 (let* ((beg (nth 1 fn))
6031 (end (nth 2 fn))
6032 (label (car fn))
6033 (referencep (/= (line-beginning-position) beg)))
6034 (when (and referencep (nth 3 fn))
6035 (save-excursion
6036 (goto-char beg)
6037 (search-forward (or label "fn:"))
6038 (org-remove-flyspell-overlays-in beg (match-end 0))))
6039 (add-text-properties beg end
6040 (list 'mouse-face 'highlight
6041 'keymap org-mouse-map
6042 'help-echo
6043 (if referencep "Footnote reference"
6044 "Footnote definition")
6045 'font-lock-fontified t
6046 'font-lock-multiline t
6047 'face 'org-footnote))))))
6049 (defun org-activate-bracket-links (limit)
6050 "Run through the buffer and add overlays to bracketed links."
6051 (if (and (re-search-forward org-bracket-link-regexp limit t)
6052 (not (org-in-src-block-p)))
6053 (let* ((hl (org-match-string-no-properties 1))
6054 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
6055 (ip (org-maybe-intangible
6056 (list 'invisible 'org-link
6057 'keymap org-mouse-map 'mouse-face 'highlight
6058 'font-lock-multiline t 'help-echo help
6059 'htmlize-link `(:uri ,hl))))
6060 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
6061 'font-lock-multiline t 'help-echo help
6062 'htmlize-link `(:uri ,hl))))
6063 ;; We need to remove the invisible property here. Table narrowing
6064 ;; may have made some of this invisible.
6065 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6066 (remove-text-properties (match-beginning 0) (match-end 0)
6067 '(invisible nil))
6068 (if (match-end 3)
6069 (progn
6070 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
6071 (org-rear-nonsticky-at (match-beginning 3))
6072 (add-text-properties (match-beginning 3) (match-end 3) vp)
6073 (org-rear-nonsticky-at (match-end 3))
6074 (add-text-properties (match-end 3) (match-end 0) ip)
6075 (org-rear-nonsticky-at (match-end 0)))
6076 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
6077 (org-rear-nonsticky-at (match-beginning 1))
6078 (add-text-properties (match-beginning 1) (match-end 1) vp)
6079 (org-rear-nonsticky-at (match-end 1))
6080 (add-text-properties (match-end 1) (match-end 0) ip)
6081 (org-rear-nonsticky-at (match-end 0)))
6082 t)))
6084 (defun org-activate-dates (limit)
6085 "Run through the buffer and add overlays to dates."
6086 (if (and (re-search-forward org-tsr-regexp-both limit t)
6087 (not (equal (char-before (match-beginning 0)) 91)))
6088 (progn
6089 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6090 (add-text-properties (match-beginning 0) (match-end 0)
6091 (list 'mouse-face 'highlight
6092 'keymap org-mouse-map))
6093 (org-rear-nonsticky-at (match-end 0))
6094 (when org-display-custom-times
6095 (if (match-end 3)
6096 (org-display-custom-time (match-beginning 3) (match-end 3)))
6097 (org-display-custom-time (match-beginning 1) (match-end 1)))
6098 t)))
6100 (defvar org-target-link-regexp nil
6101 "Regular expression matching radio targets in plain text.")
6102 (make-variable-buffer-local 'org-target-link-regexp)
6104 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6105 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6106 border border border))
6107 "Regular expression matching a link target.")
6109 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6110 "Regular expression matching a radio target.")
6112 (defconst org-any-target-regexp
6113 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6114 "Regular expression matching any target.")
6116 (defun org-activate-target-links (limit)
6117 "Run through the buffer and add overlays to target matches."
6118 (when org-target-link-regexp
6119 (let ((case-fold-search t))
6120 (if (re-search-forward org-target-link-regexp limit t)
6121 (progn
6122 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6123 (add-text-properties (match-beginning 1) (match-end 1)
6124 (list 'mouse-face 'highlight
6125 'keymap org-mouse-map
6126 'help-echo "Radio target link"
6127 'org-linked-text t))
6128 (org-rear-nonsticky-at (match-end 1))
6129 t)))))
6131 (defun org-update-radio-target-regexp ()
6132 "Find all radio targets in this file and update the regular expression.
6133 Also refresh fontification if needed."
6134 (interactive)
6135 (let ((old-regexp org-target-link-regexp)
6136 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6137 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6138 (targets
6139 (org-with-wide-buffer
6140 (goto-char (point-min))
6141 (let (rtn)
6142 (while (re-search-forward org-radio-target-regexp nil t)
6143 ;; Make sure point is really within the object.
6144 (backward-char)
6145 (let ((obj (org-element-context)))
6146 (when (eq (org-element-type obj) 'radio-target)
6147 (add-to-list 'rtn (org-element-property :value obj)))))
6148 rtn))))
6149 (setq org-target-link-regexp
6150 (and targets
6151 (concat before-re
6152 (mapconcat
6153 (lambda (x)
6154 (replace-regexp-in-string
6155 " +" "\\s-+" (regexp-quote x) t t))
6156 targets
6157 "\\|")
6158 after-re)))
6159 (unless (equal old-regexp org-target-link-regexp)
6160 ;; Clean-up cache.
6161 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6162 ((not org-target-link-regexp) old-regexp)
6164 (concat before-re
6165 (mapconcat
6166 (lambda (re)
6167 (substring re (length before-re)
6168 (- (length after-re))))
6169 (list old-regexp org-target-link-regexp)
6170 "\\|")
6171 after-re)))))
6172 (org-with-wide-buffer
6173 (goto-char (point-min))
6174 (while (re-search-forward regexp nil t)
6175 (org-element-cache-refresh (match-beginning 1)))))
6176 ;; Re fontify buffer.
6177 (when (memq 'radio org-highlight-links)
6178 (org-restart-font-lock)))))
6180 (defun org-hide-wide-columns (limit)
6181 (let (s e)
6182 (setq s (text-property-any (point) (or limit (point-max))
6183 'org-cwidth t))
6184 (when s
6185 (setq e (next-single-property-change s 'org-cwidth))
6186 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6187 (goto-char e)
6188 t)))
6190 (defvar org-latex-and-related-regexp nil
6191 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6193 (defun org-compute-latex-and-related-regexp ()
6194 "Compute regular expression for LaTeX, entities and sub/superscript.
6195 Result depends on variable `org-highlight-latex-and-related'."
6196 (org-set-local
6197 'org-latex-and-related-regexp
6198 (let* ((re-sub
6199 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6200 ((eq org-use-sub-superscripts '{})
6201 (list org-match-substring-with-braces-regexp))
6202 (org-use-sub-superscripts (list org-match-substring-regexp))))
6203 (re-latex
6204 (when (memq 'latex org-highlight-latex-and-related)
6205 (let ((matchers (plist-get org-format-latex-options :matchers)))
6206 (delq nil
6207 (mapcar (lambda (x)
6208 (and (member (car x) matchers) (nth 1 x)))
6209 org-latex-regexps)))))
6210 (re-entities
6211 (when (memq 'entities org-highlight-latex-and-related)
6212 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6213 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6215 (defun org-do-latex-and-related (limit)
6216 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6217 LIMIT bounds the search for syntax to highlight. Stop at first
6218 highlighted object, if any. Return t if some highlighting was
6219 done, nil otherwise."
6220 (when (org-string-nw-p org-latex-and-related-regexp)
6221 (catch 'found
6222 (while (re-search-forward org-latex-and-related-regexp limit t)
6223 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6224 'face))
6225 '(org-code org-verbatim underline))
6226 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6227 '(?_ ?^))
6229 0)))
6230 (font-lock-prepend-text-property
6231 (+ offset (match-beginning 0)) (match-end 0)
6232 'face 'org-latex-and-related)
6233 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6234 '(font-lock-multiline t)))
6235 (throw 'found t)))
6236 nil)))
6238 (defun org-restart-font-lock ()
6239 "Restart `font-lock-mode', to force refontification."
6240 (when (and (boundp 'font-lock-mode) font-lock-mode)
6241 (font-lock-mode -1)
6242 (font-lock-mode 1)))
6244 (defun org-activate-tags (limit)
6245 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6246 (progn
6247 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6248 (add-text-properties (match-beginning 1) (match-end 1)
6249 (list 'mouse-face 'highlight
6250 'keymap org-mouse-map))
6251 (org-rear-nonsticky-at (match-end 1))
6252 t)))
6254 (defun org-outline-level ()
6255 "Compute the outline level of the heading at point.
6256 If this is called at a normal headline, the level is the number of stars.
6257 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6258 (save-excursion
6259 (if (not (ignore-errors (org-back-to-heading t)))
6261 (looking-at org-outline-regexp)
6262 (1- (- (match-end 0) (match-beginning 0))))))
6264 (defvar org-font-lock-keywords nil)
6266 (defsubst org-re-property (property &optional literal allow-null)
6267 "Return a regexp matching a PROPERTY line.
6268 Match group 3 will be set to the value if it exists."
6269 (concat "^\\(?4:[ \t]*\\)\\(?1::\\(?2:"
6270 (if literal property (regexp-quote property))
6271 "\\):\\)[ \t]+\\(?3:[^ \t\r\n]"
6272 (if allow-null "*")
6273 ".*?\\)\\(?5:[ \t]*\\)$"))
6275 (defconst org-property-re
6276 (org-re-property ".*?" 'literal)
6277 "Regular expression matching a property line.
6278 There are four matching groups:
6279 1: :PROPKEY: including the leading and trailing colon,
6280 2: PROPKEY without the leading and trailing colon,
6281 3: PROPVAL without leading or trailing spaces,
6282 4: the indentation of the current line,
6283 5: trailing whitespace.")
6285 (defvar org-font-lock-hook nil
6286 "Functions to be called for special font lock stuff.")
6288 (defvar org-font-lock-set-keywords-hook nil
6289 "Functions that can manipulate `org-font-lock-extra-keywords'.
6290 This is called after `org-font-lock-extra-keywords' is defined, but before
6291 it is installed to be used by font lock. This can be useful if something
6292 needs to be inserted at a specific position in the font-lock sequence.")
6294 (defun org-font-lock-hook (limit)
6295 "Run `org-font-lock-hook' within LIMIT."
6296 (run-hook-with-args 'org-font-lock-hook limit))
6298 (defun org-set-font-lock-defaults ()
6299 "Set font lock defaults for the current buffer."
6300 (let* ((em org-fontify-emphasized-text)
6301 (lk org-highlight-links)
6302 (org-font-lock-extra-keywords
6303 (list
6304 ;; Call the hook
6305 '(org-font-lock-hook)
6306 ;; Headlines
6307 `(,(if org-fontify-whole-heading-line
6308 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6309 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6310 (1 (org-get-level-face 1))
6311 (2 (org-get-level-face 2))
6312 (3 (org-get-level-face 3)))
6313 ;; Table lines
6314 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6315 (1 'org-table t))
6316 ;; Table internals
6317 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6318 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6319 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6320 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6321 ;; Drawers
6322 '(org-fontify-drawers)
6323 ;; Properties
6324 (list org-property-re
6325 '(1 'org-special-keyword t)
6326 '(3 'org-property-value t))
6327 ;; Links
6328 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6329 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6330 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6331 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6332 (if (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6333 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6334 (if (memq 'footnote lk) '(org-activate-footnote-links))
6335 ;; Targets.
6336 (list org-any-target-regexp '(0 'org-target t))
6337 ;; Diary sexps.
6338 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6339 ;; Macro
6340 '(org-fontify-macros)
6341 '(org-hide-wide-columns (0 nil append))
6342 ;; TODO keyword
6343 (list (format org-heading-keyword-regexp-format
6344 org-todo-regexp)
6345 '(2 (org-get-todo-face 2) t))
6346 ;; DONE
6347 (if org-fontify-done-headline
6348 (list (format org-heading-keyword-regexp-format
6349 (concat
6350 "\\(?:"
6351 (mapconcat 'regexp-quote org-done-keywords "\\|")
6352 "\\)"))
6353 '(2 'org-headline-done t))
6354 nil)
6355 ;; Priorities
6356 '(org-font-lock-add-priority-faces)
6357 ;; Tags
6358 '(org-font-lock-add-tag-faces)
6359 ;; Tags groups
6360 (if (and org-group-tags org-tag-groups-alist)
6361 (list (concat org-outline-regexp-bol ".+\\(:"
6362 (regexp-opt (mapcar 'car org-tag-groups-alist))
6363 ":\\).*$")
6364 '(1 'org-tag-group prepend)))
6365 ;; Special keywords
6366 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6367 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6368 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6369 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6370 ;; Emphasis
6371 (if em
6372 (if (featurep 'xemacs)
6373 '(org-do-emphasis-faces (0 nil append))
6374 '(org-do-emphasis-faces)))
6375 ;; Checkboxes
6376 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6377 1 'org-checkbox prepend)
6378 (if (cdr (assq 'checkbox org-list-automatic-rules))
6379 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6380 (0 (org-get-checkbox-statistics-face) t)))
6381 ;; Description list items
6382 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6383 1 'org-list-dt prepend)
6384 ;; ARCHIVEd headings
6385 (list (concat
6386 org-outline-regexp-bol
6387 "\\(.*:" org-archive-tag ":.*\\)")
6388 '(1 'org-archived prepend))
6389 ;; Specials
6390 '(org-do-latex-and-related)
6391 '(org-fontify-entities)
6392 '(org-raise-scripts)
6393 ;; Code
6394 '(org-activate-code (1 'org-code t))
6395 ;; COMMENT
6396 (list (format
6397 "^\\*\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6398 org-todo-regexp
6399 org-comment-string)
6400 '(9 'org-special-keyword t))
6401 ;; Blocks and meta lines
6402 '(org-fontify-meta-lines-and-blocks))))
6403 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6404 (run-hooks 'org-font-lock-set-keywords-hook)
6405 ;; Now set the full font-lock-keywords
6406 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6407 (org-set-local 'font-lock-defaults
6408 '(org-font-lock-keywords t nil nil backward-paragraph))
6409 (kill-local-variable 'font-lock-keywords) nil))
6411 (defun org-toggle-pretty-entities ()
6412 "Toggle the composition display of entities as UTF8 characters."
6413 (interactive)
6414 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6415 (org-restart-font-lock)
6416 (if org-pretty-entities
6417 (message "Entities are now displayed as UTF8 characters")
6418 (save-restriction
6419 (widen)
6420 (org-decompose-region (point-min) (point-max))
6421 (message "Entities are now displayed as plain text"))))
6423 (defvar org-custom-properties-overlays nil
6424 "List of overlays used for custom properties.")
6425 (make-variable-buffer-local 'org-custom-properties-overlays)
6427 (defun org-toggle-custom-properties-visibility ()
6428 "Display or hide properties in `org-custom-properties'."
6429 (interactive)
6430 (if org-custom-properties-overlays
6431 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6432 (setq org-custom-properties-overlays nil))
6433 (unless (not org-custom-properties)
6434 (save-excursion
6435 (save-restriction
6436 (widen)
6437 (goto-char (point-min))
6438 (while (re-search-forward org-property-re nil t)
6439 (mapc (lambda(p)
6440 (when (equal p (substring (match-string 1) 1 -1))
6441 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6442 (overlay-put o 'invisible t)
6443 (overlay-put o 'org-custom-property t)
6444 (push o org-custom-properties-overlays))))
6445 org-custom-properties)))))))
6447 (defun org-fontify-entities (limit)
6448 "Find an entity to fontify."
6449 (let (ee)
6450 (when org-pretty-entities
6451 (catch 'match
6452 (while (re-search-forward
6453 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6454 limit t)
6455 (if (and (not (org-at-comment-p))
6456 (setq ee (org-entity-get (match-string 1)))
6457 (= (length (nth 6 ee)) 1))
6458 (let*
6459 ((end (if (equal (match-string 2) "{}")
6460 (match-end 2)
6461 (match-end 1))))
6462 (add-text-properties
6463 (match-beginning 0) end
6464 (list 'font-lock-fontified t))
6465 (compose-region (match-beginning 0) end
6466 (nth 6 ee) nil)
6467 (backward-char 1)
6468 (throw 'match t))))
6469 nil))))
6471 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6472 "Fontify string S like in Org-mode."
6473 (with-temp-buffer
6474 (insert s)
6475 (let ((org-odd-levels-only odd-levels))
6476 (org-mode)
6477 (font-lock-ensure)
6478 (buffer-string))))
6480 (defvar org-m nil)
6481 (defvar org-l nil)
6482 (defvar org-f nil)
6483 (defun org-get-level-face (n)
6484 "Get the right face for match N in font-lock matching of headlines."
6485 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6486 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6487 (if org-cycle-level-faces
6488 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6489 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6490 (cond
6491 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6492 ((eq n 2) org-f)
6493 (t (if org-level-color-stars-only nil org-f))))
6496 (defun org-get-todo-face (kwd)
6497 "Get the right face for a TODO keyword KWD.
6498 If KWD is a number, get the corresponding match group."
6499 (if (numberp kwd) (setq kwd (match-string kwd)))
6500 (or (org-face-from-face-or-color
6501 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6502 (and (member kwd org-done-keywords) 'org-done)
6503 'org-todo))
6505 (defun org-face-from-face-or-color (context inherit face-or-color)
6506 "Create a face list that inherits INHERIT, but sets the foreground color.
6507 When FACE-OR-COLOR is not a string, just return it."
6508 (if (stringp face-or-color)
6509 (list :inherit inherit
6510 (cdr (assoc context org-faces-easy-properties))
6511 face-or-color)
6512 face-or-color))
6514 (defun org-font-lock-add-tag-faces (limit)
6515 "Add the special tag faces."
6516 (when (and org-tag-faces org-tags-special-faces-re)
6517 (while (re-search-forward org-tags-special-faces-re limit t)
6518 (add-text-properties (match-beginning 1) (match-end 1)
6519 (list 'face (org-get-tag-face 1)
6520 'font-lock-fontified t))
6521 (backward-char 1))))
6523 (defun org-font-lock-add-priority-faces (limit)
6524 "Add the special priority faces."
6525 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6526 (when (save-match-data (org-at-heading-p))
6527 (add-text-properties
6528 (match-beginning 0) (match-end 0)
6529 (list 'face (or (org-face-from-face-or-color
6530 'priority 'org-priority
6531 (cdr (assoc (char-after (match-beginning 1))
6532 org-priority-faces)))
6533 'org-priority)
6534 'font-lock-fontified t)))))
6536 (defun org-get-tag-face (kwd)
6537 "Get the right face for a TODO keyword KWD.
6538 If KWD is a number, get the corresponding match group."
6539 (if (numberp kwd) (setq kwd (match-string kwd)))
6540 (or (org-face-from-face-or-color
6541 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6542 'org-tag))
6544 (defun org-unfontify-region (beg end &optional maybe_loudly)
6545 "Remove fontification and activation overlays from links."
6546 (font-lock-default-unfontify-region beg end)
6547 (let* ((buffer-undo-list t)
6548 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6549 (inhibit-modification-hooks t)
6550 deactivate-mark buffer-file-name buffer-file-truename)
6551 (org-decompose-region beg end)
6552 (remove-text-properties beg end
6553 '(mouse-face t keymap t org-linked-text t
6554 invisible t intangible t
6555 org-emphasis t))
6556 (org-remove-font-lock-display-properties beg end)))
6558 (defconst org-script-display '(((raise -0.3) (height 0.7))
6559 ((raise 0.3) (height 0.7))
6560 ((raise -0.5))
6561 ((raise 0.5)))
6562 "Display properties for showing superscripts and subscripts.")
6564 (defun org-remove-font-lock-display-properties (beg end)
6565 "Remove specific display properties that have been added by font lock.
6566 The will remove the raise properties that are used to show superscripts
6567 and subscripts."
6568 (let (next prop)
6569 (while (< beg end)
6570 (setq next (next-single-property-change beg 'display nil end)
6571 prop (get-text-property beg 'display))
6572 (if (member prop org-script-display)
6573 (put-text-property beg next 'display nil))
6574 (setq beg next))))
6576 (defun org-raise-scripts (limit)
6577 "Add raise properties to sub/superscripts."
6578 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6579 (if (re-search-forward
6580 (if (eq org-use-sub-superscripts t)
6581 org-match-substring-regexp
6582 org-match-substring-with-braces-regexp)
6583 limit t)
6584 (let* ((pos (point)) table-p comment-p
6585 (mpos (match-beginning 3))
6586 (emph-p (get-text-property mpos 'org-emphasis))
6587 (link-p (get-text-property mpos 'mouse-face))
6588 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6589 (goto-char (point-at-bol))
6590 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6591 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6592 (goto-char pos)
6593 ;; Handle a_b^c
6594 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6595 (if (or comment-p emph-p link-p keyw-p)
6597 (put-text-property (match-beginning 3) (match-end 0)
6598 'display
6599 (if (equal (char-after (match-beginning 2)) ?^)
6600 (nth (if table-p 3 1) org-script-display)
6601 (nth (if table-p 2 0) org-script-display)))
6602 (add-text-properties (match-beginning 2) (match-end 2)
6603 (list 'invisible t
6604 'org-dwidth t 'org-dwidth-n 1))
6605 (if (and (eq (char-after (match-beginning 3)) ?{)
6606 (eq (char-before (match-end 3)) ?}))
6607 (progn
6608 (add-text-properties
6609 (match-beginning 3) (1+ (match-beginning 3))
6610 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6611 (add-text-properties
6612 (1- (match-end 3)) (match-end 3)
6613 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6614 t)))))
6616 ;;;; Visibility cycling, including org-goto and indirect buffer
6618 ;;; Cycling
6620 (defvar org-cycle-global-status nil)
6621 (make-variable-buffer-local 'org-cycle-global-status)
6622 (put 'org-cycle-global-status 'org-state t)
6623 (defvar org-cycle-subtree-status nil)
6624 (make-variable-buffer-local 'org-cycle-subtree-status)
6625 (put 'org-cycle-subtree-status 'org-state t)
6627 (defvar org-inlinetask-min-level)
6629 (defun org-unlogged-message (&rest args)
6630 "Display a message, but avoid logging it in the *Messages* buffer."
6631 (let ((message-log-max nil))
6632 (apply 'message args)))
6634 ;;;###autoload
6635 (defun org-cycle (&optional arg)
6636 "TAB-action and visibility cycling for Org-mode.
6638 This is the command invoked in Org-mode by the TAB key. Its main purpose
6639 is outline visibility cycling, but it also invokes other actions
6640 in special contexts.
6642 - When this function is called with a prefix argument, rotate the entire
6643 buffer through 3 states (global cycling)
6644 1. OVERVIEW: Show only top-level headlines.
6645 2. CONTENTS: Show all headlines of all levels, but no body text.
6646 3. SHOW ALL: Show everything.
6647 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6648 determined by the variable `org-startup-folded', and by any VISIBILITY
6649 properties in the buffer.
6650 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6651 including any drawers.
6653 - When inside a table, re-align the table and move to the next field.
6655 - When point is at the beginning of a headline, rotate the subtree started
6656 by this line through 3 different states (local cycling)
6657 1. FOLDED: Only the main headline is shown.
6658 2. CHILDREN: The main headline and the direct children are shown.
6659 From this state, you can move to one of the children
6660 and zoom in further.
6661 3. SUBTREE: Show the entire subtree, including body text.
6662 If there is no subtree, switch directly from CHILDREN to FOLDED.
6664 - When point is at the beginning of an empty headline and the variable
6665 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6666 of the headline by demoting and promoting it to likely levels. This
6667 speeds up creation document structure by pressing TAB once or several
6668 times right after creating a new headline.
6670 - When there is a numeric prefix, go up to a heading with level ARG, do
6671 a `show-subtree' and return to the previous cursor position. If ARG
6672 is negative, go up that many levels.
6674 - When point is not at the beginning of a headline, execute the global
6675 binding for TAB, which is re-indenting the line. See the option
6676 `org-cycle-emulate-tab' for details.
6678 - Special case: if point is at the beginning of the buffer and there is
6679 no headline in line 1, this function will act as if called with prefix arg
6680 (C-u TAB, same as S-TAB) also when called without prefix arg.
6681 But only if also the variable `org-cycle-global-at-bob' is t."
6682 (interactive "P")
6683 (org-load-modules-maybe)
6684 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6685 (and org-cycle-level-after-item/entry-creation
6686 (or (org-cycle-level)
6687 (org-cycle-item-indentation))))
6688 (let* ((limit-level
6689 (or org-cycle-max-level
6690 (and (boundp 'org-inlinetask-min-level)
6691 org-inlinetask-min-level
6692 (1- org-inlinetask-min-level))))
6693 (nstars (and limit-level
6694 (if org-odd-levels-only
6695 (and limit-level (1- (* limit-level 2)))
6696 limit-level)))
6697 (org-outline-regexp
6698 (if (not (derived-mode-p 'org-mode))
6699 outline-regexp
6700 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6701 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6702 (not (looking-at org-outline-regexp))))
6703 (org-cycle-hook
6704 (if bob-special
6705 (delq 'org-optimize-window-after-visibility-change
6706 (copy-sequence org-cycle-hook))
6707 org-cycle-hook))
6708 (pos (point)))
6710 (if (or bob-special (equal arg '(4)))
6711 ;; special case: use global cycling
6712 (setq arg t))
6714 (cond
6716 ((equal arg '(16))
6717 (setq last-command 'dummy)
6718 (org-set-startup-visibility)
6719 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6721 ((equal arg '(64))
6722 (show-all)
6723 (org-unlogged-message "Entire buffer visible, including drawers"))
6725 ;; Try cdlatex TAB completion
6726 ((org-try-cdlatex-tab))
6728 ;; Table: enter it or move to the next field.
6729 ((org-at-table-p 'any)
6730 (if (org-at-table.el-p)
6731 (message "Use C-c ' to edit table.el tables")
6732 (if arg (org-table-edit-field t)
6733 (org-table-justify-field-maybe)
6734 (call-interactively 'org-table-next-field))))
6736 ((run-hook-with-args-until-success
6737 'org-tab-after-check-for-table-hook))
6739 ;; Global cycling: delegate to `org-cycle-internal-global'.
6740 ((eq arg t) (org-cycle-internal-global))
6742 ;; Drawers: delegate to `org-flag-drawer'.
6743 ((save-excursion
6744 (beginning-of-line 1)
6745 (looking-at org-drawer-regexp))
6746 (org-flag-drawer ; toggle block visibility
6747 (not (get-char-property (match-end 0) 'invisible))))
6749 ;; Show-subtree, ARG levels up from here.
6750 ((integerp arg)
6751 (save-excursion
6752 (org-back-to-heading)
6753 (outline-up-heading (if (< arg 0) (- arg)
6754 (- (funcall outline-level) arg)))
6755 (org-show-subtree)))
6757 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6758 ((and (featurep 'org-inlinetask)
6759 (org-inlinetask-at-task-p)
6760 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6761 (org-inlinetask-toggle-visibility))
6763 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6764 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6765 (save-excursion (beginning-of-line 1)
6766 (looking-at org-outline-regexp)))
6767 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6768 (org-cycle-internal-local))
6770 ;; From there: TAB emulation and template completion.
6771 (buffer-read-only (org-back-to-heading))
6773 ((run-hook-with-args-until-success
6774 'org-tab-after-check-for-cycling-hook))
6776 ((org-try-structure-completion))
6778 ((run-hook-with-args-until-success
6779 'org-tab-before-tab-emulation-hook))
6781 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6782 (or (not (bolp))
6783 (not (looking-at org-outline-regexp))))
6784 (call-interactively (global-key-binding "\t")))
6786 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6787 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6788 (or (and (eq org-cycle-emulate-tab 'white)
6789 (= (match-end 0) (point-at-eol)))
6790 (and (eq org-cycle-emulate-tab 'whitestart)
6791 (>= (match-end 0) pos))))
6793 (eq org-cycle-emulate-tab t))
6794 (call-interactively (global-key-binding "\t")))
6796 (t (save-excursion
6797 (org-back-to-heading)
6798 (org-cycle)))))))
6800 (defun org-cycle-internal-global ()
6801 "Do the global cycling action."
6802 ;; Hack to avoid display of messages for .org attachments in Gnus
6803 (let ((ga (string-match "\\*fontification" (buffer-name))))
6804 (cond
6805 ((and (eq last-command this-command)
6806 (eq org-cycle-global-status 'overview))
6807 ;; We just created the overview - now do table of contents
6808 ;; This can be slow in very large buffers, so indicate action
6809 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6810 (unless ga (org-unlogged-message "CONTENTS..."))
6811 (org-content)
6812 (unless ga (org-unlogged-message "CONTENTS...done"))
6813 (setq org-cycle-global-status 'contents)
6814 (run-hook-with-args 'org-cycle-hook 'contents))
6816 ((and (eq last-command this-command)
6817 (eq org-cycle-global-status 'contents))
6818 ;; We just showed the table of contents - now show everything
6819 (run-hook-with-args 'org-pre-cycle-hook 'all)
6820 (show-all)
6821 (unless ga (org-unlogged-message "SHOW ALL"))
6822 (setq org-cycle-global-status 'all)
6823 (run-hook-with-args 'org-cycle-hook 'all))
6826 ;; Default action: go to overview
6827 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6828 (org-overview)
6829 (unless ga (org-unlogged-message "OVERVIEW"))
6830 (setq org-cycle-global-status 'overview)
6831 (run-hook-with-args 'org-cycle-hook 'overview)))))
6833 (defvar org-called-with-limited-levels);Dyn-bound in ̀org-with-limited-levels'.
6835 (defun org-cycle-internal-local ()
6836 "Do the local cycling action."
6837 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6838 ;; First, determine end of headline (EOH), end of subtree or item
6839 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6840 (save-excursion
6841 (if (org-at-item-p)
6842 (progn
6843 (beginning-of-line)
6844 (setq struct (org-list-struct))
6845 (setq eoh (point-at-eol))
6846 (setq eos (org-list-get-item-end-before-blank (point) struct))
6847 (setq has-children (org-list-has-child-p (point) struct)))
6848 (org-back-to-heading)
6849 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6850 (setq eos (save-excursion (org-end-of-subtree t t)
6851 (when (bolp) (backward-char)) (point)))
6852 (setq has-children
6853 (or (save-excursion
6854 (let ((level (funcall outline-level)))
6855 (outline-next-heading)
6856 (and (org-at-heading-p t)
6857 (> (funcall outline-level) level))))
6858 (save-excursion
6859 (org-list-search-forward (org-item-beginning-re) eos t)))))
6860 ;; Determine end invisible part of buffer (EOL)
6861 (beginning-of-line 2)
6862 ;; XEmacs doesn't have `next-single-char-property-change'
6863 (if (featurep 'xemacs)
6864 (while (and (not (eobp)) ;; this is like `next-line'
6865 (get-char-property (1- (point)) 'invisible))
6866 (beginning-of-line 2))
6867 (while (and (not (eobp)) ;; this is like `next-line'
6868 (get-char-property (1- (point)) 'invisible))
6869 (goto-char (next-single-char-property-change (point) 'invisible))
6870 (and (eolp) (beginning-of-line 2))))
6871 (setq eol (point)))
6872 ;; Find out what to do next and set `this-command'
6873 (cond
6874 ((= eos eoh)
6875 ;; Nothing is hidden behind this heading
6876 (unless (org-before-first-heading-p)
6877 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6878 (org-unlogged-message "EMPTY ENTRY")
6879 (setq org-cycle-subtree-status nil)
6880 (save-excursion
6881 (goto-char eos)
6882 (outline-next-heading)
6883 (if (outline-invisible-p) (org-flag-heading nil))))
6884 ((and (or (>= eol eos)
6885 (not (string-match "\\S-" (buffer-substring eol eos))))
6886 (or has-children
6887 (not (setq children-skipped
6888 org-cycle-skip-children-state-if-no-children))))
6889 ;; Entire subtree is hidden in one line: children view
6890 (unless (org-before-first-heading-p)
6891 (run-hook-with-args 'org-pre-cycle-hook 'children))
6892 (if (org-at-item-p)
6893 (org-list-set-item-visibility (point-at-bol) struct 'children)
6894 (org-show-entry)
6895 (org-with-limited-levels (show-children))
6896 ;; FIXME: This slows down the func way too much.
6897 ;; How keep drawers hidden in subtree anyway?
6898 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6899 ;; (org-cycle-hide-drawers 'subtree))
6901 ;; Fold every list in subtree to top-level items.
6902 (when (eq org-cycle-include-plain-lists 'integrate)
6903 (save-excursion
6904 (org-back-to-heading)
6905 (while (org-list-search-forward (org-item-beginning-re) eos t)
6906 (beginning-of-line 1)
6907 (let* ((struct (org-list-struct))
6908 (prevs (org-list-prevs-alist struct))
6909 (end (org-list-get-bottom-point struct)))
6910 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6911 (org-list-get-all-items (point) struct prevs))
6912 (goto-char (if (< end eos) end eos)))))))
6913 (org-unlogged-message "CHILDREN")
6914 (save-excursion
6915 (goto-char eos)
6916 (outline-next-heading)
6917 (if (outline-invisible-p) (org-flag-heading nil)))
6918 (setq org-cycle-subtree-status 'children)
6919 (unless (org-before-first-heading-p)
6920 (run-hook-with-args 'org-cycle-hook 'children)))
6921 ((or children-skipped
6922 (and (eq last-command this-command)
6923 (eq org-cycle-subtree-status 'children)))
6924 ;; We just showed the children, or no children are there,
6925 ;; now show everything.
6926 (unless (org-before-first-heading-p)
6927 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6928 (outline-flag-region eoh eos nil)
6929 (org-unlogged-message
6930 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6931 (setq org-cycle-subtree-status 'subtree)
6932 (unless (org-before-first-heading-p)
6933 (run-hook-with-args 'org-cycle-hook 'subtree)))
6935 ;; Default action: hide the subtree.
6936 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6937 (outline-flag-region eoh eos t)
6938 (org-unlogged-message "FOLDED")
6939 (setq org-cycle-subtree-status 'folded)
6940 (unless (org-before-first-heading-p)
6941 (run-hook-with-args 'org-cycle-hook 'folded))))))
6943 ;;;###autoload
6944 (defun org-global-cycle (&optional arg)
6945 "Cycle the global visibility. For details see `org-cycle'.
6946 With \\[universal-argument] prefix arg, switch to startup visibility.
6947 With a numeric prefix, show all headlines up to that level."
6948 (interactive "P")
6949 (let ((org-cycle-include-plain-lists
6950 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6951 (cond
6952 ((integerp arg)
6953 (show-all)
6954 (hide-sublevels arg)
6955 (setq org-cycle-global-status 'contents))
6956 ((equal arg '(4))
6957 (org-set-startup-visibility)
6958 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6960 (org-cycle '(4))))))
6962 (defun org-set-startup-visibility ()
6963 "Set the visibility required by startup options and properties."
6964 (cond
6965 ((eq org-startup-folded t)
6966 (org-overview))
6967 ((eq org-startup-folded 'content)
6968 (org-content))
6969 ((or (eq org-startup-folded 'showeverything)
6970 (eq org-startup-folded nil))
6971 (show-all)))
6972 (unless (eq org-startup-folded 'showeverything)
6973 (if org-hide-block-startup (org-hide-block-all))
6974 (org-set-visibility-according-to-property 'no-cleanup)
6975 (org-cycle-hide-archived-subtrees 'all)
6976 (org-cycle-hide-drawers 'all)
6977 (org-cycle-show-empty-lines t)))
6979 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6980 "Switch subtree visibilities according to :VISIBILITY: property."
6981 (interactive)
6982 (let (org-show-entry-below state)
6983 (save-excursion
6984 (goto-char (point-min))
6985 (while (re-search-forward
6986 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6987 nil t)
6988 (setq state (match-string 1))
6989 (save-excursion
6990 (org-back-to-heading t)
6991 (hide-subtree)
6992 (org-reveal)
6993 (cond
6994 ((equal state '("fold" "folded"))
6995 (hide-subtree))
6996 ((equal state "children")
6997 (org-show-hidden-entry)
6998 (show-children))
6999 ((equal state "content")
7000 (save-excursion
7001 (save-restriction
7002 (org-narrow-to-subtree)
7003 (org-content))))
7004 ((member state '("all" "showall"))
7005 (show-subtree)))))
7006 (unless no-cleanup
7007 (org-cycle-hide-archived-subtrees 'all)
7008 (org-cycle-hide-drawers 'all)
7009 (org-cycle-show-empty-lines 'all)))))
7011 ;; This function uses outline-regexp instead of the more fundamental
7012 ;; org-outline-regexp so that org-cycle-global works outside of Org
7013 ;; buffers, where outline-regexp is needed.
7014 (defun org-overview ()
7015 "Switch to overview mode, showing only top-level headlines.
7016 This shows all headlines with a level equal or greater than the level
7017 of the first headline in the buffer. This is important, because if the
7018 first headline is not level one, then (hide-sublevels 1) gives confusing
7019 results."
7020 (interactive)
7021 (save-excursion
7022 (let ((level
7023 (save-excursion
7024 (goto-char (point-min))
7025 (if (re-search-forward (concat "^" outline-regexp) nil t)
7026 (progn
7027 (goto-char (match-beginning 0))
7028 (funcall outline-level))))))
7029 (and level (hide-sublevels level)))))
7031 (defun org-content (&optional arg)
7032 "Show all headlines in the buffer, like a table of contents.
7033 With numerical argument N, show content up to level N."
7034 (interactive "P")
7035 (org-overview)
7036 (save-excursion
7037 ;; Visit all headings and show their offspring
7038 (and (integerp arg) (org-overview))
7039 (goto-char (point-max))
7040 (catch 'exit
7041 (while (and (progn (condition-case nil
7042 (outline-previous-visible-heading 1)
7043 (error (goto-char (point-min))))
7045 (looking-at org-outline-regexp))
7046 (if (integerp arg)
7047 (show-children (1- arg))
7048 (show-branches))
7049 (if (bobp) (throw 'exit nil))))))
7051 (defun org-optimize-window-after-visibility-change (state)
7052 "Adjust the window after a change in outline visibility.
7053 This function is the default value of the hook `org-cycle-hook'."
7054 (when (get-buffer-window (current-buffer))
7055 (cond
7056 ((eq state 'content) nil)
7057 ((eq state 'all) nil)
7058 ((eq state 'folded) nil)
7059 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7060 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7062 (defun org-remove-empty-overlays-at (pos)
7063 "Remove outline overlays that do not contain non-white stuff."
7064 (mapc
7065 (lambda (o)
7066 (and (eq 'outline (overlay-get o 'invisible))
7067 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7068 (overlay-end o))))
7069 (delete-overlay o)))
7070 (overlays-at pos)))
7072 (defun org-clean-visibility-after-subtree-move ()
7073 "Fix visibility issues after moving a subtree."
7074 ;; First, find a reasonable region to look at:
7075 ;; Start two siblings above, end three below
7076 (let* ((beg (save-excursion
7077 (and (org-get-last-sibling)
7078 (org-get-last-sibling))
7079 (point)))
7080 (end (save-excursion
7081 (and (org-get-next-sibling)
7082 (org-get-next-sibling)
7083 (org-get-next-sibling))
7084 (if (org-at-heading-p)
7085 (point-at-eol)
7086 (point))))
7087 (level (looking-at "\\*+"))
7088 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
7089 (save-excursion
7090 (save-restriction
7091 (narrow-to-region beg end)
7092 (when re
7093 ;; Properly fold already folded siblings
7094 (goto-char (point-min))
7095 (while (re-search-forward re nil t)
7096 (if (and (not (outline-invisible-p))
7097 (save-excursion
7098 (goto-char (point-at-eol)) (outline-invisible-p)))
7099 (hide-entry))))
7100 (org-cycle-show-empty-lines 'overview)
7101 (org-cycle-hide-drawers 'overview)))))
7103 (defun org-cycle-show-empty-lines (state)
7104 "Show empty lines above all visible headlines.
7105 The region to be covered depends on STATE when called through
7106 `org-cycle-hook'. Lisp program can use t for STATE to get the
7107 entire buffer covered. Note that an empty line is only shown if there
7108 are at least `org-cycle-separator-lines' empty lines before the headline."
7109 (when (not (= org-cycle-separator-lines 0))
7110 (save-excursion
7111 (let* ((n (abs org-cycle-separator-lines))
7112 (re (cond
7113 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7114 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7115 (t (let ((ns (number-to-string (- n 2))))
7116 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7117 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7118 beg end b e)
7119 (cond
7120 ((memq state '(overview contents t))
7121 (setq beg (point-min) end (point-max)))
7122 ((memq state '(children folded))
7123 (setq beg (point) end (progn (org-end-of-subtree t t)
7124 (beginning-of-line 2)
7125 (point)))))
7126 (when beg
7127 (goto-char beg)
7128 (while (re-search-forward re end t)
7129 (unless (get-char-property (match-end 1) 'invisible)
7130 (setq e (match-end 1))
7131 (if (< org-cycle-separator-lines 0)
7132 (setq b (save-excursion
7133 (goto-char (match-beginning 0))
7134 (org-back-over-empty-lines)
7135 (if (save-excursion
7136 (goto-char (max (point-min) (1- (point))))
7137 (org-at-heading-p))
7138 (1- (point))
7139 (point))))
7140 (setq b (match-beginning 1)))
7141 (outline-flag-region b e nil)))))))
7142 ;; Never hide empty lines at the end of the file.
7143 (save-excursion
7144 (goto-char (point-max))
7145 (outline-previous-heading)
7146 (outline-end-of-heading)
7147 (if (and (looking-at "[ \t\n]+")
7148 (= (match-end 0) (point-max)))
7149 (outline-flag-region (point) (match-end 0) nil))))
7151 (defun org-show-empty-lines-in-parent ()
7152 "Move to the parent and re-show empty lines before visible headlines."
7153 (save-excursion
7154 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7155 (org-cycle-show-empty-lines context))))
7157 (defun org-files-list ()
7158 "Return `org-agenda-files' list, plus all open org-mode files.
7159 This is useful for operations that need to scan all of a user's
7160 open and agenda-wise Org files."
7161 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7162 (dolist (buf (buffer-list))
7163 (with-current-buffer buf
7164 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7165 (let ((file (expand-file-name (buffer-file-name))))
7166 (unless (member file files)
7167 (push file files))))))
7168 files))
7170 (defsubst org-entry-beginning-position ()
7171 "Return the beginning position of the current entry."
7172 (save-excursion (outline-back-to-heading t) (point)))
7174 (defsubst org-entry-end-position ()
7175 "Return the end position of the current entry."
7176 (save-excursion (outline-next-heading) (point)))
7178 (defun org-cycle-hide-drawers (state &optional exceptions)
7179 "Re-hide all drawers after a visibility state change.
7180 When non-nil, optional argument EXCEPTIONS is a list of strings
7181 specifying which drawers should not be hidden."
7182 (when (and (derived-mode-p 'org-mode)
7183 (not (memq state '(overview folded contents))))
7184 (save-excursion
7185 (let* ((globalp (memq state '(contents all)))
7186 (beg (if globalp (point-min) (point)))
7187 (end (if globalp (point-max)
7188 (if (eq state 'children)
7189 (save-excursion (outline-next-heading) (point))
7190 (org-end-of-subtree t)))))
7191 (goto-char beg)
7192 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7193 (unless (member-ignore-case (match-string 1) exceptions)
7194 (let ((drawer (org-element-at-point)))
7195 (when (memq (org-element-type drawer) '(drawer property-drawer))
7196 (org-flag-drawer t drawer)
7197 ;; Make sure to skip drawer entirely or we might flag
7198 ;; it another time when matching its ending line with
7199 ;; `org-drawer-regexp'.
7200 (goto-char (org-element-property :end drawer))))))))))
7202 (defun org-cycle-hide-inline-tasks (state)
7203 "Re-hide inline tasks when switching to 'contents or 'children
7204 visibility state."
7205 (case state
7206 (contents
7207 (when (org-bound-and-true-p org-inlinetask-min-level)
7208 (hide-sublevels (1- org-inlinetask-min-level))))
7209 (children
7210 (when (featurep 'org-inlinetask)
7211 (save-excursion
7212 (while (and (outline-next-heading)
7213 (org-inlinetask-at-task-p))
7214 (org-inlinetask-toggle-visibility)
7215 (org-inlinetask-goto-end)))))))
7217 (defun org-flag-drawer (flag &optional element)
7218 "When FLAG is non-nil, hide the drawer we are at.
7219 Otherwise make it visible. When optional argument ELEMENT is
7220 a parsed drawer, as returned by `org-element-at-point', hide or
7221 show that drawer instead."
7222 (when (save-excursion
7223 (beginning-of-line)
7224 (org-looking-at-p org-drawer-regexp))
7225 (let ((drawer (or element (org-element-at-point))))
7226 (when (memq (org-element-type drawer) '(drawer property-drawer))
7227 (let ((post (org-element-property :post-affiliated drawer)))
7228 (save-excursion
7229 (outline-flag-region
7230 (progn (goto-char post) (line-end-position))
7231 (progn (goto-char (org-element-property :end drawer))
7232 (skip-chars-backward " \r\t\n")
7233 (line-end-position))
7234 flag))
7235 ;; When the drawer is hidden away, make sure point lies in
7236 ;; a visible part of the buffer.
7237 (when (and flag (> (line-beginning-position) post))
7238 (goto-char post)))))))
7240 (defun org-subtree-end-visible-p ()
7241 "Is the end of the current subtree visible?"
7242 (pos-visible-in-window-p
7243 (save-excursion (org-end-of-subtree t) (point))))
7245 (defun org-first-headline-recenter (&optional N)
7246 "Move cursor to the first headline and recenter the headline.
7247 Optional argument N means put the headline into the Nth line of the window."
7248 (goto-char (point-min))
7249 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7250 (beginning-of-line)
7251 (recenter (prefix-numeric-value N))))
7253 ;;; Saving and restoring visibility
7255 (defun org-outline-overlay-data (&optional use-markers)
7256 "Return a list of the locations of all outline overlays.
7257 These are overlays with the `invisible' property value `outline'.
7258 The return value is a list of cons cells, with start and stop
7259 positions for each overlay.
7260 If USE-MARKERS is set, return the positions as markers."
7261 (let (beg end)
7262 (save-excursion
7263 (save-restriction
7264 (widen)
7265 (delq nil
7266 (mapcar (lambda (o)
7267 (when (eq (overlay-get o 'invisible) 'outline)
7268 (setq beg (overlay-start o)
7269 end (overlay-end o))
7270 (and beg end (> end beg)
7271 (if use-markers
7272 (cons (copy-marker beg)
7273 (copy-marker end t))
7274 (cons beg end)))))
7275 (overlays-in (point-min) (point-max))))))))
7277 (defun org-set-outline-overlay-data (data)
7278 "Create visibility overlays for all positions in DATA.
7279 DATA should have been made by `org-outline-overlay-data'."
7280 (let (o)
7281 (save-excursion
7282 (save-restriction
7283 (widen)
7284 (show-all)
7285 (mapc (lambda (c)
7286 (outline-flag-region (car c) (cdr c) t))
7287 data)))))
7289 ;;; Folding of blocks
7291 (defvar org-hide-block-overlays nil
7292 "Overlays hiding blocks.")
7293 (make-variable-buffer-local 'org-hide-block-overlays)
7295 (defun org-block-map (function &optional start end)
7296 "Call FUNCTION at the head of all source blocks in the current buffer.
7297 Optional arguments START and END can be used to limit the range."
7298 (let ((start (or start (point-min)))
7299 (end (or end (point-max))))
7300 (save-excursion
7301 (goto-char start)
7302 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7303 (save-excursion
7304 (save-match-data
7305 (goto-char (match-beginning 0))
7306 (funcall function)))))))
7308 (defun org-hide-block-toggle-all ()
7309 "Toggle the visibility of all blocks in the current buffer."
7310 (org-block-map 'org-hide-block-toggle))
7312 (defun org-hide-block-all ()
7313 "Fold all blocks in the current buffer."
7314 (interactive)
7315 (org-show-block-all)
7316 (org-block-map 'org-hide-block-toggle-maybe))
7318 (defun org-show-block-all ()
7319 "Unfold all blocks in the current buffer."
7320 (interactive)
7321 (mapc 'delete-overlay org-hide-block-overlays)
7322 (setq org-hide-block-overlays nil))
7324 (defun org-hide-block-toggle-maybe ()
7325 "Toggle visibility of block at point."
7326 (interactive)
7327 (let ((case-fold-search t))
7328 (if (save-excursion
7329 (beginning-of-line 1)
7330 (looking-at org-block-regexp))
7331 (progn (org-hide-block-toggle)
7332 t) ;; to signal that we took action
7333 nil))) ;; to signal that we did not
7335 (defun org-hide-block-toggle (&optional force)
7336 "Toggle the visibility of the current block."
7337 (interactive)
7338 (save-excursion
7339 (beginning-of-line)
7340 (if (re-search-forward org-block-regexp nil t)
7341 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7342 (end (match-end 0)) ;; end of entire body
7344 (if (memq t (mapcar (lambda (overlay)
7345 (eq (overlay-get overlay 'invisible)
7346 'org-hide-block))
7347 (overlays-at start)))
7348 (if (or (not force) (eq force 'off))
7349 (mapc (lambda (ov)
7350 (when (member ov org-hide-block-overlays)
7351 (setq org-hide-block-overlays
7352 (delq ov org-hide-block-overlays)))
7353 (when (eq (overlay-get ov 'invisible)
7354 'org-hide-block)
7355 (delete-overlay ov)))
7356 (overlays-at start)))
7357 (setq ov (make-overlay start end))
7358 (overlay-put ov 'invisible 'org-hide-block)
7359 ;; make the block accessible to isearch
7360 (overlay-put
7361 ov 'isearch-open-invisible
7362 (lambda (ov)
7363 (when (member ov org-hide-block-overlays)
7364 (setq org-hide-block-overlays
7365 (delq ov org-hide-block-overlays)))
7366 (when (eq (overlay-get ov 'invisible)
7367 'org-hide-block)
7368 (delete-overlay ov))))
7369 (push ov org-hide-block-overlays)))
7370 (user-error "Not looking at a source block"))))
7372 ;; org-tab-after-check-for-cycling-hook
7373 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7374 ;; Remove overlays when changing major mode
7375 (add-hook 'org-mode-hook
7376 (lambda () (org-add-hook 'change-major-mode-hook
7377 'org-show-block-all 'append 'local)))
7379 ;;; Org-goto
7381 (defvar org-goto-window-configuration nil)
7382 (defvar org-goto-marker nil)
7383 (defvar org-goto-map)
7384 (defun org-goto-map ()
7385 "Set the keymap `org-goto'."
7386 (setq org-goto-map
7387 (let ((map (make-sparse-keymap)))
7388 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7389 mouse-drag-region universal-argument org-occur))
7390 cmd)
7391 (while (setq cmd (pop cmds))
7392 (substitute-key-definition cmd cmd map global-map)))
7393 (suppress-keymap map)
7394 (org-defkey map "\C-m" 'org-goto-ret)
7395 (org-defkey map [(return)] 'org-goto-ret)
7396 (org-defkey map [(left)] 'org-goto-left)
7397 (org-defkey map [(right)] 'org-goto-right)
7398 (org-defkey map [(control ?g)] 'org-goto-quit)
7399 (org-defkey map "\C-i" 'org-cycle)
7400 (org-defkey map [(tab)] 'org-cycle)
7401 (org-defkey map [(down)] 'outline-next-visible-heading)
7402 (org-defkey map [(up)] 'outline-previous-visible-heading)
7403 (if org-goto-auto-isearch
7404 (if (fboundp 'define-key-after)
7405 (define-key-after map [t] 'org-goto-local-auto-isearch)
7406 nil)
7407 (org-defkey map "q" 'org-goto-quit)
7408 (org-defkey map "n" 'outline-next-visible-heading)
7409 (org-defkey map "p" 'outline-previous-visible-heading)
7410 (org-defkey map "f" 'outline-forward-same-level)
7411 (org-defkey map "b" 'outline-backward-same-level)
7412 (org-defkey map "u" 'outline-up-heading))
7413 (org-defkey map "/" 'org-occur)
7414 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7415 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7416 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7417 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7418 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7419 map)))
7421 (defconst org-goto-help
7422 "Browse buffer copy, to find location or copy text.%s
7423 RET=jump to location C-g=quit and return to previous location
7424 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7426 (defvar org-goto-start-pos) ; dynamically scoped parameter
7428 (defun org-goto (&optional alternative-interface)
7429 "Look up a different location in the current file, keeping current visibility.
7431 When you want look-up or go to a different location in a
7432 document, the fastest way is often to fold the entire buffer and
7433 then dive into the tree. This method has the disadvantage, that
7434 the previous location will be folded, which may not be what you
7435 want.
7437 This command works around this by showing a copy of the current
7438 buffer in an indirect buffer, in overview mode. You can dive
7439 into the tree in that copy, use org-occur and incremental search
7440 to find a location. When pressing RET or `Q', the command
7441 returns to the original buffer in which the visibility is still
7442 unchanged. After RET it will also jump to the location selected
7443 in the indirect buffer and expose the headline hierarchy above.
7445 With a prefix argument, use the alternative interface: e.g. if
7446 `org-goto-interface' is 'outline use 'outline-path-completion."
7447 (interactive "P")
7448 (org-goto-map)
7449 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7450 (org-refile-use-outline-path t)
7451 (org-refile-target-verify-function nil)
7452 (interface
7453 (if (not alternative-interface)
7454 org-goto-interface
7455 (if (eq org-goto-interface 'outline)
7456 'outline-path-completion
7457 'outline)))
7458 (org-goto-start-pos (point))
7459 (selected-point
7460 (if (eq interface 'outline)
7461 (car (org-get-location (current-buffer) org-goto-help))
7462 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7463 (org-refile-check-position pa)
7464 (nth 3 pa)))))
7465 (if selected-point
7466 (progn
7467 (org-mark-ring-push org-goto-start-pos)
7468 (goto-char selected-point)
7469 (if (or (outline-invisible-p) (org-invisible-p2))
7470 (org-show-context 'org-goto)))
7471 (message "Quit"))))
7473 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7474 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7475 (defvar org-goto-local-auto-isearch-map) ; defined below
7477 (defun org-get-location (buf help)
7478 "Let the user select a location in the Org-mode buffer BUF.
7479 This function uses a recursive edit. It returns the selected position
7480 or nil."
7481 (org-no-popups
7482 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7483 (isearch-hide-immediately nil)
7484 (isearch-search-fun-function
7485 (lambda () 'org-goto-local-search-headings))
7486 (org-goto-selected-point org-goto-exit-command))
7487 (save-excursion
7488 (save-window-excursion
7489 (delete-other-windows)
7490 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7491 (org-pop-to-buffer-same-window
7492 (condition-case nil
7493 (make-indirect-buffer (current-buffer) "*org-goto*")
7494 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7495 (with-output-to-temp-buffer "*Org Help*"
7496 (princ (format help (if org-goto-auto-isearch
7497 " Just type for auto-isearch."
7498 " n/p/f/b/u to navigate, q to quit."))))
7499 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7500 (setq buffer-read-only nil)
7501 (let ((org-startup-truncated t)
7502 (org-startup-folded nil)
7503 (org-startup-align-all-tables nil))
7504 (org-mode)
7505 (org-overview))
7506 (setq buffer-read-only t)
7507 (if (and (boundp 'org-goto-start-pos)
7508 (integer-or-marker-p org-goto-start-pos))
7509 (let ((org-show-hierarchy-above t)
7510 (org-show-siblings t)
7511 (org-show-following-heading t))
7512 (goto-char org-goto-start-pos)
7513 (and (outline-invisible-p) (org-show-context)))
7514 (goto-char (point-min)))
7515 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7516 (message "Select location and press RET")
7517 (use-local-map org-goto-map)
7518 (recursive-edit)))
7519 (kill-buffer "*org-goto*")
7520 (cons org-goto-selected-point org-goto-exit-command))))
7522 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7523 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7524 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7525 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7527 (defun org-goto-local-search-headings (string bound noerror)
7528 "Search and make sure that any matches are in headlines."
7529 (catch 'return
7530 (while (if isearch-forward
7531 (search-forward string bound noerror)
7532 (search-backward string bound noerror))
7533 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7534 (and (member :headline context)
7535 (not (member :tags context))))
7536 (throw 'return (point))))))
7538 (defun org-goto-local-auto-isearch ()
7539 "Start isearch."
7540 (interactive)
7541 (goto-char (point-min))
7542 (let ((keys (this-command-keys)))
7543 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7544 (isearch-mode t)
7545 (isearch-process-search-char (string-to-char keys)))))
7547 (defun org-goto-ret (&optional arg)
7548 "Finish `org-goto' by going to the new location."
7549 (interactive "P")
7550 (setq org-goto-selected-point (point)
7551 org-goto-exit-command 'return)
7552 (throw 'exit nil))
7554 (defun org-goto-left ()
7555 "Finish `org-goto' by going to the new location."
7556 (interactive)
7557 (if (org-at-heading-p)
7558 (progn
7559 (beginning-of-line 1)
7560 (setq org-goto-selected-point (point)
7561 org-goto-exit-command 'left)
7562 (throw 'exit nil))
7563 (user-error "Not on a heading")))
7565 (defun org-goto-right ()
7566 "Finish `org-goto' by going to the new location."
7567 (interactive)
7568 (if (org-at-heading-p)
7569 (progn
7570 (setq org-goto-selected-point (point)
7571 org-goto-exit-command 'right)
7572 (throw 'exit nil))
7573 (user-error "Not on a heading")))
7575 (defun org-goto-quit ()
7576 "Finish `org-goto' without cursor motion."
7577 (interactive)
7578 (setq org-goto-selected-point nil)
7579 (setq org-goto-exit-command 'quit)
7580 (throw 'exit nil))
7582 ;;; Indirect buffer display of subtrees
7584 (defvar org-indirect-dedicated-frame nil
7585 "This is the frame being used for indirect tree display.")
7586 (defvar org-last-indirect-buffer nil)
7588 (defun org-tree-to-indirect-buffer (&optional arg)
7589 "Create indirect buffer and narrow it to current subtree.
7590 With a numerical prefix ARG, go up to this level and then take that tree.
7591 If ARG is negative, go up that many levels.
7593 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7594 indirect buffer previously made with this command, to avoid proliferation of
7595 indirect buffers. However, when you call the command with a \
7596 \\[universal-argument] prefix, or
7597 when `org-indirect-buffer-display' is `new-frame', the last buffer
7598 is kept so that you can work with several indirect buffers at the same time.
7599 If `org-indirect-buffer-display' is `dedicated-frame', the \
7600 \\[universal-argument] prefix also
7601 requests that a new frame be made for the new buffer, so that the dedicated
7602 frame is not changed."
7603 (interactive "P")
7604 (let ((cbuf (current-buffer))
7605 (cwin (selected-window))
7606 (pos (point))
7607 beg end level heading ibuf)
7608 (save-excursion
7609 (org-back-to-heading t)
7610 (when (numberp arg)
7611 (setq level (org-outline-level))
7612 (if (< arg 0) (setq arg (+ level arg)))
7613 (while (> (setq level (org-outline-level)) arg)
7614 (org-up-heading-safe)))
7615 (setq beg (point)
7616 heading (org-get-heading))
7617 (org-end-of-subtree t t)
7618 (if (org-at-heading-p) (backward-char 1))
7619 (setq end (point)))
7620 (if (and (buffer-live-p org-last-indirect-buffer)
7621 (not (eq org-indirect-buffer-display 'new-frame))
7622 (not arg))
7623 (kill-buffer org-last-indirect-buffer))
7624 (setq ibuf (org-get-indirect-buffer cbuf heading)
7625 org-last-indirect-buffer ibuf)
7626 (cond
7627 ((or (eq org-indirect-buffer-display 'new-frame)
7628 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7629 (select-frame (make-frame))
7630 (delete-other-windows)
7631 (org-pop-to-buffer-same-window ibuf)
7632 (org-set-frame-title heading))
7633 ((eq org-indirect-buffer-display 'dedicated-frame)
7634 (raise-frame
7635 (select-frame (or (and org-indirect-dedicated-frame
7636 (frame-live-p org-indirect-dedicated-frame)
7637 org-indirect-dedicated-frame)
7638 (setq org-indirect-dedicated-frame (make-frame)))))
7639 (delete-other-windows)
7640 (org-pop-to-buffer-same-window ibuf)
7641 (org-set-frame-title (concat "Indirect: " heading)))
7642 ((eq org-indirect-buffer-display 'current-window)
7643 (org-pop-to-buffer-same-window ibuf))
7644 ((eq org-indirect-buffer-display 'other-window)
7645 (pop-to-buffer ibuf))
7646 (t (error "Invalid value")))
7647 (if (featurep 'xemacs)
7648 (save-excursion (org-mode) (turn-on-font-lock)))
7649 (narrow-to-region beg end)
7650 (show-all)
7651 (goto-char pos)
7652 (run-hook-with-args 'org-cycle-hook 'all)
7653 (and (window-live-p cwin) (select-window cwin))))
7655 (defun org-get-indirect-buffer (&optional buffer heading)
7656 (setq buffer (or buffer (current-buffer)))
7657 (let ((n 1) (base (buffer-name buffer)) bname)
7658 (while (buffer-live-p
7659 (get-buffer
7660 (setq bname
7661 (concat base "-"
7662 (if heading (concat heading "-" (number-to-string n))
7663 (number-to-string n))))))
7664 (setq n (1+ n)))
7665 (condition-case nil
7666 (make-indirect-buffer buffer bname 'clone)
7667 (error (make-indirect-buffer buffer bname)))))
7669 (defun org-set-frame-title (title)
7670 "Set the title of the current frame to the string TITLE."
7671 ;; FIXME: how to name a single frame in XEmacs???
7672 (unless (featurep 'xemacs)
7673 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7675 ;;;; Structure editing
7677 ;;; Inserting headlines
7679 (defun org-previous-line-empty-p (&optional next)
7680 "Is the previous line a blank line?
7681 When NEXT is non-nil, check the next line instead."
7682 (save-excursion
7683 (and (not (bobp))
7684 (or (beginning-of-line (if next 2 0)) t)
7685 (save-match-data
7686 (looking-at "[ \t]*$")))))
7688 (defun org-insert-heading (&optional arg invisible-ok)
7689 "Insert a new heading or item with same depth at point.
7691 If point is in a plain list and ARG is nil, add a new list item.
7693 With one universal prefix argument, insert a heading even when
7694 the point is within a list.
7696 With two universal prefix arguments, insert the heading at the
7697 end of the grandparent subtree. For example, if point is within
7698 a 2nd-level heading, then it will insert a 2nd-level heading at
7699 the end of the 1st-level parent heading.
7701 If point is at the beginning of a headline, insert a sibling
7702 before the current headline. If point is not at the beginning,
7703 split the line and create a new headline with the text in the
7704 current line after point \(see `org-M-RET-may-split-line' on how
7705 to modify this behavior).
7707 If point is at the beginning of a normal line, turn this line
7708 into a heading.
7710 When INVISIBLE-OK is set, stop at invisible headlines when going
7711 back. This is important for non-interactive uses of the
7712 command."
7713 (interactive "P")
7714 (if (org-called-interactively-p 'any) (org-reveal))
7715 (let ((itemp (org-in-item-p))
7716 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7717 (respect-content (or org-insert-heading-respect-content
7718 (equal arg '(4))))
7719 (initial-content "")
7720 (adjust-empty-lines t))
7722 (cond
7724 ((or (= (buffer-size) 0)
7725 (and (not (save-excursion
7726 (and (ignore-errors (org-back-to-heading invisible-ok))
7727 (org-at-heading-p))))
7728 (or arg (not itemp))))
7729 ;; At beginning of buffer or so high up that only a heading
7730 ;; makes sense.
7731 (when (and (org-before-first-heading-p) (not (bolp)))
7732 (re-search-forward org-outline-regexp-bol)
7733 (beginning-of-line 0))
7734 (insert
7735 (if (or (bobp) (org-previous-line-empty-p)) "" "\n")
7736 (if (org-in-src-block-p) ",* " "* "))
7737 (run-hooks 'org-insert-heading-hook))
7739 ((and itemp (not (member arg '((4) (16)))))
7740 ;; Insert an item
7741 (org-insert-item))
7744 ;; Maybe move at the end of the subtree
7745 (when (equal arg '(16))
7746 (org-up-heading-safe)
7747 (org-end-of-subtree t))
7748 ;; Insert a heading
7749 (save-restriction
7750 (widen)
7751 (let* ((level nil)
7752 (on-heading (org-at-heading-p))
7753 (empty-line-p (if on-heading
7754 (org-previous-line-empty-p)
7755 ;; We will decide later
7756 nil))
7757 ;; Get a level string to fall back on
7758 (fix-level
7759 (if (org-before-first-heading-p) "*"
7760 (save-excursion
7761 (org-back-to-heading t)
7762 (if (org-previous-line-empty-p) (setq empty-line-p t))
7763 (looking-at org-outline-regexp)
7764 (make-string (1- (length (match-string 0))) ?*))))
7765 (stars
7766 (save-excursion
7767 (condition-case nil
7768 (progn
7769 (org-back-to-heading invisible-ok)
7770 (when (and (not on-heading)
7771 (featurep 'org-inlinetask)
7772 (integerp org-inlinetask-min-level)
7773 (>= (length (match-string 0))
7774 org-inlinetask-min-level))
7775 ;; Find a heading level before the inline task
7776 (while (and (setq level (org-up-heading-safe))
7777 (>= level org-inlinetask-min-level)))
7778 (if (org-at-heading-p)
7779 (org-back-to-heading invisible-ok)
7780 (error "This should not happen")))
7781 (unless (and (save-excursion
7782 (save-match-data
7783 (org-backward-heading-same-level
7784 1 invisible-ok))
7785 (= (point) (match-beginning 0)))
7786 (not (org-previous-line-empty-p t)))
7787 (setq empty-line-p (or empty-line-p
7788 (org-previous-line-empty-p))))
7789 (match-string 0))
7790 (error (or fix-level "* ")))))
7791 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7792 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7793 pos hide-previous previous-pos)
7795 ;; If we insert after content, move there and clean up whitespace
7796 (when (and respect-content
7797 (not (org-looking-at-p org-outline-regexp-bol))
7798 (not (bolp)))
7799 (if (not (org-before-first-heading-p))
7800 (org-end-of-subtree nil t)
7801 (re-search-forward org-outline-regexp-bol)
7802 (beginning-of-line 0))
7803 (skip-chars-backward " \r\n")
7804 (and (not (looking-back "^\\*+"))
7805 (looking-at "[ \t]+") (replace-match ""))
7806 (unless (eobp) (forward-char 1))
7807 (when (looking-at "^\\*")
7808 (unless (bobp) (backward-char 1))
7809 (insert "\n")))
7811 ;; If we are splitting, grab the text that should be moved to the new headline
7812 (when may-split
7813 (if (org-on-heading-p)
7814 ;; This is a heading, we split intelligently (keeping tags)
7815 (let ((pos (point)))
7816 (goto-char (point-at-bol))
7817 (unless (looking-at org-complex-heading-regexp)
7818 (error "This should not happen"))
7819 (when (and (match-beginning 4)
7820 (> pos (match-beginning 4))
7821 (< pos (match-end 4)))
7822 (setq initial-content (buffer-substring pos (match-end 4)))
7823 (goto-char pos)
7824 (delete-region (point) (match-end 4))
7825 (if (looking-at "[ \t]*$")
7826 (replace-match "")
7827 (insert (make-string (length initial-content) ?\ )))
7828 (setq initial-content (org-trim initial-content)))
7829 (goto-char pos))
7830 ;; a normal line
7831 (setq initial-content
7832 (org-trim (buffer-substring (point) (point-at-eol))))
7833 (delete-region (point) (point-at-eol))))
7835 ;; If we are at the beginning of the line, insert before it. Else after
7836 (cond
7837 ((and (bolp) (looking-at "[ \t]*$")))
7838 ((and (bolp) (not (looking-at "[ \t]*$")))
7839 (open-line 1))
7841 (goto-char (point-at-eol))
7842 (insert "\n")))
7844 ;; Insert the new heading
7845 (insert stars)
7846 (just-one-space)
7847 (insert initial-content)
7848 (when adjust-empty-lines
7849 (if (or (not blank)
7850 (and blank (not (org-previous-line-empty-p))))
7851 (org-N-empty-lines-before-current (if blank 1 0))))
7852 (run-hooks 'org-insert-heading-hook)))))))
7854 (defun org-N-empty-lines-before-current (N)
7855 "Make the number of empty lines before current exactly N.
7856 So this will delete or add empty lines."
7857 (save-excursion
7858 (goto-char (point-at-bol))
7859 (if (looking-back "\\s-+" nil 'greedy)
7860 (replace-match ""))
7861 (or (bobp) (insert "\n"))
7862 (while (> N 0)
7863 (insert "\n")
7864 (setq N (1- N)))))
7866 (defun org-get-heading (&optional no-tags no-todo)
7867 "Return the heading of the current entry, without the stars.
7868 When NO-TAGS is non-nil, don't include tags.
7869 When NO-TODO is non-nil, don't include TODO keywords."
7870 (save-excursion
7871 (org-back-to-heading t)
7872 (cond
7873 ((and no-tags no-todo)
7874 (looking-at org-complex-heading-regexp)
7875 (match-string 4))
7876 (no-tags
7877 (looking-at (concat org-outline-regexp
7878 "\\(.*?\\)"
7879 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7880 (match-string 1))
7881 (no-todo
7882 (looking-at org-todo-line-regexp)
7883 (match-string 3))
7884 (t (looking-at org-heading-regexp)
7885 (match-string 2)))))
7887 (defvar orgstruct-mode) ; defined below
7889 (defun org-heading-components ()
7890 "Return the components of the current heading.
7891 This is a list with the following elements:
7892 - the level as an integer
7893 - the reduced level, different if `org-odd-levels-only' is set.
7894 - the TODO keyword, or nil
7895 - the priority character, like ?A, or nil if no priority is given
7896 - the headline text itself, or the tags string if no headline text
7897 - the tags string, or nil."
7898 (save-excursion
7899 (org-back-to-heading t)
7900 (if (let (case-fold-search)
7901 (looking-at
7902 (if orgstruct-mode
7903 org-heading-regexp
7904 org-complex-heading-regexp)))
7905 (if orgstruct-mode
7906 (list (length (match-string 1))
7907 (org-reduced-level (length (match-string 1)))
7910 (match-string 2)
7911 nil)
7912 (list (length (match-string 1))
7913 (org-reduced-level (length (match-string 1)))
7914 (org-match-string-no-properties 2)
7915 (and (match-end 3) (aref (match-string 3) 2))
7916 (org-match-string-no-properties 4)
7917 (org-match-string-no-properties 5))))))
7919 (defun org-get-entry ()
7920 "Get the entry text, after heading, entire subtree."
7921 (save-excursion
7922 (org-back-to-heading t)
7923 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7925 (defun org-insert-heading-after-current ()
7926 "Insert a new heading with same level as current, after current subtree."
7927 (interactive)
7928 (org-back-to-heading)
7929 (org-insert-heading)
7930 (org-move-subtree-down)
7931 (end-of-line 1))
7933 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7934 "Insert heading with `org-insert-heading-respect-content' set to t."
7935 (interactive "P")
7936 (let ((org-insert-heading-respect-content t))
7937 (org-insert-heading '(4) invisible-ok)))
7939 (defun org-insert-todo-heading-respect-content (&optional force-state)
7940 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7941 (interactive "P")
7942 (let ((org-insert-heading-respect-content t))
7943 (org-insert-todo-heading force-state '(4))))
7945 (defun org-insert-todo-heading (arg &optional force-heading)
7946 "Insert a new heading with the same level and TODO state as current heading.
7947 If the heading has no TODO state, or if the state is DONE, use the first
7948 state (TODO by default). Also with one prefix arg, force first state. With
7949 two prefix args, force inserting at the end of the parent subtree."
7950 (interactive "P")
7951 (when (or force-heading (not (org-insert-item 'checkbox)))
7952 (org-insert-heading (or (and (equal arg '(16)) '(16))
7953 force-heading))
7954 (save-excursion
7955 (org-back-to-heading)
7956 (outline-previous-heading)
7957 (looking-at org-todo-line-regexp))
7958 (let*
7959 ((new-mark-x
7960 (if (or (equal arg '(4))
7961 (not (match-beginning 2))
7962 (member (match-string 2) org-done-keywords))
7963 (car org-todo-keywords-1)
7964 (match-string 2)))
7965 (new-mark
7967 (run-hook-with-args-until-success
7968 'org-todo-get-default-hook new-mark-x nil)
7969 new-mark-x)))
7970 (beginning-of-line 1)
7971 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7972 (if org-treat-insert-todo-heading-as-state-change
7973 (org-todo new-mark)
7974 (insert new-mark " "))))
7975 (when org-provide-todo-statistics
7976 (org-update-parent-todo-statistics))))
7978 (defun org-insert-subheading (arg)
7979 "Insert a new subheading and demote it.
7980 Works for outline headings and for plain lists alike."
7981 (interactive "P")
7982 (org-insert-heading arg)
7983 (cond
7984 ((org-at-heading-p) (org-do-demote))
7985 ((org-at-item-p) (org-indent-item))))
7987 (defun org-insert-todo-subheading (arg)
7988 "Insert a new subheading with TODO keyword or checkbox and demote it.
7989 Works for outline headings and for plain lists alike."
7990 (interactive "P")
7991 (org-insert-todo-heading arg)
7992 (cond
7993 ((org-at-heading-p) (org-do-demote))
7994 ((org-at-item-p) (org-indent-item))))
7996 ;;; Promotion and Demotion
7998 (defvar org-after-demote-entry-hook nil
7999 "Hook run after an entry has been demoted.
8000 The cursor will be at the beginning of the entry.
8001 When a subtree is being demoted, the hook will be called for each node.")
8003 (defvar org-after-promote-entry-hook nil
8004 "Hook run after an entry has been promoted.
8005 The cursor will be at the beginning of the entry.
8006 When a subtree is being promoted, the hook will be called for each node.")
8008 (defun org-promote-subtree ()
8009 "Promote the entire subtree.
8010 See also `org-promote'."
8011 (interactive)
8012 (save-excursion
8013 (org-with-limited-levels (org-map-tree 'org-promote)))
8014 (org-fix-position-after-promote))
8016 (defun org-demote-subtree ()
8017 "Demote the entire subtree. See `org-demote'.
8018 See also `org-promote'."
8019 (interactive)
8020 (save-excursion
8021 (org-with-limited-levels (org-map-tree 'org-demote)))
8022 (org-fix-position-after-promote))
8025 (defun org-do-promote ()
8026 "Promote the current heading higher up the tree.
8027 If the region is active in `transient-mark-mode', promote all headings
8028 in the region."
8029 (interactive)
8030 (save-excursion
8031 (if (org-region-active-p)
8032 (org-map-region 'org-promote (region-beginning) (region-end))
8033 (org-promote)))
8034 (org-fix-position-after-promote))
8036 (defun org-do-demote ()
8037 "Demote the current heading lower down the tree.
8038 If the region is active in `transient-mark-mode', demote all headings
8039 in the region."
8040 (interactive)
8041 (save-excursion
8042 (if (org-region-active-p)
8043 (org-map-region 'org-demote (region-beginning) (region-end))
8044 (org-demote)))
8045 (org-fix-position-after-promote))
8047 (defun org-fix-position-after-promote ()
8048 "Make sure that after pro/demotion cursor position is right."
8049 (let ((pos (point)))
8050 (when (save-excursion
8051 (beginning-of-line 1)
8052 (looking-at org-todo-line-regexp)
8053 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
8054 (cond ((eobp) (insert " "))
8055 ((eolp) (insert " "))
8056 ((equal (char-after) ?\ ) (forward-char 1))))))
8058 (defun org-current-level ()
8059 "Return the level of the current entry, or nil if before the first headline.
8060 The level is the number of stars at the beginning of the headline."
8061 (save-excursion
8062 (org-with-limited-levels
8063 (if (ignore-errors (org-back-to-heading t))
8064 (funcall outline-level)))))
8066 (defun org-get-previous-line-level ()
8067 "Return the outline depth of the last headline before the current line.
8068 Returns 0 for the first headline in the buffer, and nil if before the
8069 first headline."
8070 (and (org-current-level)
8071 (or (and (/= (line-beginning-position) (point-min))
8072 (save-excursion (beginning-of-line 0) (org-current-level)))
8073 0)))
8075 (defun org-reduced-level (l)
8076 "Compute the effective level of a heading.
8077 This takes into account the setting of `org-odd-levels-only'."
8078 (cond
8079 ((zerop l) 0)
8080 (org-odd-levels-only (1+ (floor (/ l 2))))
8081 (t l)))
8083 (defun org-level-increment ()
8084 "Return the number of stars that will be added or removed at a
8085 time to headlines when structure editing, based on the value of
8086 `org-odd-levels-only'."
8087 (if org-odd-levels-only 2 1))
8089 (defun org-get-valid-level (level &optional change)
8090 "Rectify a level change under the influence of `org-odd-levels-only'
8091 LEVEL is a current level, CHANGE is by how much the level should be
8092 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8093 even level numbers will become the next higher odd number."
8094 (if org-odd-levels-only
8095 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8096 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8097 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8098 (max 1 (+ level (or change 0)))))
8100 (if (boundp 'define-obsolete-function-alias)
8101 (if (or (featurep 'xemacs) (< emacs-major-version 23))
8102 (define-obsolete-function-alias 'org-get-legal-level
8103 'org-get-valid-level)
8104 (define-obsolete-function-alias 'org-get-legal-level
8105 'org-get-valid-level "23.1")))
8107 (defun org-promote ()
8108 "Promote the current heading higher up the tree.
8109 If the region is active in `transient-mark-mode', promote all headings
8110 in the region."
8111 (org-back-to-heading t)
8112 (let* ((level (save-match-data (funcall outline-level)))
8113 (after-change-functions (remove 'flyspell-after-change-function
8114 after-change-functions))
8115 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8116 (diff (abs (- level (length up-head) -1))))
8117 (cond ((and (= level 1) org-called-with-limited-levels
8118 org-allow-promoting-top-level-subtree)
8119 (replace-match "# " nil t))
8120 ((= level 1)
8121 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8122 (t (replace-match up-head nil t)))
8123 ;; Fixup tag positioning
8124 (unless (= level 1)
8125 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
8126 (if org-adapt-indentation (org-fixup-indentation (- diff))))
8127 (run-hooks 'org-after-promote-entry-hook)))
8129 (defun org-demote ()
8130 "Demote the current heading lower down the tree.
8131 If the region is active in `transient-mark-mode', demote all headings
8132 in the region."
8133 (org-back-to-heading t)
8134 (let* ((level (save-match-data (funcall outline-level)))
8135 (after-change-functions (remove 'flyspell-after-change-function
8136 after-change-functions))
8137 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8138 (diff (abs (- level (length down-head) -1))))
8139 (replace-match down-head nil t)
8140 ;; Fixup tag positioning
8141 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
8142 (if org-adapt-indentation (org-fixup-indentation diff))
8143 (run-hooks 'org-after-demote-entry-hook)))
8145 (defun org-cycle-level ()
8146 "Cycle the level of an empty headline through possible states.
8147 This goes first to child, then to parent, level, then up the hierarchy.
8148 After top level, it switches back to sibling level."
8149 (interactive)
8150 (let ((org-adapt-indentation nil))
8151 (when (org-point-at-end-of-empty-headline)
8152 (setq this-command 'org-cycle-level) ; Only needed for caching
8153 (let ((cur-level (org-current-level))
8154 (prev-level (org-get-previous-line-level)))
8155 (cond
8156 ;; If first headline in file, promote to top-level.
8157 ((= prev-level 0)
8158 (loop repeat (/ (- cur-level 1) (org-level-increment))
8159 do (org-do-promote)))
8160 ;; If same level as prev, demote one.
8161 ((= prev-level cur-level)
8162 (org-do-demote))
8163 ;; If parent is top-level, promote to top level if not already.
8164 ((= prev-level 1)
8165 (loop repeat (/ (- cur-level 1) (org-level-increment))
8166 do (org-do-promote)))
8167 ;; If top-level, return to prev-level.
8168 ((= cur-level 1)
8169 (loop repeat (/ (- prev-level 1) (org-level-increment))
8170 do (org-do-demote)))
8171 ;; If less than prev-level, promote one.
8172 ((< cur-level prev-level)
8173 (org-do-promote))
8174 ;; If deeper than prev-level, promote until higher than
8175 ;; prev-level.
8176 ((> cur-level prev-level)
8177 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8178 do (org-do-promote))))
8179 t))))
8181 (defun org-map-tree (fun)
8182 "Call FUN for every heading underneath the current one."
8183 (org-back-to-heading)
8184 (let ((level (funcall outline-level)))
8185 (save-excursion
8186 (funcall fun)
8187 (while (and (progn
8188 (outline-next-heading)
8189 (> (funcall outline-level) level))
8190 (not (eobp)))
8191 (funcall fun)))))
8193 (defun org-map-region (fun beg end)
8194 "Call FUN for every heading between BEG and END."
8195 (let ((org-ignore-region t))
8196 (save-excursion
8197 (setq end (copy-marker end))
8198 (goto-char beg)
8199 (if (and (re-search-forward org-outline-regexp-bol nil t)
8200 (< (point) end))
8201 (funcall fun))
8202 (while (and (progn
8203 (outline-next-heading)
8204 (< (point) end))
8205 (not (eobp)))
8206 (funcall fun)))))
8208 (defvar org-property-end-re) ; silence byte-compiler
8209 (defun org-fixup-indentation (diff)
8210 "Change the indentation in the current entry by DIFF.
8211 However, if any line in the current entry has no indentation, or if it
8212 would end up with no indentation after the change, nothing at all is done."
8213 (save-excursion
8214 (let ((end (save-excursion (outline-next-heading)
8215 (point-marker)))
8216 (prohibit (if (> diff 0)
8217 "^\\S-"
8218 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8219 col)
8220 (unless (save-excursion (end-of-line 1)
8221 (re-search-forward prohibit end t))
8222 (while (and (< (point) end)
8223 (re-search-forward "^[ \t]+" end t))
8224 (goto-char (match-end 0))
8225 (setq col (current-column))
8226 (if (< diff 0) (replace-match ""))
8227 (org-indent-to-column (+ diff col))))
8228 (move-marker end nil))))
8230 (defun org-convert-to-odd-levels ()
8231 "Convert an org-mode file with all levels allowed to one with odd levels.
8232 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8233 level 5 etc."
8234 (interactive)
8235 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8236 (let ((outline-level 'org-outline-level)
8237 (org-odd-levels-only nil) n)
8238 (save-excursion
8239 (goto-char (point-min))
8240 (while (re-search-forward "^\\*\\*+ " nil t)
8241 (setq n (- (length (match-string 0)) 2))
8242 (while (>= (setq n (1- n)) 0)
8243 (org-demote))
8244 (end-of-line 1))))))
8246 (defun org-convert-to-oddeven-levels ()
8247 "Convert an org-mode file with only odd levels to one with odd/even levels.
8248 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8249 file contains a section with an even level, conversion would
8250 destroy the structure of the file. An error is signaled in this
8251 case."
8252 (interactive)
8253 (goto-char (point-min))
8254 ;; First check if there are no even levels
8255 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8256 (org-show-context t)
8257 (error "Not all levels are odd in this file. Conversion not possible"))
8258 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8259 (let ((outline-regexp org-outline-regexp)
8260 (outline-level 'org-outline-level)
8261 (org-odd-levels-only nil) n)
8262 (save-excursion
8263 (goto-char (point-min))
8264 (while (re-search-forward "^\\*\\*+ " nil t)
8265 (setq n (/ (1- (length (match-string 0))) 2))
8266 (while (>= (setq n (1- n)) 0)
8267 (org-promote))
8268 (end-of-line 1))))))
8270 (defun org-tr-level (n)
8271 "Make N odd if required."
8272 (if org-odd-levels-only (1+ (/ n 2)) n))
8274 ;;; Vertical tree motion, cutting and pasting of subtrees
8276 (defun org-move-subtree-up (&optional arg)
8277 "Move the current subtree up past ARG headlines of the same level."
8278 (interactive "p")
8279 (org-move-subtree-down (- (prefix-numeric-value arg))))
8281 (defun org-move-subtree-down (&optional arg)
8282 "Move the current subtree down past ARG headlines of the same level."
8283 (interactive "p")
8284 (setq arg (prefix-numeric-value arg))
8285 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8286 'org-get-last-sibling))
8287 (ins-point (make-marker))
8288 (cnt (abs arg))
8289 (col (current-column))
8290 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8291 ;; Select the tree
8292 (org-back-to-heading)
8293 (setq beg0 (point))
8294 (save-excursion
8295 (setq ne-beg (org-back-over-empty-lines))
8296 (setq beg (point)))
8297 (save-match-data
8298 (save-excursion (outline-end-of-heading)
8299 (setq folded (outline-invisible-p)))
8300 (progn (org-end-of-subtree nil t)
8301 (unless (eobp) (backward-char))))
8302 (outline-next-heading)
8303 (setq ne-end (org-back-over-empty-lines))
8304 (setq end (point))
8305 (goto-char beg0)
8306 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8307 ;; include less whitespace
8308 (save-excursion
8309 (goto-char beg)
8310 (forward-line (- ne-beg ne-end))
8311 (setq beg (point))))
8312 ;; Find insertion point, with error handling
8313 (while (> cnt 0)
8314 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8315 (progn (goto-char beg0)
8316 (user-error "Cannot move past superior level or buffer limit")))
8317 (setq cnt (1- cnt)))
8318 (if (> arg 0)
8319 ;; Moving forward - still need to move over subtree
8320 (progn (org-end-of-subtree t t)
8321 (save-excursion
8322 (org-back-over-empty-lines)
8323 (or (bolp) (newline)))))
8324 (setq ne-ins (org-back-over-empty-lines))
8325 (move-marker ins-point (point))
8326 (setq txt (buffer-substring beg end))
8327 (org-save-markers-in-region beg end)
8328 (delete-region beg end)
8329 (org-remove-empty-overlays-at beg)
8330 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8331 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8332 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8333 (let ((bbb (point)))
8334 (insert-before-markers txt)
8335 (org-reinstall-markers-in-region bbb)
8336 (move-marker ins-point bbb))
8337 (or (bolp) (insert "\n"))
8338 (setq ins-end (point))
8339 (goto-char ins-point)
8340 (org-skip-whitespace)
8341 (when (and (< arg 0)
8342 (org-first-sibling-p)
8343 (> ne-ins ne-beg))
8344 ;; Move whitespace back to beginning
8345 (save-excursion
8346 (goto-char ins-end)
8347 (let ((kill-whole-line t))
8348 (kill-line (- ne-ins ne-beg)) (point)))
8349 (insert (make-string (- ne-ins ne-beg) ?\n)))
8350 (move-marker ins-point nil)
8351 (if folded
8352 (hide-subtree)
8353 (org-show-entry)
8354 (show-children)
8355 (org-cycle-hide-drawers 'children))
8356 (org-clean-visibility-after-subtree-move)
8357 ;; move back to the initial column we were at
8358 (move-to-column col)))
8360 (defvar org-subtree-clip ""
8361 "Clipboard for cut and paste of subtrees.
8362 This is actually only a copy of the kill, because we use the normal kill
8363 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8365 (defvar org-subtree-clip-folded nil
8366 "Was the last copied subtree folded?
8367 This is used to fold the tree back after pasting.")
8369 (defun org-cut-subtree (&optional n)
8370 "Cut the current subtree into the clipboard.
8371 With prefix arg N, cut this many sequential subtrees.
8372 This is a short-hand for marking the subtree and then cutting it."
8373 (interactive "p")
8374 (org-copy-subtree n 'cut))
8376 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8377 "Copy the current subtree it in the clipboard.
8378 With prefix arg N, copy this many sequential subtrees.
8379 This is a short-hand for marking the subtree and then copying it.
8380 If CUT is non-nil, actually cut the subtree.
8381 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8382 of some markers in the region, even if CUT is non-nil. This is
8383 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8384 (interactive "p")
8385 (let (beg end folded (beg0 (point)))
8386 (if (org-called-interactively-p 'any)
8387 (org-back-to-heading nil) ; take what looks like a subtree
8388 (org-back-to-heading t)) ; take what is really there
8389 (setq beg (point))
8390 (skip-chars-forward " \t\r\n")
8391 (save-match-data
8392 (if nosubtrees
8393 (outline-next-heading)
8394 (save-excursion (outline-end-of-heading)
8395 (setq folded (outline-invisible-p)))
8396 (ignore-errors (org-forward-heading-same-level (1- n) t))
8397 (org-end-of-subtree t t)))
8398 (setq end (point))
8399 (goto-char beg0)
8400 (when (> end beg)
8401 (setq org-subtree-clip-folded folded)
8402 (when (or cut force-store-markers)
8403 (org-save-markers-in-region beg end))
8404 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8405 (setq org-subtree-clip (current-kill 0))
8406 (message "%s: Subtree(s) with %d characters"
8407 (if cut "Cut" "Copied")
8408 (length org-subtree-clip)))))
8410 (defun org-paste-subtree (&optional level tree for-yank)
8411 "Paste the clipboard as a subtree, with modification of headline level.
8412 The entire subtree is promoted or demoted in order to match a new headline
8413 level.
8415 If the cursor is at the beginning of a headline, the same level as
8416 that headline is used to paste the tree.
8418 If not, the new level is derived from the *visible* headings
8419 before and after the insertion point, and taken to be the inferior headline
8420 level of the two. So if the previous visible heading is level 3 and the
8421 next is level 4 (or vice versa), level 4 will be used for insertion.
8422 This makes sure that the subtree remains an independent subtree and does
8423 not swallow low level entries.
8425 You can also force a different level, either by using a numeric prefix
8426 argument, or by inserting the heading marker by hand. For example, if the
8427 cursor is after \"*****\", then the tree will be shifted to level 5.
8429 If optional TREE is given, use this text instead of the kill ring.
8431 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8432 move back over whitespace before inserting, and move point to the end of
8433 the inserted text when done."
8434 (interactive "P")
8435 (setq tree (or tree (and kill-ring (current-kill 0))))
8436 (unless (org-kill-is-subtree-p tree)
8437 (user-error "%s"
8438 (substitute-command-keys
8439 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8440 (org-with-limited-levels
8441 (let* ((visp (not (outline-invisible-p)))
8442 (txt tree)
8443 (^re_ "\\(\\*+\\)[ \t]*")
8444 (old-level (if (string-match org-outline-regexp-bol txt)
8445 (- (match-end 0) (match-beginning 0) 1)
8446 -1))
8447 (force-level (cond (level (prefix-numeric-value level))
8448 ((and (looking-at "[ \t]*$")
8449 (string-match
8450 "^\\*+$" (buffer-substring
8451 (point-at-bol) (point))))
8452 (- (match-end 1) (match-beginning 1)))
8453 ((and (bolp)
8454 (looking-at org-outline-regexp))
8455 (- (match-end 0) (point) 1))))
8456 (previous-level (save-excursion
8457 (condition-case nil
8458 (progn
8459 (outline-previous-visible-heading 1)
8460 (if (looking-at ^re_)
8461 (- (match-end 0) (match-beginning 0) 1)
8463 (error 1))))
8464 (next-level (save-excursion
8465 (condition-case nil
8466 (progn
8467 (or (looking-at org-outline-regexp)
8468 (outline-next-visible-heading 1))
8469 (if (looking-at ^re_)
8470 (- (match-end 0) (match-beginning 0) 1)
8472 (error 1))))
8473 (new-level (or force-level (max previous-level next-level)))
8474 (shift (if (or (= old-level -1)
8475 (= new-level -1)
8476 (= old-level new-level))
8478 (- new-level old-level)))
8479 (delta (if (> shift 0) -1 1))
8480 (func (if (> shift 0) 'org-demote 'org-promote))
8481 (org-odd-levels-only nil)
8482 beg end newend)
8483 ;; Remove the forced level indicator
8484 (if force-level
8485 (delete-region (point-at-bol) (point)))
8486 ;; Paste
8487 (beginning-of-line (if (bolp) 1 2))
8488 (setq beg (point))
8489 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8490 (insert-before-markers txt)
8491 (unless (string-match "\n\\'" txt) (insert "\n"))
8492 (setq newend (point))
8493 (org-reinstall-markers-in-region beg)
8494 (setq end (point))
8495 (goto-char beg)
8496 (skip-chars-forward " \t\n\r")
8497 (setq beg (point))
8498 (if (and (outline-invisible-p) visp)
8499 (save-excursion (outline-show-heading)))
8500 ;; Shift if necessary
8501 (unless (= shift 0)
8502 (save-restriction
8503 (narrow-to-region beg end)
8504 (while (not (= shift 0))
8505 (org-map-region func (point-min) (point-max))
8506 (setq shift (+ delta shift)))
8507 (goto-char (point-min))
8508 (setq newend (point-max))))
8509 (when (or (org-called-interactively-p 'interactive) for-yank)
8510 (message "Clipboard pasted as level %d subtree" new-level))
8511 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8512 kill-ring
8513 (eq org-subtree-clip (current-kill 0))
8514 org-subtree-clip-folded)
8515 ;; The tree was folded before it was killed/copied
8516 (hide-subtree))
8517 (and for-yank (goto-char newend)))))
8519 (defun org-kill-is-subtree-p (&optional txt)
8520 "Check if the current kill is an outline subtree, or a set of trees.
8521 Returns nil if kill does not start with a headline, or if the first
8522 headline level is not the largest headline level in the tree.
8523 So this will actually accept several entries of equal levels as well,
8524 which is OK for `org-paste-subtree'.
8525 If optional TXT is given, check this string instead of the current kill."
8526 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8527 (re (org-get-limited-outline-regexp))
8528 (^re (concat "^" re))
8529 (start-level (and kill
8530 (string-match
8531 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8532 kill)
8533 (- (match-end 2) (match-beginning 2) 1)))
8534 (start (1+ (or (match-beginning 2) -1))))
8535 (if (not start-level)
8536 (progn
8537 nil) ;; does not even start with a heading
8538 (catch 'exit
8539 (while (setq start (string-match ^re kill (1+ start)))
8540 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8541 (throw 'exit nil)))
8542 t))))
8544 (defvar org-markers-to-move nil
8545 "Markers that should be moved with a cut-and-paste operation.
8546 Those markers are stored together with their positions relative to
8547 the start of the region.")
8549 (defun org-save-markers-in-region (beg end)
8550 "Check markers in region.
8551 If these markers are between BEG and END, record their position relative
8552 to BEG, so that after moving the block of text, we can put the markers back
8553 into place.
8554 This function gets called just before an entry or tree gets cut from the
8555 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8556 called immediately, to move the markers with the entries."
8557 (setq org-markers-to-move nil)
8558 (when (featurep 'org-clock)
8559 (org-clock-save-markers-for-cut-and-paste beg end))
8560 (when (featurep 'org-agenda)
8561 (org-agenda-save-markers-for-cut-and-paste beg end)))
8563 (defun org-check-and-save-marker (marker beg end)
8564 "Check if MARKER is between BEG and END.
8565 If yes, remember the marker and the distance to BEG."
8566 (when (and (marker-buffer marker)
8567 (equal (marker-buffer marker) (current-buffer)))
8568 (if (and (>= marker beg) (< marker end))
8569 (push (cons marker (- marker beg)) org-markers-to-move))))
8571 (defun org-reinstall-markers-in-region (beg)
8572 "Move all remembered markers to their position relative to BEG."
8573 (mapc (lambda (x)
8574 (move-marker (car x) (+ beg (cdr x))))
8575 org-markers-to-move)
8576 (setq org-markers-to-move nil))
8578 (defun org-narrow-to-subtree ()
8579 "Narrow buffer to the current subtree."
8580 (interactive)
8581 (save-excursion
8582 (save-match-data
8583 (org-with-limited-levels
8584 (narrow-to-region
8585 (progn (org-back-to-heading t) (point))
8586 (progn (org-end-of-subtree t t)
8587 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8588 (point)))))))
8590 (defun org-narrow-to-block ()
8591 "Narrow buffer to the current block."
8592 (interactive)
8593 (let* ((case-fold-search t)
8594 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8595 "^[ \t]*#\\+end_.*")))
8596 (if blockp
8597 (narrow-to-region (car blockp) (cdr blockp))
8598 (user-error "Not in a block"))))
8600 (eval-when-compile
8601 (defvar org-property-drawer-re))
8603 (defvar org-property-start-re) ;; defined below
8604 (defun org-clone-subtree-with-time-shift (n &optional shift)
8605 "Clone the task (subtree) at point N times.
8606 The clones will be inserted as siblings.
8608 In interactive use, the user will be prompted for the number of
8609 clones to be produced. If the entry has a timestamp, the user
8610 will also be prompted for a time shift, which may be a repeater
8611 as used in time stamps, for example `+3d'. To disable this,
8612 you can call the function with a universal prefix argument.
8614 When a valid repeater is given and the entry contains any time
8615 stamps, the clones will become a sequence in time, with time
8616 stamps in the subtree shifted for each clone produced. If SHIFT
8617 is nil or the empty string, time stamps will be left alone. The
8618 ID property of the original subtree is removed.
8620 If the original subtree did contain time stamps with a repeater,
8621 the following will happen:
8622 - the repeater will be removed in each clone
8623 - an additional clone will be produced, with the current, unshifted
8624 date(s) in the entry.
8625 - the original entry will be placed *after* all the clones, with
8626 repeater intact.
8627 - the start days in the repeater in the original entry will be shifted
8628 to past the last clone.
8629 In this way you can spell out a number of instances of a repeating task,
8630 and still retain the repeater to cover future instances of the task."
8631 (interactive "nNumber of clones to produce: ")
8632 (let ((shift
8633 (or shift
8634 (if (and (not (equal current-prefix-arg '(4)))
8635 (save-excursion
8636 (re-search-forward org-ts-regexp-both
8637 (save-excursion
8638 (org-end-of-subtree t)
8639 (point)) t)))
8640 (read-from-minibuffer
8641 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8642 ""))) ;; No time shift
8643 (n-no-remove -1)
8644 (drawer-re org-drawer-regexp)
8645 beg end template task idprop
8646 shift-n shift-what doshift nmin nmax)
8647 (if (not (and (integerp n) (> n 0)))
8648 (user-error "Invalid number of replications %s" n))
8649 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8650 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8651 shift)))
8652 (user-error "Invalid shift specification %s" shift))
8653 (when doshift
8654 (setq shift-n (string-to-number (match-string 1 shift))
8655 shift-what (cdr (assoc (match-string 2 shift)
8656 '(("d" . day) ("w" . week)
8657 ("m" . month) ("y" . year))))))
8658 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8659 (setq nmin 1 nmax n)
8660 (org-back-to-heading t)
8661 (setq beg (point))
8662 (setq idprop (org-entry-get nil "ID"))
8663 (org-end-of-subtree t t)
8664 (or (bolp) (insert "\n"))
8665 (setq end (point))
8666 (setq template (buffer-substring beg end))
8667 (when (and doshift
8668 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8669 (delete-region beg end)
8670 (setq end beg)
8671 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8672 (goto-char end)
8673 (loop for n from nmin to nmax do
8674 ;; prepare clone
8675 (with-temp-buffer
8676 (insert template)
8677 (org-mode)
8678 (goto-char (point-min))
8679 (org-show-subtree)
8680 (and idprop (if org-clone-delete-id
8681 (org-entry-delete nil "ID")
8682 (org-id-get-create t)))
8683 (unless (= n 0)
8684 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8685 (kill-whole-line))
8686 (goto-char (point-min))
8687 (while (re-search-forward drawer-re nil t)
8688 (org-remove-empty-drawer-at (point))))
8689 (goto-char (point-min))
8690 (when doshift
8691 (while (re-search-forward org-ts-regexp-both nil t)
8692 (org-timestamp-change (* n shift-n) shift-what))
8693 (unless (= n n-no-remove)
8694 (goto-char (point-min))
8695 (while (re-search-forward org-ts-regexp nil t)
8696 (save-excursion
8697 (goto-char (match-beginning 0))
8698 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8699 (delete-region (match-beginning 1) (match-end 1)))))))
8700 (setq task (buffer-string)))
8701 (insert task))
8702 (goto-char beg)))
8704 ;;; Outline Sorting
8706 (defun org-sort (with-case)
8707 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8708 Optional argument WITH-CASE means sort case-sensitively."
8709 (interactive "P")
8710 (cond
8711 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8712 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8714 (org-call-with-arg 'org-sort-entries with-case))))
8716 (defun org-sort-remove-invisible (s)
8717 "Remove invisible links from string S."
8718 (remove-text-properties 0 (length s) org-rm-props s)
8719 (while (string-match org-bracket-link-regexp s)
8720 (setq s (replace-match (if (match-end 2)
8721 (match-string 3 s)
8722 (match-string 1 s)) t t s)))
8723 (let ((st (format " %s " s)))
8724 (while (string-match org-emph-re st)
8725 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8726 (setq s (substring st 1 -1)))
8729 (defvar org-priority-regexp) ; defined later in the file
8731 (defvar org-after-sorting-entries-or-items-hook nil
8732 "Hook that is run after a bunch of entries or items have been sorted.
8733 When children are sorted, the cursor is in the parent line when this
8734 hook gets called. When a region or a plain list is sorted, the cursor
8735 will be in the first entry of the sorted region/list.")
8737 (defun org-sort-entries
8738 (&optional with-case sorting-type getkey-func compare-func property)
8739 "Sort entries on a certain level of an outline tree.
8740 If there is an active region, the entries in the region are sorted.
8741 Else, if the cursor is before the first entry, sort the top-level items.
8742 Else, the children of the entry at point are sorted.
8744 Sorting can be alphabetically, numerically, by date/time as given by
8745 a time stamp, by a property, by priority order, or by a custom function.
8747 The command prompts for the sorting type unless it has been given to the
8748 function through the SORTING-TYPE argument, which needs to be a character,
8749 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8750 the precise meaning of each character:
8752 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8753 c By creation time, which is assumed to be the first inactive time stamp
8754 at the beginning of a line.
8755 d By deadline date/time.
8756 k By clocking time.
8757 n Numerically, by converting the beginning of the entry/item to a number.
8758 o By order of TODO keywords.
8759 p By priority according to the cookie.
8760 r By the value of a property.
8761 s By scheduled date/time.
8762 t By date/time, either the first active time stamp in the entry, or, if
8763 none exist, by the first inactive one.
8765 Capital letters will reverse the sort order.
8767 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8768 called with point at the beginning of the record. It must return either
8769 a string or a number that should serve as the sorting key for that record.
8771 Comparing entries ignores case by default. However, with an optional argument
8772 WITH-CASE, the sorting considers case as well.
8774 Sorting is done against the visible part of the headlines, it ignores hidden
8775 links.
8777 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
8778 (interactive "P")
8779 (let ((case-func (if with-case 'identity 'downcase))
8780 (cmstr
8781 ;; The clock marker is lost when using `sort-subr', let's
8782 ;; store the clocking string.
8783 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8784 (save-excursion
8785 (goto-char org-clock-marker)
8786 (looking-back "^.*") (match-string-no-properties 0))))
8787 start beg end stars re re2
8788 txt what tmp)
8789 ;; Find beginning and end of region to sort
8790 (cond
8791 ((org-region-active-p)
8792 ;; we will sort the region
8793 (setq end (region-end)
8794 what "region")
8795 (goto-char (region-beginning))
8796 (if (not (org-at-heading-p)) (outline-next-heading))
8797 (setq start (point)))
8798 ((or (org-at-heading-p)
8799 (ignore-errors (progn (org-back-to-heading) t)))
8800 ;; we will sort the children of the current headline
8801 (org-back-to-heading)
8802 (setq start (point)
8803 end (progn (org-end-of-subtree t t)
8804 (or (bolp) (insert "\n"))
8805 (when (>= (org-back-over-empty-lines) 1)
8806 (forward-line 1))
8807 (point))
8808 what "children")
8809 (goto-char start)
8810 (show-subtree)
8811 (outline-next-heading))
8813 ;; we will sort the top-level entries in this file
8814 (goto-char (point-min))
8815 (or (org-at-heading-p) (outline-next-heading))
8816 (setq start (point))
8817 (goto-char (point-max))
8818 (beginning-of-line 1)
8819 (when (looking-at ".*?\\S-")
8820 ;; File ends in a non-white line
8821 (end-of-line 1)
8822 (insert "\n"))
8823 (setq end (point-max))
8824 (setq what "top-level")
8825 (goto-char start)
8826 (show-all)))
8828 (setq beg (point))
8829 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8831 (looking-at "\\(\\*+\\)")
8832 (setq stars (match-string 1)
8833 re (concat "^" (regexp-quote stars) " +")
8834 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8835 txt (buffer-substring beg end))
8836 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8837 (if (and (not (equal stars "*")) (string-match re2 txt))
8838 (user-error "Region to sort contains a level above the first entry"))
8840 (unless sorting-type
8841 (message
8842 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8843 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8844 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8845 what)
8846 (setq sorting-type (read-char-exclusive))
8848 (unless getkey-func
8849 (and (= (downcase sorting-type) ?f)
8850 (setq getkey-func
8851 (org-icompleting-read "Sort using function: "
8852 obarray 'fboundp t nil nil))
8853 (setq getkey-func (intern getkey-func))))
8855 (and (= (downcase sorting-type) ?r)
8856 (not property)
8857 (setq property
8858 (org-icompleting-read "Property: "
8859 (mapcar 'list (org-buffer-property-keys t))
8860 nil t))))
8862 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8863 (message "Sorting entries...")
8865 (save-restriction
8866 (narrow-to-region start end)
8867 (let ((dcst (downcase sorting-type))
8868 (case-fold-search nil)
8869 (now (current-time)))
8870 (sort-subr
8871 (/= dcst sorting-type)
8872 ;; This function moves to the beginning character of the "record" to
8873 ;; be sorted.
8874 (lambda nil
8875 (if (re-search-forward re nil t)
8876 (goto-char (match-beginning 0))
8877 (goto-char (point-max))))
8878 ;; This function moves to the last character of the "record" being
8879 ;; sorted.
8880 (lambda nil
8881 (save-match-data
8882 (condition-case nil
8883 (outline-forward-same-level 1)
8884 (error
8885 (goto-char (point-max))))))
8886 ;; This function returns the value that gets sorted against.
8887 (lambda nil
8888 (cond
8889 ((= dcst ?n)
8890 (if (looking-at org-complex-heading-regexp)
8891 (string-to-number (org-sort-remove-invisible (match-string 4)))
8892 nil))
8893 ((= dcst ?a)
8894 (if (looking-at org-complex-heading-regexp)
8895 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8896 nil))
8897 ((= dcst ?k)
8898 (or (get-text-property (point) :org-clock-minutes) 0))
8899 ((= dcst ?t)
8900 (let ((end (save-excursion (outline-next-heading) (point))))
8901 (if (or (re-search-forward org-ts-regexp end t)
8902 (re-search-forward org-ts-regexp-both end t))
8903 (org-time-string-to-seconds (match-string 0))
8904 (org-float-time now))))
8905 ((= dcst ?c)
8906 (let ((end (save-excursion (outline-next-heading) (point))))
8907 (if (re-search-forward
8908 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8909 end t)
8910 (org-time-string-to-seconds (match-string 0))
8911 (org-float-time now))))
8912 ((= dcst ?s)
8913 (let ((end (save-excursion (outline-next-heading) (point))))
8914 (if (re-search-forward org-scheduled-time-regexp end t)
8915 (org-time-string-to-seconds (match-string 1))
8916 (org-float-time now))))
8917 ((= dcst ?d)
8918 (let ((end (save-excursion (outline-next-heading) (point))))
8919 (if (re-search-forward org-deadline-time-regexp end t)
8920 (org-time-string-to-seconds (match-string 1))
8921 (org-float-time now))))
8922 ((= dcst ?p)
8923 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8924 (string-to-char (match-string 2))
8925 org-default-priority))
8926 ((= dcst ?r)
8927 (or (org-entry-get nil property) ""))
8928 ((= dcst ?o)
8929 (if (looking-at org-complex-heading-regexp)
8930 (let* ((m (match-string 2))
8931 (s (if (member m org-done-keywords) '- '+)))
8932 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
8933 ((= dcst ?f)
8934 (if getkey-func
8935 (progn
8936 (setq tmp (funcall getkey-func))
8937 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8938 tmp)
8939 (error "Invalid key function `%s'" getkey-func)))
8940 (t (error "Invalid sorting type `%c'" sorting-type))))
8942 (cond
8943 ((= dcst ?a) 'string<)
8944 ((= dcst ?f) compare-func)
8945 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
8946 (run-hooks 'org-after-sorting-entries-or-items-hook)
8947 ;; Reset the clock marker if needed
8948 (when cmstr
8949 (save-excursion
8950 (goto-char start)
8951 (search-forward cmstr nil t)
8952 (move-marker org-clock-marker (point))))
8953 (message "Sorting entries...done")))
8955 (defun org-do-sort (table what &optional with-case sorting-type)
8956 "Sort TABLE of WHAT according to SORTING-TYPE.
8957 The user will be prompted for the SORTING-TYPE if the call to this
8958 function does not specify it.
8959 WHAT is only for the prompt, to indicate what is being sorted.
8960 The sorting key will be extracted from the car of the elements of
8961 the table.
8962 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8963 (unless sorting-type
8964 (message
8965 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8966 what)
8967 (setq sorting-type (read-char-exclusive)))
8968 (let ((dcst (downcase sorting-type))
8969 extractfun comparefun)
8970 ;; Define the appropriate functions
8971 (cond
8972 ((= dcst ?n)
8973 (setq extractfun 'string-to-number
8974 comparefun (if (= dcst sorting-type) '< '>)))
8975 ((= dcst ?a)
8976 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8977 (lambda(x) (downcase (org-sort-remove-invisible x))))
8978 comparefun (if (= dcst sorting-type)
8979 'string<
8980 (lambda (a b) (and (not (string< a b))
8981 (not (string= a b)))))))
8982 ((= dcst ?t)
8983 (setq extractfun
8984 (lambda (x)
8985 (cond ((or (string-match org-ts-regexp x)
8986 (string-match org-ts-regexp-both x))
8987 (org-float-time
8988 (org-time-string-to-time (match-string 0 x))))
8989 ((string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" x)
8990 (org-hh:mm-string-to-minutes x))
8991 (t 0)))
8992 comparefun (if (= dcst sorting-type) '< '>)))
8993 (t (error "Invalid sorting type `%c'" sorting-type)))
8995 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8996 table)
8997 (lambda (a b) (funcall comparefun (car a) (car b))))))
9000 ;;; The orgstruct minor mode
9002 ;; Define a minor mode which can be used in other modes in order to
9003 ;; integrate the org-mode structure editing commands.
9005 ;; This is really a hack, because the org-mode structure commands use
9006 ;; keys which normally belong to the major mode. Here is how it
9007 ;; works: The minor mode defines all the keys necessary to operate the
9008 ;; structure commands, but wraps the commands into a function which
9009 ;; tests if the cursor is currently at a headline or a plain list
9010 ;; item. If that is the case, the structure command is used,
9011 ;; temporarily setting many Org-mode variables like regular
9012 ;; expressions for filling etc. However, when any of those keys is
9013 ;; used at a different location, function uses `key-binding' to look
9014 ;; up if the key has an associated command in another currently active
9015 ;; keymap (minor modes, major mode, global), and executes that
9016 ;; command. There might be problems if any of the keys is otherwise
9017 ;; used as a prefix key.
9019 (defcustom orgstruct-heading-prefix-regexp ""
9020 "Regexp that matches the custom prefix of Org headlines in
9021 orgstruct(++)-mode."
9022 :group 'org
9023 :version "24.4"
9024 :package-version '(Org . "8.3")
9025 :type 'regexp)
9026 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9028 (defcustom orgstruct-setup-hook nil
9029 "Hook run after orgstruct-mode-map is filled."
9030 :group 'org
9031 :version "24.4"
9032 :package-version '(Org . "8.0")
9033 :type 'hook)
9035 (defvar orgstruct-initialized nil)
9037 (defvar org-local-vars nil
9038 "List of local variables, for use by `orgstruct-mode'.")
9040 ;;;###autoload
9041 (define-minor-mode orgstruct-mode
9042 "Toggle the minor mode `orgstruct-mode'.
9043 This mode is for using Org-mode structure commands in other
9044 modes. The following keys behave as if Org-mode were active, if
9045 the cursor is on a headline, or on a plain list item (both as
9046 defined by Org-mode)."
9047 nil " OrgStruct" (make-sparse-keymap)
9048 (funcall (if orgstruct-mode
9049 'add-to-invisibility-spec
9050 'remove-from-invisibility-spec)
9051 '(outline . t))
9052 (when orgstruct-mode
9053 (org-load-modules-maybe)
9054 (unless orgstruct-initialized
9055 (orgstruct-setup)
9056 (setq orgstruct-initialized t))))
9058 ;;;###autoload
9059 (defun turn-on-orgstruct ()
9060 "Unconditionally turn on `orgstruct-mode'."
9061 (orgstruct-mode 1))
9063 (defvar org-fb-vars nil)
9064 (make-variable-buffer-local 'org-fb-vars)
9065 (defun orgstruct++-mode (&optional arg)
9066 "Toggle `orgstruct-mode', the enhanced version of it.
9067 In addition to setting orgstruct-mode, this also exports all
9068 indentation and autofilling variables from org-mode into the
9069 buffer. It will also recognize item context in multiline items."
9070 (interactive "P")
9071 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9072 (if (< arg 1)
9073 (progn (orgstruct-mode -1)
9074 (mapc (lambda(v)
9075 (org-set-local (car v)
9076 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
9077 org-fb-vars))
9078 (orgstruct-mode 1)
9079 (setq org-fb-vars nil)
9080 (unless org-local-vars
9081 (setq org-local-vars (org-get-local-variables)))
9082 (let (var val)
9083 (mapc
9084 (lambda (x)
9085 (when (string-match
9086 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
9087 (symbol-name (car x)))
9088 (setq var (car x) val (nth 1 x))
9089 (push (list var `(quote ,(eval var))) org-fb-vars)
9090 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9091 org-local-vars)
9092 (org-set-local 'orgstruct-is-++ t))))
9094 (defvar orgstruct-is-++ nil
9095 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9096 (make-variable-buffer-local 'orgstruct-is-++)
9098 ;;;###autoload
9099 (defun turn-on-orgstruct++ ()
9100 "Unconditionally turn on `orgstruct++-mode'."
9101 (orgstruct++-mode 1))
9103 (defun orgstruct-error ()
9104 "Error when there is no default binding for a structure key."
9105 (interactive)
9106 (funcall (if (fboundp 'user-error)
9107 'user-error
9108 'error)
9109 "This key has no function outside structure elements"))
9111 (defun orgstruct-setup ()
9112 "Setup orgstruct keymap."
9113 (dolist (cell '((org-demote . t)
9114 (org-metaleft . t)
9115 (org-metaright . t)
9116 (org-promote . t)
9117 (org-shiftmetaleft . t)
9118 (org-shiftmetaright . t)
9119 org-backward-element
9120 org-backward-heading-same-level
9121 org-ctrl-c-ret
9122 org-ctrl-c-minus
9123 org-ctrl-c-star
9124 org-cycle
9125 org-forward-heading-same-level
9126 org-insert-heading
9127 org-insert-heading-respect-content
9128 org-kill-note-or-show-branches
9129 org-mark-subtree
9130 org-meta-return
9131 org-metadown
9132 org-metaup
9133 org-narrow-to-subtree
9134 org-promote-subtree
9135 org-reveal
9136 org-shiftdown
9137 org-shiftleft
9138 org-shiftmetadown
9139 org-shiftmetaup
9140 org-shiftright
9141 org-shifttab
9142 org-shifttab
9143 org-shiftup
9144 org-show-subtree
9145 org-sort
9146 org-up-element
9147 outline-demote
9148 outline-next-visible-heading
9149 outline-previous-visible-heading
9150 outline-promote
9151 outline-up-heading
9152 show-children))
9153 (let ((f (or (car-safe cell) cell))
9154 (disable-when-heading-prefix (cdr-safe cell)))
9155 (when (fboundp f)
9156 (let ((new-bindings))
9157 (dolist (binding (nconc (where-is-internal f org-mode-map)
9158 (where-is-internal f outline-mode-map)))
9159 (push binding new-bindings)
9160 ;; TODO use local-function-key-map
9161 (dolist (rep '(("<tab>" . "TAB")
9162 ("<return>" . "RET")
9163 ("<escape>" . "ESC")
9164 ("<delete>" . "DEL")))
9165 (setq binding (read-kbd-macro
9166 (let ((case-fold-search))
9167 (replace-regexp-in-string
9168 (regexp-quote (cdr rep))
9169 (car rep)
9170 (key-description binding)))))
9171 (pushnew binding new-bindings :test 'equal)))
9172 (dolist (binding new-bindings)
9173 (let ((key (lookup-key orgstruct-mode-map binding)))
9174 (when (or (not key) (numberp key))
9175 (ignore-errors
9176 (org-defkey orgstruct-mode-map
9177 binding
9178 (orgstruct-make-binding
9179 f binding disable-when-heading-prefix))))))))))
9180 (run-hooks 'orgstruct-setup-hook))
9182 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9183 "Create a function for binding in the structure minor mode.
9184 FUN is the command to call inside a table. KEY is the key that
9185 should be checked in for a command to execute outside of tables.
9186 Non-nil `disable-when-heading-prefix' means to disable the command
9187 if `orgstruct-heading-prefix-regexp' is not empty."
9188 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9189 (let ((nname name)
9190 (i 0))
9191 (while (fboundp (intern nname))
9192 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9193 (setq name (intern nname)))
9194 (eval
9195 (let ((bindings '((org-heading-regexp
9196 (concat "^"
9197 orgstruct-heading-prefix-regexp
9198 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9199 (org-outline-regexp
9200 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9201 (org-outline-regexp-bol
9202 (concat "^" org-outline-regexp))
9203 (outline-regexp org-outline-regexp)
9204 (outline-heading-end-regexp "\n")
9205 (outline-level 'org-outline-level)
9206 (outline-heading-alist))))
9207 `(defun ,name (arg)
9208 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9209 "Outside of structure, run the binding of `"
9210 (key-description key) "'."
9211 (when disable-when-heading-prefix
9212 (concat
9213 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9214 "back to the default binding due to limitations of Org's implementation of\n"
9215 "`" (symbol-name fun) "'.")))
9216 (interactive "p")
9217 (let* ((disable
9218 ,(and disable-when-heading-prefix
9219 '(not (string= orgstruct-heading-prefix-regexp ""))))
9220 (fallback
9221 (or disable
9222 (not
9223 (let* ,bindings
9224 (org-context-p 'headline 'item
9225 ,(when (memq fun
9226 '(org-insert-heading
9227 org-insert-heading-respect-content
9228 org-meta-return))
9229 '(when orgstruct-is-++
9230 'item-body))))))))
9231 (if fallback
9232 (let* ((orgstruct-mode)
9233 (binding
9234 (loop with key = ,key
9235 for rep in
9236 '(nil
9237 ("<\\([^>]*\\)tab>" . "\\1TAB")
9238 ("<\\([^>]*\\)return>" . "\\1RET")
9239 ("<\\([^>]*\\)escape>" . "\\1ESC")
9240 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9242 (when rep
9243 (setq key (read-kbd-macro
9244 (let ((case-fold-search))
9245 (replace-regexp-in-string
9246 (car rep)
9247 (cdr rep)
9248 (key-description key))))))
9249 thereis (key-binding key))))
9250 (if (keymapp binding)
9251 (org-set-transient-map binding)
9252 (let ((func (or binding
9253 (unless disable
9254 'orgstruct-error))))
9255 (when func
9256 (call-interactively func)))))
9257 (org-run-like-in-org-mode
9258 (lambda ()
9259 (interactive)
9260 (let* ,bindings
9261 (call-interactively ',fun)))))))))
9262 name))
9264 (defun org-contextualize-keys (alist contexts)
9265 "Return valid elements in ALIST depending on CONTEXTS.
9267 `org-agenda-custom-commands' or `org-capture-templates' are the
9268 values used for ALIST, and `org-agenda-custom-commands-contexts'
9269 or `org-capture-templates-contexts' are the associated contexts
9270 definitions."
9271 (let ((contexts
9272 ;; normalize contexts
9273 (mapcar
9274 (lambda(c) (cond ((listp (cadr c))
9275 (list (car c) (car c) (cadr c)))
9276 ((string= "" (cadr c))
9277 (list (car c) (car c) (caddr c)))
9278 (t c))) contexts))
9279 (a alist) c r s)
9280 ;; loop over all commands or templates
9281 (while (setq c (pop a))
9282 (let (vrules repl)
9283 (cond
9284 ((not (assoc (car c) contexts))
9285 (push c r))
9286 ((and (assoc (car c) contexts)
9287 (setq vrules (org-contextualize-validate-key
9288 (car c) contexts)))
9289 (mapc (lambda (vr)
9290 (when (not (equal (car vr) (cadr vr)))
9291 (setq repl vr))) vrules)
9292 (if (not repl) (push c r)
9293 (push (cadr repl) s)
9294 (push
9295 (cons (car c)
9296 (cdr (or (assoc (cadr repl) alist)
9297 (error "Undefined key `%s' as contextual replacement for `%s'"
9298 (cadr repl) (car c)))))
9299 r))))))
9300 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9301 (delq
9303 (delete-dups
9304 (mapcar (lambda (x)
9305 (let ((tpl (car x)))
9306 (when (not (delq
9308 (mapcar (lambda(y)
9309 (equal y tpl)) s))) x)))
9310 (reverse r))))))
9312 (defun org-contextualize-validate-key (key contexts)
9313 "Check CONTEXTS for agenda or capture KEY."
9314 (let (r rr res)
9315 (while (setq r (pop contexts))
9316 (mapc
9317 (lambda (rr)
9318 (when
9319 (and (equal key (car r))
9320 (if (functionp rr) (funcall rr)
9321 (or (and (eq (car rr) 'in-file)
9322 (buffer-file-name)
9323 (string-match (cdr rr) (buffer-file-name)))
9324 (and (eq (car rr) 'in-mode)
9325 (string-match (cdr rr) (symbol-name major-mode)))
9326 (and (eq (car rr) 'in-buffer)
9327 (string-match (cdr rr) (buffer-name)))
9328 (when (and (eq (car rr) 'not-in-file)
9329 (buffer-file-name))
9330 (not (string-match (cdr rr) (buffer-file-name))))
9331 (when (eq (car rr) 'not-in-mode)
9332 (not (string-match (cdr rr) (symbol-name major-mode))))
9333 (when (eq (car rr) 'not-in-buffer)
9334 (not (string-match (cdr rr) (buffer-name)))))))
9335 (push r res)))
9336 (car (last r))))
9337 (delete-dups (delq nil res))))
9339 (defun org-context-p (&rest contexts)
9340 "Check if local context is any of CONTEXTS.
9341 Possible values in the list of contexts are `table', `headline', and `item'."
9342 (let ((pos (point)))
9343 (goto-char (point-at-bol))
9344 (prog1 (or (and (memq 'table contexts)
9345 (looking-at "[ \t]*|"))
9346 (and (memq 'headline contexts)
9347 (looking-at org-outline-regexp))
9348 (and (memq 'item contexts)
9349 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9350 (and (memq 'item-body contexts)
9351 (org-in-item-p)))
9352 (goto-char pos))))
9354 (defun org-get-local-variables ()
9355 "Return a list of all local variables in an Org mode buffer."
9356 (let (varlist)
9357 (with-current-buffer (get-buffer-create "*Org tmp*")
9358 (erase-buffer)
9359 (org-mode)
9360 (setq varlist (buffer-local-variables)))
9361 (kill-buffer "*Org tmp*")
9362 (delq nil
9363 (mapcar
9364 (lambda (x)
9365 (setq x
9366 (if (symbolp x)
9367 (list x)
9368 (list (car x) (cdr x))))
9369 (if (and (not (get (car x) 'org-state))
9370 (string-match
9371 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9372 (symbol-name (car x))))
9373 x nil))
9374 varlist))))
9376 (defun org-clone-local-variables (from-buffer &optional regexp)
9377 "Clone local variables from FROM-BUFFER.
9378 Optional argument REGEXP selects variables to clone."
9379 (mapc
9380 (lambda (pair)
9381 (and (symbolp (car pair))
9382 (or (null regexp)
9383 (string-match regexp (symbol-name (car pair))))
9384 (set (make-local-variable (car pair))
9385 (cdr pair))))
9386 (buffer-local-variables from-buffer)))
9388 ;;;###autoload
9389 (defun org-run-like-in-org-mode (cmd)
9390 "Run a command, pretending that the current buffer is in Org-mode.
9391 This will temporarily bind local variables that are typically bound in
9392 Org-mode to the values they have in Org-mode, and then interactively
9393 call CMD."
9394 (org-load-modules-maybe)
9395 (unless org-local-vars
9396 (setq org-local-vars (org-get-local-variables)))
9397 (let (binds)
9398 (dolist (var org-local-vars)
9399 (when (or (not (boundp (car var)))
9400 (eq (symbol-value (car var))
9401 (default-value (car var))))
9402 (push (list (car var) `(quote ,(cadr var))) binds)))
9403 (eval `(let ,binds
9404 (call-interactively (quote ,cmd))))))
9406 (defun org-get-category (&optional pos force-refresh)
9407 "Get the category applying to position POS."
9408 (save-match-data
9409 (if force-refresh (org-refresh-category-properties))
9410 (let ((pos (or pos (point))))
9411 (or (get-text-property pos 'org-category)
9412 (progn (org-refresh-category-properties)
9413 (get-text-property pos 'org-category))))))
9415 ;;; Refresh properties
9417 (defun org-refresh-properties (dprop tprop)
9418 "Refresh buffer text properties.
9419 DPROP is the drawer property and TPROP is either the
9420 corresponding text property to set, or an alist with each element
9421 being a text property (as a symbol) and a function to apply to
9422 the value of the drawer property."
9423 (let ((case-fold-search t)
9424 (inhibit-read-only t))
9425 (org-with-silent-modifications
9426 (save-excursion
9427 (save-restriction
9428 (widen)
9429 (goto-char (point-min))
9430 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9431 (org-refresh-property tprop (org-match-string-no-properties 1))))))))
9433 (defun org-refresh-property (tprop p)
9434 "Refresh the buffer text property TPROP from the drawer property P.
9435 The refresh happens only for the current tree (not subtree)."
9436 (save-excursion
9437 (org-back-to-heading t)
9438 ;; tprop is a text property symbol
9439 (if (symbolp tprop)
9440 (put-text-property
9441 (point) (or (outline-next-heading) (point-max)) tprop p)
9442 ;; tprop is an alist with (properties . function) elements
9443 (mapc (lambda(al)
9444 (save-excursion
9445 (put-text-property
9446 (point-at-bol) (or (outline-next-heading) (point-max))
9447 (car al)
9448 (funcall (cdr al) p))))
9449 tprop))))
9451 (defun org-refresh-category-properties ()
9452 "Refresh category text properties in the buffer."
9453 (let ((case-fold-search t)
9454 (inhibit-read-only t)
9455 (def-cat (cond
9456 ((null org-category)
9457 (if buffer-file-name
9458 (file-name-sans-extension
9459 (file-name-nondirectory buffer-file-name))
9460 "???"))
9461 ((symbolp org-category) (symbol-name org-category))
9462 (t org-category)))
9463 beg end cat pos optionp)
9464 (org-with-silent-modifications
9465 (save-excursion
9466 (save-restriction
9467 (widen)
9468 (goto-char (point-min))
9469 (put-text-property (point) (point-max) 'org-category def-cat)
9470 (while (re-search-forward
9471 "^[ \t]*\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9472 (setq pos (match-end 0)
9473 optionp (equal (char-after (match-beginning 0)) ?#)
9474 cat (org-trim (match-string 2)))
9475 (if optionp
9476 (setq beg (point-at-bol) end (point-max))
9477 (org-back-to-heading t)
9478 (setq beg (point) end (org-end-of-subtree t t)))
9479 (put-text-property beg end 'org-category cat)
9480 (goto-char pos)))))))
9482 (defun org-refresh-stats-properties ()
9483 "Refresh stats text properties in the buffer."
9484 (let (stats)
9485 (org-with-silent-modifications
9486 (save-excursion
9487 (save-restriction
9488 (widen)
9489 (goto-char (point-min))
9490 (while (re-search-forward
9491 (concat org-outline-regexp-bol ".*"
9492 "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
9493 nil t)
9494 (setq stats (cond ((equal (match-string 3) "0") 0)
9495 ((match-string 2)
9496 (/ (* (string-to-number (match-string 2)) 100)
9497 (string-to-number (match-string 3))))
9498 (t (string-to-number (match-string 1)))))
9499 (org-back-to-heading t)
9500 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9501 'org-stats stats)))))))
9503 (defun org-refresh-effort-properties ()
9504 "Refresh effort properties"
9505 (org-refresh-properties
9506 org-effort-property
9507 '((effort . identity)
9508 (effort-minutes . org-duration-string-to-minutes))))
9510 ;;;; Link Stuff
9512 ;;; Link abbreviations
9514 (defun org-link-expand-abbrev (link)
9515 "Apply replacements as defined in `org-link-abbrev-alist'."
9516 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9517 (let* ((key (match-string 1 link))
9518 (as (or (assoc key org-link-abbrev-alist-local)
9519 (assoc key org-link-abbrev-alist)))
9520 (tag (and (match-end 2) (match-string 3 link)))
9521 rpl)
9522 (if (not as)
9523 link
9524 (setq rpl (cdr as))
9525 (cond
9526 ((symbolp rpl) (funcall rpl tag))
9527 ((string-match "%(\\([^)]+\\))" rpl)
9528 (replace-match
9529 (save-match-data
9530 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9531 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9532 ((string-match "%h" rpl)
9533 (replace-match (url-hexify-string (or tag "")) t t rpl))
9534 (t (concat rpl tag)))))
9535 link))
9537 ;;; Storing and inserting links
9539 (defvar org-insert-link-history nil
9540 "Minibuffer history for links inserted with `org-insert-link'.")
9542 (defvar org-stored-links nil
9543 "Contains the links stored with `org-store-link'.")
9545 (defvar org-store-link-plist nil
9546 "Plist with info about the most recently link created with `org-store-link'.")
9548 (defvar org-link-protocols nil
9549 "Link protocols added to Org-mode using `org-add-link-type'.")
9551 (defvar org-store-link-functions nil
9552 "List of functions that are called to create and store a link.
9553 Each function will be called in turn until one returns a non-nil
9554 value. Each function should check if it is responsible for creating
9555 this link (for example by looking at the major mode).
9556 If not, it must exit and return nil.
9557 If yes, it should return a non-nil value after a calling
9558 `org-store-link-props' with a list of properties and values.
9559 Special properties are:
9561 :type The link prefix, like \"http\". This must be given.
9562 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9563 This is obligatory as well.
9564 :description Optional default description for the second pair
9565 of brackets in an Org-mode link. The user can still change
9566 this when inserting this link into an Org-mode buffer.
9568 In addition to these, any additional properties can be specified
9569 and then used in capture templates.")
9571 (defun org-add-link-type (type &optional follow export)
9572 "Add TYPE to the list of `org-link-types'.
9573 Re-compute all regular expressions depending on `org-link-types'
9575 FOLLOW and EXPORT are two functions.
9577 FOLLOW should take the link path as the single argument and do whatever
9578 is necessary to follow the link, for example find a file or display
9579 a mail message.
9581 EXPORT should format the link path for export to one of the export formats.
9582 It should be a function accepting three arguments:
9584 path the path of the link, the text after the prefix (like \"http:\")
9585 desc the description of the link, if any, or a description added by
9586 org-export-normalize-links if there is none
9587 format the export format, a symbol like `html' or `latex' or `ascii'..
9589 The function may use the FORMAT information to return different values
9590 depending on the format. The return value will be put literally into
9591 the exported file. If the return value is nil, this means Org should
9592 do what it normally does with links which do not have EXPORT defined.
9594 Org-mode has a built-in default for exporting links. If you are happy with
9595 this default, there is no need to define an export function for the link
9596 type. For a simple example of an export function, see `org-bbdb.el'."
9597 (add-to-list 'org-link-types type t)
9598 (org-make-link-regexps)
9599 (if (assoc type org-link-protocols)
9600 (setcdr (assoc type org-link-protocols) (list follow export))
9601 (push (list type follow export) org-link-protocols)))
9603 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9604 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9606 ;;;###autoload
9607 (defun org-store-link (arg)
9608 "\\<org-mode-map>Store an org-link to the current location.
9609 This link is added to `org-stored-links' and can later be inserted
9610 into an org-buffer with \\[org-insert-link].
9612 For some link types, a prefix arg is interpreted.
9613 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9614 For file links, arg negates `org-context-in-file-links'.
9616 A double prefix arg force skipping storing functions that are not
9617 part of Org's core.
9619 A triple prefix arg force storing a link for each line in the
9620 active region."
9621 (interactive "P")
9622 (org-load-modules-maybe)
9623 (if (and (equal arg '(64)) (org-region-active-p))
9624 (save-excursion
9625 (let ((end (region-end)))
9626 (goto-char (region-beginning))
9627 (set-mark (point))
9628 (while (< (point-at-eol) end)
9629 (move-end-of-line 1) (activate-mark)
9630 (let (current-prefix-arg)
9631 (call-interactively 'org-store-link))
9632 (move-beginning-of-line 2)
9633 (set-mark (point)))))
9634 (org-with-limited-levels
9635 (setq org-store-link-plist nil)
9636 (let (link cpltxt desc description search
9637 txt custom-id agenda-link sfuns sfunsn)
9638 (cond
9640 ;; Store a link using an external link type
9641 ((and (not (equal arg '(16)))
9642 (setq sfuns
9643 (delq
9644 nil (mapcar (lambda (f)
9645 (let (fs) (if (funcall f) (push f fs))))
9646 org-store-link-functions))
9647 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9648 (or (and (cdr sfuns)
9649 (funcall (intern
9650 (completing-read
9651 "Which function for creating the link? "
9652 sfunsn nil t (car sfunsn)))))
9653 (funcall (caar sfuns)))
9654 (setq link (plist-get org-store-link-plist :link)
9655 desc (or (plist-get org-store-link-plist
9656 :description) link))))
9658 ;; Store a link from a source code buffer
9659 ((org-src-edit-buffer-p)
9660 (let (label gc)
9661 (while (or (not label)
9662 (save-excursion
9663 (save-restriction
9664 (widen)
9665 (goto-char (point-min))
9666 (re-search-forward
9667 (regexp-quote (format org-coderef-label-format label))
9668 nil t))))
9669 (when label (message "Label exists already") (sit-for 2))
9670 (setq label (read-string "Code line label: " label)))
9671 (end-of-line 1)
9672 (setq link (format org-coderef-label-format label))
9673 (setq gc (- 79 (length link)))
9674 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9675 (insert link)
9676 (setq link (concat "(" label ")") desc nil)))
9678 ;; We are in the agenda, link to referenced location
9679 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9680 (let ((m (or (get-text-property (point) 'org-hd-marker)
9681 (get-text-property (point) 'org-marker))))
9682 (when m
9683 (org-with-point-at m
9684 (setq agenda-link
9685 (if (org-called-interactively-p 'any)
9686 (call-interactively 'org-store-link)
9687 (org-store-link nil)))))))
9689 ((eq major-mode 'calendar-mode)
9690 (let ((cd (calendar-cursor-to-date)))
9691 (setq link
9692 (format-time-string
9693 (car org-time-stamp-formats)
9694 (apply 'encode-time
9695 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9696 nil nil nil))))
9697 (org-store-link-props :type "calendar" :date cd)))
9699 ((eq major-mode 'help-mode)
9700 (setq link (concat "help:" (save-excursion
9701 (goto-char (point-min))
9702 (looking-at "^[^ ]+")
9703 (match-string 0))))
9704 (org-store-link-props :type "help"))
9706 ((eq major-mode 'w3-mode)
9707 (setq cpltxt (if (and (buffer-name)
9708 (not (string-match "Untitled" (buffer-name))))
9709 (buffer-name)
9710 (url-view-url t))
9711 link (url-view-url t))
9712 (org-store-link-props :type "w3" :url (url-view-url t)))
9714 ((eq major-mode 'image-mode)
9715 (setq cpltxt (concat "file:"
9716 (abbreviate-file-name buffer-file-name))
9717 link cpltxt)
9718 (org-store-link-props :type "image" :file buffer-file-name))
9720 ;; In dired, store a link to the file of the current line
9721 ((derived-mode-p 'dired-mode)
9722 (let ((file (dired-get-filename nil t)))
9723 (setq file (if file
9724 (abbreviate-file-name
9725 (expand-file-name (dired-get-filename nil t)))
9726 ;; otherwise, no file so use current directory.
9727 default-directory))
9728 (setq cpltxt (concat "file:" file)
9729 link cpltxt)))
9731 ((setq search (run-hook-with-args-until-success
9732 'org-create-file-search-functions))
9733 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9734 "::" search))
9735 (setq cpltxt (or description link)))
9737 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9738 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9739 (cond
9740 ;; Store a link using the target at point
9741 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9742 (setq cpltxt
9743 (concat "file:"
9744 (abbreviate-file-name
9745 (buffer-file-name (buffer-base-buffer)))
9746 "::" (match-string 1))
9747 link cpltxt))
9748 ((and (featurep 'org-id)
9749 (or (eq org-id-link-to-org-use-id t)
9750 (and (org-called-interactively-p 'any)
9751 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9752 (and (eq org-id-link-to-org-use-id
9753 'create-if-interactive-and-no-custom-id)
9754 (not custom-id))))
9755 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9756 ;; Store a link using the ID at point
9757 (setq link (condition-case nil
9758 (prog1 (org-id-store-link)
9759 (setq desc (or (plist-get org-store-link-plist
9760 :description)
9761 "")))
9762 (error
9763 ;; Probably before first headline, link only to file
9764 (concat "file:"
9765 (abbreviate-file-name
9766 (buffer-file-name (buffer-base-buffer))))))))
9768 ;; Just link to current headline
9769 (setq cpltxt (concat "file:"
9770 (abbreviate-file-name
9771 (buffer-file-name (buffer-base-buffer)))))
9772 ;; Add a context search string
9773 (when (org-xor org-context-in-file-links arg)
9774 (let* ((ee (org-element-at-point))
9775 (et (org-element-type ee))
9776 (ev (plist-get (cadr ee) :value))
9777 (ek (plist-get (cadr ee) :key))
9778 (eok (and (stringp ek) (string-match "name" ek))))
9779 (setq txt (cond
9780 ((org-at-heading-p) nil)
9781 ((and (eq et 'keyword) eok) ev)
9782 ((org-region-active-p)
9783 (buffer-substring (region-beginning) (region-end)))))
9784 (when (or (null txt) (string-match "\\S-" txt))
9785 (setq cpltxt
9786 (concat cpltxt "::"
9787 (condition-case nil
9788 (org-make-org-heading-search-string txt)
9789 (error "")))
9790 desc (or (and (eq et 'keyword) eok ev)
9791 (nth 4 (ignore-errors (org-heading-components)))
9792 "NONE")))))
9793 (if (string-match "::\\'" cpltxt)
9794 (setq cpltxt (substring cpltxt 0 -2)))
9795 (setq link cpltxt))))
9797 ((buffer-file-name (buffer-base-buffer))
9798 ;; Just link to this file here.
9799 (setq cpltxt (concat "file:"
9800 (abbreviate-file-name
9801 (buffer-file-name (buffer-base-buffer)))))
9802 ;; Add a context string.
9803 (when (org-xor org-context-in-file-links arg)
9804 (setq txt (if (org-region-active-p)
9805 (buffer-substring (region-beginning) (region-end))
9806 (buffer-substring (point-at-bol) (point-at-eol))))
9807 ;; Only use search option if there is some text.
9808 (when (string-match "\\S-" txt)
9809 (setq cpltxt
9810 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9811 desc "NONE")))
9812 (setq link cpltxt))
9814 ((org-called-interactively-p 'interactive)
9815 (user-error "No method for storing a link from this buffer"))
9817 (t (setq link nil)))
9819 ;; We're done setting link and desc, clean up
9820 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9821 (setq link (or link cpltxt)
9822 desc (or desc cpltxt))
9823 (cond ((equal desc "NONE") (setq desc nil))
9824 ((and desc (string-match org-bracket-link-analytic-regexp desc))
9825 (let ((d0 (match-string 3 desc))
9826 (p0 (match-string 5 desc)))
9827 (setq desc
9828 (replace-regexp-in-string
9829 org-bracket-link-regexp
9830 (concat (or p0 d0)
9831 (if (equal (length (match-string 0 desc))
9832 (length desc)) "*" "")) desc)))))
9834 ;; Return the link
9835 (if (not (and (or (org-called-interactively-p 'any)
9836 executing-kbd-macro) link))
9837 (or agenda-link (and link (org-make-link-string link desc)))
9838 (push (list link desc) org-stored-links)
9839 (message "Stored: %s" (or desc link))
9840 (when custom-id
9841 (setq link (concat "file:" (abbreviate-file-name
9842 (buffer-file-name)) "::#" custom-id))
9843 (push (list link desc) org-stored-links))
9844 (car org-stored-links))))))
9846 (defun org-store-link-props (&rest plist)
9847 "Store link properties, extract names and addresses."
9848 (let (x adr)
9849 (when (setq x (plist-get plist :from))
9850 (setq adr (mail-extract-address-components x))
9851 (setq plist (plist-put plist :fromname (car adr)))
9852 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9853 (when (setq x (plist-get plist :to))
9854 (setq adr (mail-extract-address-components x))
9855 (setq plist (plist-put plist :toname (car adr)))
9856 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9857 (let ((from (plist-get plist :from))
9858 (to (plist-get plist :to)))
9859 (when (and from to org-from-is-user-regexp)
9860 (setq plist
9861 (plist-put plist :fromto
9862 (if (string-match org-from-is-user-regexp from)
9863 (concat "to %t")
9864 (concat "from %f"))))))
9865 (setq org-store-link-plist plist))
9867 (defun org-add-link-props (&rest plist)
9868 "Add these properties to the link property list."
9869 (let (key value)
9870 (while plist
9871 (setq key (pop plist) value (pop plist))
9872 (setq org-store-link-plist
9873 (plist-put org-store-link-plist key value)))))
9875 (defun org-email-link-description (&optional fmt)
9876 "Return the description part of an email link.
9877 This takes information from `org-store-link-plist' and formats it
9878 according to FMT (default from `org-email-link-description-format')."
9879 (setq fmt (or fmt org-email-link-description-format))
9880 (let* ((p org-store-link-plist)
9881 (to (plist-get p :toaddress))
9882 (from (plist-get p :fromaddress))
9883 (table
9884 (list
9885 (cons "%c" (plist-get p :fromto))
9886 (cons "%F" (plist-get p :from))
9887 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9888 (cons "%T" (plist-get p :to))
9889 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9890 (cons "%s" (plist-get p :subject))
9891 (cons "%d" (plist-get p :date))
9892 (cons "%m" (plist-get p :message-id)))))
9893 (when (string-match "%c" fmt)
9894 ;; Check if the user wrote this message
9895 (if (and org-from-is-user-regexp from to
9896 (save-match-data (string-match org-from-is-user-regexp from)))
9897 (setq fmt (replace-match "to %t" t t fmt))
9898 (setq fmt (replace-match "from %f" t t fmt))))
9899 (org-replace-escapes fmt table)))
9901 (defun org-make-org-heading-search-string (&optional string)
9902 "Make search string for the current headline or STRING."
9903 (let ((s (or string
9904 (and (derived-mode-p 'org-mode)
9905 (save-excursion
9906 (org-back-to-heading t)
9907 (org-element-property :raw-value (org-element-at-point))))))
9908 (lines org-context-in-file-links))
9909 (or string (setq s (concat "*" s))) ; Add * for headlines
9910 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9911 (when (and string (integerp lines) (> lines 0))
9912 (let ((slines (org-split-string s "\n")))
9913 (when (< lines (length slines))
9914 (setq s (mapconcat
9915 'identity
9916 (reverse (nthcdr (- (length slines) lines)
9917 (reverse slines))) "\n")))))
9918 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9920 (defun org-make-link-string (link &optional description)
9921 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9922 (unless (string-match "\\S-" link)
9923 (error "Empty link"))
9924 (when (and description
9925 (stringp description)
9926 (not (string-match "\\S-" description)))
9927 (setq description nil))
9928 (when (stringp description)
9929 ;; Remove brackets from the description, they are fatal.
9930 (while (string-match "\\[" description)
9931 (setq description (replace-match "{" t t description)))
9932 (while (string-match "\\]" description)
9933 (setq description (replace-match "}" t t description))))
9934 (when (equal link description)
9935 ;; No description needed, it is identical
9936 (setq description nil))
9937 (when (and (not description)
9938 (not (string-match (org-image-file-name-regexp) link))
9939 (not (equal link (org-link-escape link))))
9940 (setq description (org-extract-attributes link)))
9941 (setq link
9942 (cond ((string-match (org-image-file-name-regexp) link) link)
9943 ((string-match org-link-types-re link)
9944 (concat (match-string 1 link)
9945 (org-link-escape (substring link (match-end 1)))))
9946 (t (org-link-escape link))))
9947 (concat "[[" link "]"
9948 (if description (concat "[" description "]") "")
9949 "]"))
9951 (defconst org-link-escape-chars
9952 ;;%20 %5B %5D
9953 '(?\ ?\[ ?\])
9954 "List of characters that should be escaped in a link when stored to Org.
9955 This is the list that is used for internal purposes.")
9957 (defconst org-link-escape-chars-browser
9958 ;;%20 %22
9959 '(?\ ?\")
9960 "List of characters to be escaped before handing over to the browser.
9961 If you consider using this constant then you probably want to use
9962 the function `org-link-escape-browser' instead. See there why
9963 this constant is a candidate to be removed once Org drops support
9964 for Emacs 24.1 and 24.2.")
9966 (defun org-link-escape (text &optional table merge)
9967 "Return percent escaped representation of TEXT.
9968 TEXT is a string with the text to escape.
9969 Optional argument TABLE is a list with characters that should be
9970 escaped. When nil, `org-link-escape-chars' is used.
9971 If optional argument MERGE is set, merge TABLE into
9972 `org-link-escape-chars'."
9973 ;; Don't escape chars in internal links
9974 (if (string-match "^\\*[[:alnum:]]+" text)
9975 text
9976 (cond
9977 ((and table merge)
9978 (mapc (lambda (defchr)
9979 (unless (member defchr table)
9980 (setq table (cons defchr table))))
9981 org-link-escape-chars))
9982 ((null table)
9983 (setq table org-link-escape-chars)))
9984 (mapconcat
9985 (lambda (char)
9986 (if (or (member char table)
9987 (and (or (< char 32) (= char ?\%) (> char 126))
9988 org-url-hexify-p))
9989 (mapconcat (lambda (sequence-element)
9990 (format "%%%.2X" sequence-element))
9991 (or (encode-coding-char char 'utf-8)
9992 (error "Unable to percent escape character: %s"
9993 (char-to-string char))) "")
9994 (char-to-string char))) text "")))
9996 (defun org-link-escape-browser (text)
9997 "Escape some characters before handing over to the browser.
9998 This function is a candidate to be removed together with the
9999 constant `org-link-escape-chars-browser' once Org drops support
10000 for Emacs 24.1 and 24.2. All calls to this function will have to
10001 be replaced with `url-encode-url' which is available since Emacs
10002 24.3.1."
10003 ;; Example with the Org link
10004 ;; [[http://lists.gnu.org/archive/cgi-bin/namazu.cgi?idxname=emacs-orgmode&query=%252Bsubject:"Release+8.2"]]
10005 ;; to open the browser with +subject:"Release 8.2" filled into the
10006 ;; query field: In this case the variable TEXT contains the
10007 ;; unescaped [...]=%2Bsubject:"Release+8.2". Then `url-encode-url'
10008 ;; converts correctly to [...]=%2Bsubject:%22Release+8.2%22 or
10009 ;; `org-link-escape' with `org-link-escape-chars-browser' converts
10010 ;; wrongly to [...]=%252Bsubject:%22Release+8.2%22.
10011 (if (fboundp 'url-encode-url)
10012 (url-encode-url text)
10013 (if (org-string-match-p
10014 (concat "[[:nonascii:]" org-link-escape-chars-browser "]")
10015 text)
10016 (org-link-escape text org-link-escape-chars-browser)
10017 text)))
10019 (defun org-link-unescape (str)
10020 "Unhex hexified Unicode strings as returned from the JavaScript function
10021 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
10022 (unless (and (null str) (string= "" str))
10023 (let ((pos 0) (case-fold-search t) unhexed)
10024 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
10025 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
10026 (setq str (replace-match unhexed t t str))
10027 (setq pos (+ pos (length unhexed))))))
10028 str)
10030 (defun org-link-unescape-compound (hex)
10031 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10032 Note: this function also decodes single byte encodings like
10033 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10034 (save-match-data
10035 (let* ((bytes (cdr (split-string hex "%")))
10036 (ret "")
10037 (eat 0)
10038 (sum 0))
10039 (while bytes
10040 (let* ((val (string-to-number (pop bytes) 16))
10041 (shift-xor
10042 (if (= 0 eat)
10043 (cond
10044 ((>= val 252) (cons 6 252))
10045 ((>= val 248) (cons 5 248))
10046 ((>= val 240) (cons 4 240))
10047 ((>= val 224) (cons 3 224))
10048 ((>= val 192) (cons 2 192))
10049 (t (cons 0 0)))
10050 (cons 6 128))))
10051 (if (>= val 192) (setq eat (car shift-xor)))
10052 (setq val (logxor val (cdr shift-xor)))
10053 (setq sum (+ (lsh sum (car shift-xor)) val))
10054 (if (> eat 0) (setq eat (- eat 1)))
10055 (cond
10056 ((= 0 eat) ;multi byte
10057 (setq ret (concat ret (org-char-to-string sum)))
10058 (setq sum 0))
10059 ((not bytes) ; single byte(s)
10060 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10061 ret)))
10063 (defun org-link-unescape-single-byte-sequence (hex)
10064 "Unhexify hex-encoded single byte character sequences."
10065 (mapconcat (lambda (byte)
10066 (char-to-string (string-to-number byte 16)))
10067 (cdr (split-string hex "%")) ""))
10069 (defun org-xor (a b)
10070 "Exclusive or."
10071 (if a (not b) b))
10073 (defun org-fixup-message-id-for-http (s)
10074 "Replace special characters in a message id, so it can be used in an http query."
10075 (when (string-match "%" s)
10076 (setq s (mapconcat (lambda (c)
10077 (if (eq c ?%)
10078 "%25"
10079 (char-to-string c)))
10080 s "")))
10081 (while (string-match "<" s)
10082 (setq s (replace-match "%3C" t t s)))
10083 (while (string-match ">" s)
10084 (setq s (replace-match "%3E" t t s)))
10085 (while (string-match "@" s)
10086 (setq s (replace-match "%40" t t s)))
10089 (defun org-link-prettify (link)
10090 "Return a human-readable representation of LINK.
10091 The car of LINK must be a raw link.
10092 The cdr of LINK must be either a link description or nil."
10093 (let ((desc (or (cadr link) "<no description>")))
10094 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10095 "<" (car link) ">")))
10097 ;;;###autoload
10098 (defun org-insert-link-global ()
10099 "Insert a link like Org-mode does.
10100 This command can be called in any mode to insert a link in Org-mode syntax."
10101 (interactive)
10102 (org-load-modules-maybe)
10103 (org-run-like-in-org-mode 'org-insert-link))
10105 (defun org-insert-all-links (arg &optional pre post)
10106 "Insert all links in `org-stored-links'.
10107 When a universal prefix, do not delete the links from `org-stored-links'.
10108 When `ARG' is a number, insert the last N link(s).
10109 `PRE' and `POST' are optional arguments to define a string to
10110 prepend or to append."
10111 (interactive "P")
10112 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10113 (links (copy-seq org-stored-links))
10114 (pr (or pre "- "))
10115 (po (or post "\n"))
10116 (cnt 1) l)
10117 (if (null org-stored-links)
10118 (message "No link to insert")
10119 (while (and (or (listp arg) (>= arg cnt))
10120 (setq l (if (listp arg)
10121 (pop links)
10122 (pop org-stored-links))))
10123 (setq cnt (1+ cnt))
10124 (insert pr)
10125 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10126 (insert po)))))
10128 (defun org-insert-last-stored-link (arg)
10129 "Insert the last link stored in `org-stored-links'."
10130 (interactive "p")
10131 (org-insert-all-links arg "" "\n"))
10133 (defun org-link-fontify-links-to-this-file ()
10134 "Fontify links to the current file in `org-stored-links'."
10135 (let ((f (buffer-file-name)) a b)
10136 (setq a (mapcar (lambda(l)
10137 (let ((ll (car l)))
10138 (when (and (string-match "^file:\\(.+\\)::" ll)
10139 (equal f (expand-file-name (match-string 1 ll))))
10140 ll)))
10141 org-stored-links))
10142 (when (featurep 'org-id)
10143 (setq b (mapcar (lambda(l)
10144 (let ((ll (car l)))
10145 (when (and (string-match "^id:\\(.+\\)$" ll)
10146 (equal f (expand-file-name
10147 (or (org-id-find-id-file
10148 (match-string 1 ll)) ""))))
10149 ll)))
10150 org-stored-links)))
10151 (mapcar (lambda(l)
10152 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10153 (delq nil (append a b)))))
10155 (defvar org-link-links-in-this-file nil)
10156 (defun org-insert-link (&optional complete-file link-location default-description)
10157 "Insert a link. At the prompt, enter the link.
10159 Completion can be used to insert any of the link protocol prefixes like
10160 http or ftp in use.
10162 The history can be used to select a link previously stored with
10163 `org-store-link'. When the empty string is entered (i.e. if you just
10164 press RET at the prompt), the link defaults to the most recently
10165 stored link. As SPC triggers completion in the minibuffer, you need to
10166 use M-SPC or C-q SPC to force the insertion of a space character.
10168 You will also be prompted for a description, and if one is given, it will
10169 be displayed in the buffer instead of the link.
10171 If there is already a link at point, this command will allow you to edit link
10172 and description parts.
10174 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
10175 be selected using completion. The path to the file will be relative to the
10176 current directory if the file is in the current directory or a subdirectory.
10177 Otherwise, the link will be the absolute path as completed in the minibuffer
10178 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10179 option `org-link-file-path-type'.
10181 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
10182 the current directory or below.
10184 With three \\[universal-argument] prefixes, negate the meaning of
10185 `org-keep-stored-link-after-insertion'.
10187 If `org-make-link-description-function' is non-nil, this function will be
10188 called with the link target, and the result will be the default
10189 link description.
10191 If the LINK-LOCATION parameter is non-nil, this value will be
10192 used as the link location instead of reading one interactively.
10194 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10195 be used as the default description."
10196 (interactive "P")
10197 (let* ((wcf (current-window-configuration))
10198 (origbuf (current-buffer))
10199 (region (if (org-region-active-p)
10200 (buffer-substring (region-beginning) (region-end))))
10201 (remove (and region (list (region-beginning) (region-end))))
10202 (desc region)
10203 tmphist ; byte-compile incorrectly complains about this
10204 (link link-location)
10205 (abbrevs org-link-abbrev-alist-local)
10206 entry file all-prefixes auto-desc)
10207 (cond
10208 (link-location) ; specified by arg, just use it.
10209 ((org-in-regexp org-bracket-link-regexp 1)
10210 ;; We do have a link at point, and we are going to edit it.
10211 (setq remove (list (match-beginning 0) (match-end 0)))
10212 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
10213 (setq link (read-string "Link: "
10214 (org-link-unescape
10215 (org-match-string-no-properties 1)))))
10216 ((or (org-in-regexp org-angle-link-re)
10217 (org-in-regexp org-plain-link-re))
10218 ;; Convert to bracket link
10219 (setq remove (list (match-beginning 0) (match-end 0))
10220 link (read-string "Link: "
10221 (org-remove-angle-brackets (match-string 0)))))
10222 ((member complete-file '((4) (16)))
10223 ;; Completing read for file names.
10224 (setq link (org-file-complete-link complete-file)))
10226 ;; Read link, with completion for stored links.
10227 (org-link-fontify-links-to-this-file)
10228 (org-switch-to-buffer-other-window "*Org Links*")
10229 (with-current-buffer "*Org Links*"
10230 (erase-buffer)
10231 (insert "Insert a link.
10232 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10233 (when org-stored-links
10234 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10235 (insert (mapconcat 'org-link-prettify
10236 (reverse org-stored-links) "\n")))
10237 (goto-char (point-min)))
10238 (let ((cw (selected-window)))
10239 (select-window (get-buffer-window "*Org Links*" 'visible))
10240 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10241 (unless (pos-visible-in-window-p (point-max))
10242 (org-fit-window-to-buffer))
10243 (and (window-live-p cw) (select-window cw)))
10244 ;; Fake a link history, containing the stored links.
10245 (setq tmphist (append (mapcar 'car org-stored-links)
10246 org-insert-link-history))
10247 (setq all-prefixes (append (mapcar 'car abbrevs)
10248 (mapcar 'car org-link-abbrev-alist)
10249 org-link-types))
10250 (unwind-protect
10251 (progn
10252 (setq link
10253 (org-completing-read
10254 "Link: "
10255 (append
10256 (mapcar (lambda (x) (concat x ":"))
10257 all-prefixes)
10258 (mapcar 'car org-stored-links))
10259 nil nil nil
10260 'tmphist
10261 (caar org-stored-links)))
10262 (if (not (string-match "\\S-" link))
10263 (user-error "No link selected"))
10264 (mapc (lambda(l)
10265 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
10266 org-stored-links)
10267 (if (or (member link all-prefixes)
10268 (and (equal ":" (substring link -1))
10269 (member (substring link 0 -1) all-prefixes)
10270 (setq link (substring link 0 -1))))
10271 (setq link (with-current-buffer origbuf
10272 (org-link-try-special-completion link)))))
10273 (set-window-configuration wcf)
10274 (kill-buffer "*Org Links*"))
10275 (setq entry (assoc link org-stored-links))
10276 (or entry (push link org-insert-link-history))
10277 (setq desc (or desc (nth 1 entry)))))
10279 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10280 (not org-keep-stored-link-after-insertion))
10281 (setq org-stored-links (delq (assoc link org-stored-links)
10282 org-stored-links)))
10284 (if (and (string-match org-plain-link-re link)
10285 (not (string-match org-ts-regexp link)))
10286 ;; URL-like link, normalize the use of angular brackets.
10287 (setq link (org-remove-angle-brackets link)))
10289 ;; Check if we are linking to the current file with a search
10290 ;; option If yes, simplify the link by using only the search
10291 ;; option.
10292 (when (and buffer-file-name
10293 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10294 (let* ((path (match-string 1 link))
10295 (case-fold-search nil)
10296 (search (match-string 2 link)))
10297 (save-match-data
10298 (if (equal (file-truename buffer-file-name) (file-truename path))
10299 ;; We are linking to this same file, with a search option
10300 (setq link search)))))
10302 ;; Check if we can/should use a relative path. If yes, simplify the link
10303 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10304 (let* ((type (match-string 1 link))
10305 (path (match-string 2 link))
10306 (origpath path)
10307 (case-fold-search nil))
10308 (cond
10309 ((or (eq org-link-file-path-type 'absolute)
10310 (equal complete-file '(16)))
10311 (setq path (abbreviate-file-name (expand-file-name path))))
10312 ((eq org-link-file-path-type 'noabbrev)
10313 (setq path (expand-file-name path)))
10314 ((eq org-link-file-path-type 'relative)
10315 (setq path (file-relative-name path)))
10317 (save-match-data
10318 (if (string-match (concat "^" (regexp-quote
10319 (expand-file-name
10320 (file-name-as-directory
10321 default-directory))))
10322 (expand-file-name path))
10323 ;; We are linking a file with relative path name.
10324 (setq path (substring (expand-file-name path)
10325 (match-end 0)))
10326 (setq path (abbreviate-file-name (expand-file-name path)))))))
10327 (setq link (concat type path))
10328 (if (equal desc origpath)
10329 (setq desc path))))
10331 (if org-make-link-description-function
10332 (setq desc
10333 (or (condition-case nil
10334 (funcall org-make-link-description-function link desc)
10335 (error (progn (message "Can't get link description from `%s'"
10336 (symbol-name org-make-link-description-function))
10337 (sit-for 2) nil)))
10338 (read-string "Description: " default-description)))
10339 (if default-description (setq desc default-description)
10340 (setq desc (or (and auto-desc desc)
10341 (read-string "Description: " desc)))))
10343 (unless (string-match "\\S-" desc) (setq desc nil))
10344 (if remove (apply 'delete-region remove))
10345 (insert (org-make-link-string link desc))))
10347 (defun org-link-try-special-completion (type)
10348 "If there is completion support for link type TYPE, offer it."
10349 (let ((fun (intern (concat "org-" type "-complete-link"))))
10350 (if (functionp fun)
10351 (funcall fun)
10352 (read-string "Link (no completion support): " (concat type ":")))))
10354 (defun org-file-complete-link (&optional arg)
10355 "Create a file link using completion."
10356 (let (file link)
10357 (setq file (org-iread-file-name "File: "))
10358 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10359 (pwd1 (file-name-as-directory (abbreviate-file-name
10360 (expand-file-name ".")))))
10361 (cond
10362 ((equal arg '(16))
10363 (setq link (concat
10364 "file:"
10365 (abbreviate-file-name (expand-file-name file)))))
10366 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10367 (setq link (concat "file:" (match-string 1 file))))
10368 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10369 (expand-file-name file))
10370 (setq link (concat
10371 "file:" (match-string 1 (expand-file-name file)))))
10372 (t (setq link (concat "file:" file)))))
10373 link))
10375 (defun org-iread-file-name (&rest args)
10376 "Read-file-name using `ido-mode' speedup if available.
10377 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10378 See `read-file-name' for a description of parameters."
10379 (org-without-partial-completion
10380 (if (and org-completion-use-ido
10381 (fboundp 'ido-read-file-name)
10382 (boundp 'ido-mode) ido-mode
10383 (listp (second args)))
10384 (let ((ido-enter-matching-directory nil))
10385 (apply 'ido-read-file-name args))
10386 (apply 'read-file-name args))))
10388 (defun org-completing-read (&rest args)
10389 "Completing-read with SPACE being a normal character."
10390 (let ((enable-recursive-minibuffers t)
10391 (minibuffer-local-completion-map
10392 (copy-keymap minibuffer-local-completion-map)))
10393 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10394 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10395 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10396 (apply 'org-icompleting-read args)))
10398 (defun org-completing-read-no-i (&rest args)
10399 (let (org-completion-use-ido org-completion-use-iswitchb)
10400 (apply 'org-completing-read args)))
10402 (defun org-iswitchb-completing-read (prompt choices &rest args)
10403 "Use iswitch as a completing-read replacement to choose from choices.
10404 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10405 from."
10406 (let* ((iswitchb-use-virtual-buffers nil)
10407 (iswitchb-make-buflist-hook
10408 (lambda ()
10409 (setq iswitchb-temp-buflist choices))))
10410 (iswitchb-read-buffer prompt)))
10412 (defun org-icompleting-read (&rest args)
10413 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10414 (org-without-partial-completion
10415 (if (and org-completion-use-ido
10416 (fboundp 'ido-completing-read)
10417 (boundp 'ido-mode) ido-mode
10418 (listp (second args)))
10419 (let ((ido-enter-matching-directory nil))
10420 (apply 'ido-completing-read (concat (car args))
10421 (if (consp (car (nth 1 args)))
10422 (mapcar 'car (nth 1 args))
10423 (nth 1 args))
10424 (cddr args)))
10425 (if (and org-completion-use-iswitchb
10426 (boundp 'iswitchb-mode) iswitchb-mode
10427 (listp (second args)))
10428 (apply 'org-iswitchb-completing-read (concat (car args))
10429 (if (consp (car (nth 1 args)))
10430 (mapcar 'car (nth 1 args))
10431 (nth 1 args))
10432 (cddr args))
10433 (apply 'completing-read args)))))
10435 (defun org-extract-attributes (s)
10436 "Extract the attributes cookie from a string and set as text property."
10437 (let (a attr (start 0) key value)
10438 (save-match-data
10439 (when (string-match "{{\\([^}]+\\)}}$" s)
10440 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10441 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10442 (setq key (match-string 1 a) value (match-string 2 a)
10443 start (match-end 0)
10444 attr (plist-put attr (intern key) value))))
10445 (org-add-props s nil 'org-attr attr))
10448 ;;; Opening/following a link
10450 (defvar org-link-search-failed nil)
10452 (defvar org-open-link-functions nil
10453 "Hook for functions finding a plain text link.
10454 These functions must take a single argument, the link content.
10455 They will be called for links that look like [[link text][description]]
10456 when LINK TEXT does not have a protocol like \"http:\" and does not look
10457 like a filename (e.g. \"./blue.png\").
10459 These functions will be called *before* Org attempts to resolve the
10460 link by doing text searches in the current buffer - so if you want a
10461 link \"[[target]]\" to still find \"<<target>>\", your function should
10462 handle this as a special case.
10464 When the function does handle the link, it must return a non-nil value.
10465 If it decides that it is not responsible for this link, it must return
10466 nil to indicate that that Org-mode can continue with other options
10467 like exact and fuzzy text search.")
10469 (defun org-next-link (&optional search-backward)
10470 "Move forward to the next link.
10471 If the link is in hidden text, expose it."
10472 (interactive "P")
10473 (when (and org-link-search-failed (eq this-command last-command))
10474 (goto-char (point-min))
10475 (message "Link search wrapped back to beginning of buffer"))
10476 (setq org-link-search-failed nil)
10477 (let* ((pos (point))
10478 (ct (org-context))
10479 (a (assoc :link ct))
10480 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10481 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10482 ((looking-at org-any-link-re)
10483 ;; Don't stay stuck at link without an org-link face
10484 (forward-char (if search-backward -1 1))))
10485 (if (funcall srch-fun org-any-link-re nil t)
10486 (progn
10487 (goto-char (match-beginning 0))
10488 (if (outline-invisible-p) (org-show-context)))
10489 (goto-char pos)
10490 (setq org-link-search-failed t)
10491 (message "No further link found"))))
10493 (defun org-previous-link ()
10494 "Move backward to the previous link.
10495 If the link is in hidden text, expose it."
10496 (interactive)
10497 (funcall 'org-next-link t))
10499 (defun org-translate-link (s)
10500 "Translate a link string if a translation function has been defined."
10501 (if (and org-link-translation-function
10502 (fboundp org-link-translation-function)
10503 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10504 (progn
10505 (setq s (funcall org-link-translation-function
10506 (match-string 1 s) (match-string 2 s)))
10507 (concat (car s) ":" (cdr s)))
10510 (defun org-translate-link-from-planner (type path)
10511 "Translate a link from Emacs Planner syntax so that Org can follow it.
10512 This is still an experimental function, your mileage may vary."
10513 (cond
10514 ((member type '("http" "https" "news" "ftp"))
10515 ;; standard Internet links are the same.
10516 nil)
10517 ((and (equal type "irc") (string-match "^//" path))
10518 ;; Planner has two / at the beginning of an irc link, we have 1.
10519 ;; We should have zero, actually....
10520 (setq path (substring path 1)))
10521 ((and (equal type "lisp") (string-match "^/" path))
10522 ;; Planner has a slash, we do not.
10523 (setq type "elisp" path (substring path 1)))
10524 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10525 ;; A typical message link. Planner has the id after the final slash,
10526 ;; we separate it with a hash mark
10527 (setq path (concat (match-string 1 path) "#"
10528 (org-remove-angle-brackets (match-string 2 path))))))
10529 (cons type path))
10531 (defun org-find-file-at-mouse (ev)
10532 "Open file link or URL at mouse."
10533 (interactive "e")
10534 (mouse-set-point ev)
10535 (org-open-at-point 'in-emacs))
10537 (defun org-open-at-mouse (ev)
10538 "Open file link or URL at mouse.
10539 See the docstring of `org-open-file' for details."
10540 (interactive "e")
10541 (mouse-set-point ev)
10542 (if (eq major-mode 'org-agenda-mode)
10543 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10544 (org-open-at-point))
10546 (defvar org-window-config-before-follow-link nil
10547 "The window configuration before following a link.
10548 This is saved in case the need arises to restore it.")
10550 (defvar org-open-link-marker (make-marker)
10551 "Marker pointing to the location where `org-open-at-point' was called.")
10553 ;;;###autoload
10554 (defun org-open-at-point-global ()
10555 "Follow a link like Org-mode does.
10556 This command can be called in any mode to follow a link that has
10557 Org-mode syntax."
10558 (interactive)
10559 (org-run-like-in-org-mode 'org-open-at-point))
10561 ;;;###autoload
10562 (defun org-open-link-from-string (s &optional arg reference-buffer)
10563 "Open a link in the string S, as if it was in Org-mode."
10564 (interactive "sLink: \nP")
10565 (let ((reference-buffer (or reference-buffer (current-buffer))))
10566 (with-temp-buffer
10567 (let ((org-inhibit-startup (not reference-buffer)))
10568 (org-mode)
10569 (insert s)
10570 (goto-char (point-min))
10571 (when reference-buffer
10572 (setq org-link-abbrev-alist-local
10573 (with-current-buffer reference-buffer
10574 org-link-abbrev-alist-local)))
10575 (org-open-at-point arg reference-buffer)))))
10577 (defvar org-open-at-point-functions nil
10578 "Hook that is run when following a link at point.
10580 Functions in this hook must return t if they identify and follow
10581 a link at point. If they don't find anything interesting at point,
10582 they must return nil.")
10584 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10585 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10586 (defun org-open-at-point (&optional arg reference-buffer)
10587 "Open link, timestamp, footnote or tags at point.
10589 When point is on a link, follow it. Normally, files will be
10590 opened by an appropriate application. If the optional prefix
10591 argument ARG is non-nil, Emacs will visit the file. With
10592 a double prefix argument, try to open outside of Emacs, in the
10593 application the system uses for this file type.
10595 When point is on a timestamp, open the agenda at the day
10596 specified.
10598 When point is a footnote definition, move to the first reference
10599 found. If it is on a reference, move to the associated
10600 definition.
10602 When point is on a headline, display a list of every link in the
10603 entry, so it is possible to pick one, or all, of them. If point
10604 is on a tag, call `org-tags-view' instead.
10606 When optional argument REFERENCE-BUFFER is non-nil, it should
10607 specify a buffer from where the link search should happen. This
10608 is used internally by `org-open-link-from-string'.
10610 On top of syntactically correct links, this function will open
10611 the link at point in comments and the first link in a property
10612 drawer line."
10613 (interactive "P")
10614 ;; On a code block, open block's results.
10615 (unless (call-interactively 'org-babel-open-src-block-result)
10616 (org-load-modules-maybe)
10617 (move-marker org-open-link-marker (point))
10618 (setq org-window-config-before-follow-link (current-window-configuration))
10619 (org-remove-occur-highlights nil nil t)
10620 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10621 (let* ((context (org-element-context)) type value)
10622 ;; On an unsupported type, check if point is contained within
10623 ;; a support one.
10624 (while (and (not (memq (setq type (org-element-type context))
10625 '(comment headline inlinetask link
10626 footnote-definition footnote-reference
10627 node-property timestamp)))
10628 (setq context (org-element-property :parent context))))
10629 (setq value (org-element-property :value context))
10630 (cond
10631 ;; Blank lines at the beginning of buffer: bail out.
10632 ((not context) (user-error "No link found"))
10633 ;; Exception n°1: links in property drawers
10634 ((eq type 'node-property)
10635 (org-open-link-from-string
10636 (and (string-match org-any-link-re value)
10637 (match-string-no-properties 0 value))))
10638 ;; Exception n°2: links in comments.
10639 ((eq type 'comment)
10640 (let ((string-rear (replace-regexp-in-string
10641 "^[ \t]*# [ \t]*" ""
10642 (buffer-substring (point) (line-beginning-position))))
10643 (string-front (buffer-substring (point) (line-end-position))))
10644 (with-temp-buffer
10645 (let ((org-inhibit-startup t)) (org-mode))
10646 (insert value)
10647 (goto-char (point-min))
10648 (when (and (search-forward string-rear nil t)
10649 (search-forward string-front (line-end-position) t))
10650 (goto-char (match-beginning 0))
10651 (org-open-at-point)
10652 (when (string= string-rear "") (forward-char))))))
10653 ;; On a headline or an inlinetask, but not on a timestamp,
10654 ;; a link, a footnote reference or on tags.
10655 ((and (memq type '(headline inlinetask))
10656 ;; Not on tags.
10657 (progn (save-excursion (beginning-of-line)
10658 (looking-at org-complex-heading-regexp))
10659 (or (not (match-beginning 5))
10660 (< (point) (match-beginning 5)))))
10661 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10662 (links (car data))
10663 (links-end (cdr data)))
10664 (if links
10665 (dolist (link (if (stringp links) (list links) links))
10666 (search-forward link nil links-end)
10667 (goto-char (match-beginning 0))
10668 (org-open-at-point))
10669 (require 'org-attach)
10670 (org-attach-reveal 'if-exists))))
10671 ;; Do nothing on white spaces after an object, unless point
10672 ;; is right after it.
10673 ((> (point)
10674 (save-excursion
10675 (goto-char (org-element-property :end context))
10676 (skip-chars-backward " \t")
10677 (point)))
10678 (user-error "No link found"))
10679 ((eq type 'timestamp) (org-follow-timestamp-link))
10680 ;; On tags within a headline or an inlinetask.
10681 ((and (memq type '(headline inlinetask))
10682 (progn (save-excursion (beginning-of-line)
10683 (looking-at org-complex-heading-regexp))
10684 (and (match-beginning 5)
10685 (>= (point) (match-beginning 5)))))
10686 (org-tags-view arg (substring (match-string 5) 0 -1)))
10687 ((eq type 'link)
10688 (let ((type (org-element-property :type context))
10689 (path (org-link-unescape (org-element-property :path context))))
10690 ;; Switch back to REFERENCE-BUFFER needed when called in
10691 ;; a temporary buffer through `org-open-link-from-string'.
10692 (with-current-buffer (or reference-buffer (current-buffer))
10693 (cond
10694 ((equal type "file")
10695 (if (string-match "[*?{]" (file-name-nondirectory path))
10696 (dired path)
10697 ;; Look into `org-link-protocols' in order to find
10698 ;; a DEDICATED-FUNCTION to open file. The function
10699 ;; will be applied on raw link instead of parsed
10700 ;; link due to the limitation in `org-add-link-type'
10701 ;; ("open" function called with a single argument).
10702 ;; If no such function is found, fallback to
10703 ;; `org-open-file'.
10705 ;; Note : "file+emacs" and "file+sys" types are
10706 ;; hard-coded in order to escape the previous
10707 ;; limitation.
10708 (let* ((option (org-element-property :search-option context))
10709 (app (org-element-property :application context))
10710 (dedicated-function
10711 (nth 1 (assoc app org-link-protocols))))
10712 (if dedicated-function
10713 (funcall dedicated-function
10714 (concat path
10715 (and option (concat "::" option))))
10716 (apply 'org-open-file
10717 path
10718 (cond (arg)
10719 ((equal app "emacs") 'emacs)
10720 ((equal app "sys") 'system))
10721 (cond ((not option) nil)
10722 ((org-string-match-p "\\`[0-9]+\\'" option)
10723 (list (string-to-number option)))
10724 (t (list nil
10725 (org-link-unescape option)))))))))
10726 ((assoc type org-link-protocols)
10727 (funcall (nth 1 (assoc type org-link-protocols)) path))
10728 ((equal type "help")
10729 (let ((f-or-v (intern path)))
10730 (cond ((fboundp f-or-v) (describe-function f-or-v))
10731 ((boundp f-or-v) (describe-variable f-or-v))
10732 (t (error "Not a known function or variable")))))
10733 ((member type '("http" "https" "ftp" "mailto" "news"))
10734 (browse-url (org-link-escape-browser (concat type ":" path))))
10735 ((equal type "doi")
10736 (browse-url
10737 (org-link-escape-browser (concat org-doi-server-url path))))
10738 ((equal type "message") (browse-url (concat type ":" path)))
10739 ((equal type "shell")
10740 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10741 (cmd path))
10742 (if (or (and (org-string-nw-p
10743 org-confirm-shell-link-not-regexp)
10744 (string-match
10745 org-confirm-shell-link-not-regexp cmd))
10746 (not org-confirm-shell-link-function)
10747 (funcall org-confirm-shell-link-function
10748 (format "Execute \"%s\" in shell? "
10749 (org-add-props cmd nil
10750 'face 'org-warning))))
10751 (progn
10752 (message "Executing %s" cmd)
10753 (shell-command cmd buf)
10754 (when (featurep 'midnight)
10755 (setq clean-buffer-list-kill-buffer-names
10756 (cons buf
10757 clean-buffer-list-kill-buffer-names))))
10758 (user-error "Abort"))))
10759 ((equal type "elisp")
10760 (let ((cmd path))
10761 (if (or (and (org-string-nw-p
10762 org-confirm-elisp-link-not-regexp)
10763 (org-string-match-p
10764 org-confirm-elisp-link-not-regexp cmd))
10765 (not org-confirm-elisp-link-function)
10766 (funcall org-confirm-elisp-link-function
10767 (format "Execute \"%s\" as elisp? "
10768 (org-add-props cmd nil
10769 'face 'org-warning))))
10770 (message "%s => %s" cmd
10771 (if (eq (string-to-char cmd) ?\()
10772 (eval (read cmd))
10773 (call-interactively (read cmd))))
10774 (user-error "Abort"))))
10775 ((equal type "id")
10776 (require 'ord-id)
10777 (funcall (nth 1 (assoc "id" org-link-protocols)) path))
10778 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10779 (unless (run-hook-with-args-until-success
10780 'org-open-link-functions path)
10781 (if (not arg) (org-mark-ring-push)
10782 (switch-to-buffer-other-window
10783 (org-get-buffer-for-internal-link (current-buffer))))
10784 (let ((cmd `(org-link-search
10785 ,(if (member type '("custom-id" "coderef"))
10786 (org-element-property :raw-link context)
10787 path)
10788 ,(cond ((equal arg '(4)) 'occur)
10789 ((equal arg '(16)) 'org-occur))
10790 ,(org-element-property :begin context))))
10791 (condition-case nil
10792 (let ((org-link-search-inhibit-query t))
10793 (eval cmd))
10794 (error (progn (widen) (eval cmd)))))))
10795 (t (browse-url-at-point))))))
10796 ;; On a footnote reference or at a footnote definition's label.
10797 ((or (eq type 'footnote-reference)
10798 (and (eq type 'footnote-definition)
10799 (save-excursion
10800 ;; Do not validate action when point is on the
10801 ;; spaces right after the footnote label, in
10802 ;; order to be on par with behaviour on links.
10803 (skip-chars-forward " \t")
10804 (let ((begin
10805 (org-element-property :contents-begin context)))
10806 (if begin (< (point) begin)
10807 (= (org-element-property :post-affiliated context)
10808 (line-beginning-position)))))))
10809 (org-footnote-action))
10810 (t (user-error "No link found")))))
10811 (move-marker org-open-link-marker nil)
10812 (run-hook-with-args 'org-follow-link-hook)))
10814 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10815 "Offer links in the current entry and return the selected link.
10816 If there is only one link, return it.
10817 If NTH is an integer, return the NTH link found.
10818 If ZERO is a string, check also this string for a link, and if
10819 there is one, return it."
10820 (with-current-buffer buffer
10821 (save-excursion
10822 (save-restriction
10823 (widen)
10824 (goto-char marker)
10825 (let ((cnt ?0)
10826 (in-emacs (if (integerp nth) nil nth))
10827 have-zero end links link c)
10828 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10829 (push (match-string 0 zero) links)
10830 (setq cnt (1- cnt) have-zero t))
10831 (save-excursion
10832 (org-back-to-heading t)
10833 (setq end (save-excursion (outline-next-heading) (point)))
10834 (while (re-search-forward org-any-link-re end t)
10835 (push (match-string 0) links))
10836 (setq links (org-uniquify (reverse links))))
10837 (cond
10838 ((null links)
10839 (message "No links"))
10840 ((equal (length links) 1)
10841 (setq link (car links)))
10842 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10843 (setq link (nth (if have-zero nth (1- nth)) links)))
10844 (t ; we have to select a link
10845 (save-excursion
10846 (save-window-excursion
10847 (delete-other-windows)
10848 (with-output-to-temp-buffer "*Select Link*"
10849 (mapc (lambda (l)
10850 (if (not (string-match org-bracket-link-regexp l))
10851 (princ (format "[%c] %s\n" (incf cnt)
10852 (org-remove-angle-brackets l)))
10853 (if (match-end 3)
10854 (princ (format "[%c] %s (%s)\n" (incf cnt)
10855 (match-string 3 l) (match-string 1 l)))
10856 (princ (format "[%c] %s\n" (incf cnt)
10857 (match-string 1 l))))))
10858 links))
10859 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10860 (message "Select link to open, RET to open all:")
10861 (setq c (read-char-exclusive))
10862 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10863 (when (equal c ?q) (user-error "Abort"))
10864 (if (equal c ?\C-m)
10865 (setq link links)
10866 (setq nth (- c ?0))
10867 (if have-zero (setq nth (1+ nth)))
10868 (unless (and (integerp nth) (>= (length links) nth))
10869 (user-error "Invalid link selection"))
10870 (setq link (nth (1- nth) links)))))
10871 (cons link end))))))
10873 ;; TODO: These functions are deprecated since `org-open-at-point'
10874 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10875 (defun org-open-file-with-system (path)
10876 "Open file at PATH using the system way of opening it."
10877 (org-open-file path 'system))
10878 (defun org-open-file-with-emacs (path)
10879 "Open file at PATH in Emacs."
10880 (org-open-file path 'emacs))
10883 ;;; File search
10885 (defvar org-create-file-search-functions nil
10886 "List of functions to construct the right search string for a file link.
10887 These functions are called in turn with point at the location to
10888 which the link should point.
10890 A function in the hook should first test if it would like to
10891 handle this file type, for example by checking the `major-mode'
10892 or the file extension. If it decides not to handle this file, it
10893 should just return nil to give other functions a chance. If it
10894 does handle the file, it must return the search string to be used
10895 when following the link. The search string will be part of the
10896 file link, given after a double colon, and `org-open-at-point'
10897 will automatically search for it. If special measures must be
10898 taken to make the search successful, another function should be
10899 added to the companion hook `org-execute-file-search-functions',
10900 which see.
10902 A function in this hook may also use `setq' to set the variable
10903 `description' to provide a suggestion for the descriptive text to
10904 be used for this link when it gets inserted into an Org-mode
10905 buffer with \\[org-insert-link].")
10907 (defvar org-execute-file-search-functions nil
10908 "List of functions to execute a file search triggered by a link.
10910 Functions added to this hook must accept a single argument, the
10911 search string that was part of the file link, the part after the
10912 double colon. The function must first check if it would like to
10913 handle this search, for example by checking the `major-mode' or
10914 the file extension. If it decides not to handle this search, it
10915 should just return nil to give other functions a chance. If it
10916 does handle the search, it must return a non-nil value to keep
10917 other functions from trying.
10919 Each function can access the current prefix argument through the
10920 variable `current-prefix-arg'. Note that a single prefix is used
10921 to force opening a link in Emacs, so it may be good to only use a
10922 numeric or double prefix to guide the search function.
10924 In case this is needed, a function in this hook can also restore
10925 the window configuration before `org-open-at-point' was called using:
10927 (set-window-configuration org-window-config-before-follow-link)")
10929 (defun org-link-search (s &optional type avoid-pos stealth)
10930 "Search for a link search option.
10931 If S is surrounded by forward slashes, it is interpreted as a
10932 regular expression. In org-mode files, this will create an `org-occur'
10933 sparse tree. In ordinary files, `occur' will be used to list matches.
10934 If the current buffer is in `dired-mode', grep will be used to search
10935 in all files. If AVOID-POS is given, ignore matches near that position.
10937 When optional argument STEALTH is non-nil, do not modify
10938 visibility around point, thus ignoring
10939 `org-show-hierarchy-above', `org-show-following-heading' and
10940 `org-show-siblings' variables."
10941 (let ((case-fold-search t)
10942 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10943 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10944 (append '(("") (" ") ("\t") ("\n"))
10945 org-emphasis-alist)
10946 "\\|") "\\)"))
10947 (pos (point))
10948 (pre nil) (post nil)
10949 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10950 (cond
10951 ;; First check if there are any special search functions
10952 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10953 ;; Now try the builtin stuff
10954 ((and (equal (string-to-char s0) ?#)
10955 (> (length s0) 1)
10956 (save-excursion
10957 (goto-char (point-min))
10958 (and
10959 (re-search-forward
10960 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10961 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10962 (setq type 'dedicated
10963 pos (match-beginning 0))))
10964 ;; There is an exact target for this
10965 (goto-char pos)
10966 (org-back-to-heading t)))
10967 ((save-excursion
10968 (goto-char (point-min))
10969 (and
10970 (re-search-forward
10971 (concat "<<" (regexp-quote s0) ">>") nil t)
10972 (setq type 'dedicated
10973 pos (match-beginning 0))))
10974 ;; There is an exact target for this
10975 (goto-char pos))
10976 ((save-excursion
10977 (goto-char (point-min))
10978 (and
10979 (re-search-forward
10980 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10981 (setq type 'dedicated pos (match-beginning 0))))
10982 ;; Found an element with a matching #+name affiliated keyword.
10983 (goto-char pos))
10984 ((and (string-match "^(\\(.*\\))$" s0)
10985 (save-excursion
10986 (goto-char (point-min))
10987 (and
10988 (re-search-forward
10989 (concat "[^[]" (regexp-quote
10990 (format org-coderef-label-format
10991 (match-string 1 s0))))
10992 nil t)
10993 (setq type 'dedicated
10994 pos (1+ (match-beginning 0))))))
10995 ;; There is a coderef target for this
10996 (goto-char pos))
10997 ((string-match "^/\\(.*\\)/$" s)
10998 ;; A regular expression
10999 (cond
11000 ((derived-mode-p 'org-mode)
11001 (org-occur (match-string 1 s)))
11002 (t (org-do-occur (match-string 1 s)))))
11003 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
11004 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
11005 (goto-char (point-min))
11006 (cond
11007 ((let (case-fold-search)
11008 (re-search-forward (format org-complex-heading-regexp-format
11009 (regexp-quote s))
11010 nil t))
11011 ;; OK, found a match
11012 (setq type 'dedicated)
11013 (goto-char (match-beginning 0)))
11014 ((and (not org-link-search-inhibit-query)
11015 (eq org-link-search-must-match-exact-headline 'query-to-create)
11016 (y-or-n-p "No match - create this as a new heading? "))
11017 (goto-char (point-max))
11018 (or (bolp) (newline))
11019 (insert "* " s "\n")
11020 (beginning-of-line 0))
11022 (goto-char pos)
11023 (error "No match"))))
11025 ;; A normal search string
11026 (when (equal (string-to-char s) ?*)
11027 ;; Anchor on headlines, post may include tags.
11028 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
11029 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
11030 s (substring s 1)))
11031 (remove-text-properties
11032 0 (length s)
11033 '(face nil mouse-face nil keymap nil fontified nil) s)
11034 ;; Make a series of regular expressions to find a match
11035 (setq words (org-split-string s "[ \n\r\t]+")
11037 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
11038 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
11039 "\\)" markers)
11040 re2a_ (concat "\\(" (mapconcat 'downcase words
11041 "[ \t\r\n]+") "\\)[ \t\r\n]")
11042 re2a (concat "[ \t\r\n]" re2a_)
11043 re4_ (concat "\\(" (mapconcat 'downcase words
11044 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
11045 re4 (concat "[^a-zA-Z_]" re4_)
11047 re1 (concat pre re2 post)
11048 re3 (concat pre (if pre re4_ re4) post)
11049 re5 (concat pre ".*" re4)
11050 re2 (concat pre re2)
11051 re2a (concat pre (if pre re2a_ re2a))
11052 re4 (concat pre (if pre re4_ re4))
11053 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
11054 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
11055 re5 "\\)"))
11056 (cond
11057 ((eq type 'org-occur) (org-occur reall))
11058 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
11059 (t (goto-char (point-min))
11060 (setq type 'fuzzy)
11061 (if (or (and (org-search-not-self 1 re0 nil t)
11062 (setq type 'dedicated))
11063 (org-search-not-self 1 re1 nil t)
11064 (org-search-not-self 1 re2 nil t)
11065 (org-search-not-self 1 re2a nil t)
11066 (org-search-not-self 1 re3 nil t)
11067 (org-search-not-self 1 re4 nil t)
11068 (org-search-not-self 1 re5 nil t))
11069 (goto-char (match-beginning 1))
11070 (goto-char pos)
11071 (error "No match"))))))
11072 (and (derived-mode-p 'org-mode)
11073 (not stealth)
11074 (org-show-context 'link-search))
11075 type))
11077 (defun org-search-not-self (group &rest args)
11078 "Execute `re-search-forward', but only accept matches that do not
11079 enclose the position of `org-open-link-marker'."
11080 (let ((m org-open-link-marker))
11081 (catch 'exit
11082 (while (apply 're-search-forward args)
11083 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
11084 (goto-char (match-end group))
11085 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
11086 (> (match-beginning 0) (marker-position m))
11087 (< (match-end 0) (marker-position m)))
11088 (save-match-data
11089 (or (not (org-in-regexp
11090 org-bracket-link-analytic-regexp 1))
11091 (not (match-end 4)) ; no description
11092 (and (<= (match-beginning 4) (point))
11093 (>= (match-end 4) (point))))))
11094 (throw 'exit (point))))))))
11096 (defun org-get-buffer-for-internal-link (buffer)
11097 "Return a buffer to be used for displaying the link target of internal links."
11098 (cond
11099 ((not org-display-internal-link-with-indirect-buffer)
11100 buffer)
11101 ((string-match "(Clone)$" (buffer-name buffer))
11102 (message "Buffer is already a clone, not making another one")
11103 ;; we also do not modify visibility in this case
11104 buffer)
11105 (t ; make a new indirect buffer for displaying the link
11106 (let* ((bn (buffer-name buffer))
11107 (ibn (concat bn "(Clone)"))
11108 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11109 (with-current-buffer ib (org-overview))
11110 ib))))
11112 (defun org-do-occur (regexp &optional cleanup)
11113 "Call the Emacs command `occur'.
11114 If CLEANUP is non-nil, remove the printout of the regular expression
11115 in the *Occur* buffer. This is useful if the regex is long and not useful
11116 to read."
11117 (occur regexp)
11118 (when cleanup
11119 (let ((cwin (selected-window)) win beg end)
11120 (when (setq win (get-buffer-window "*Occur*"))
11121 (select-window win))
11122 (goto-char (point-min))
11123 (when (re-search-forward "match[a-z]+" nil t)
11124 (setq beg (match-end 0))
11125 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
11126 (setq end (1- (match-beginning 0)))))
11127 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11128 (goto-char (point-min))
11129 (select-window cwin))))
11131 ;;; The mark ring for links jumps
11133 (defvar org-mark-ring nil
11134 "Mark ring for positions before jumps in Org-mode.")
11135 (defvar org-mark-ring-last-goto nil
11136 "Last position in the mark ring used to go back.")
11137 ;; Fill and close the ring
11138 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11139 (loop for i from 1 to org-mark-ring-length do
11140 (push (make-marker) org-mark-ring))
11141 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11142 org-mark-ring)
11144 (defun org-mark-ring-push (&optional pos buffer)
11145 "Put the current position or POS into the mark ring and rotate it."
11146 (interactive)
11147 (setq pos (or pos (point)))
11148 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11149 (move-marker (car org-mark-ring)
11150 (or pos (point))
11151 (or buffer (current-buffer)))
11152 (message "%s"
11153 (substitute-command-keys
11154 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
11156 (defun org-mark-ring-goto (&optional n)
11157 "Jump to the previous position in the mark ring.
11158 With prefix arg N, jump back that many stored positions. When
11159 called several times in succession, walk through the entire ring.
11160 Org-mode commands jumping to a different position in the current file,
11161 or to another Org-mode file, automatically push the old position
11162 onto the ring."
11163 (interactive "p")
11164 (let (p m)
11165 (if (eq last-command this-command)
11166 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11167 (setq p org-mark-ring))
11168 (setq org-mark-ring-last-goto p)
11169 (setq m (car p))
11170 (org-pop-to-buffer-same-window (marker-buffer m))
11171 (goto-char m)
11172 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11174 (defun org-remove-angle-brackets (s)
11175 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
11176 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
11178 (defun org-add-angle-brackets (s)
11179 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
11180 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
11182 (defun org-remove-double-quotes (s)
11183 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
11184 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
11187 ;;; Following specific links
11189 (defun org-follow-timestamp-link ()
11190 "Open an agenda view for the time-stamp date/range at point."
11191 (cond
11192 ((org-at-date-range-p t)
11193 (let ((org-agenda-start-on-weekday)
11194 (t1 (match-string 1))
11195 (t2 (match-string 2)) tt1 tt2)
11196 (setq tt1 (time-to-days (org-time-string-to-time t1))
11197 tt2 (time-to-days (org-time-string-to-time t2)))
11198 (let ((org-agenda-buffer-tmp-name
11199 (format "*Org Agenda(a:%s)"
11200 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11201 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11202 ((org-at-timestamp-p t)
11203 (let ((org-agenda-buffer-tmp-name
11204 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11205 (org-agenda-list nil (time-to-days (org-time-string-to-time
11206 (substring (match-string 1) 0 10)))
11207 1)))
11208 (t (error "This should not happen"))))
11211 ;;; Following file links
11212 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11213 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11214 (declare-function mailcap-mime-info
11215 "mailcap" (string &optional request no-decode))
11216 (defvar org-wait nil)
11217 (defun org-open-file (path &optional in-emacs line search)
11218 "Open the file at PATH.
11219 First, this expands any special file name abbreviations. Then the
11220 configuration variable `org-file-apps' is checked if it contains an
11221 entry for this file type, and if yes, the corresponding command is launched.
11223 If no application is found, Emacs simply visits the file.
11225 With optional prefix argument IN-EMACS, Emacs will visit the file.
11226 With a double \\[universal-argument] \\[universal-argument] \
11227 prefix arg, Org tries to avoid opening in Emacs
11228 and to use an external application to visit the file.
11230 Optional LINE specifies a line to go to, optional SEARCH a string
11231 to search for. If LINE or SEARCH is given, the file will be
11232 opened in Emacs, unless an entry from org-file-apps that makes
11233 use of groups in a regexp matches.
11235 If you want to change the way frames are used when following a
11236 link, please customize `org-link-frame-setup'.
11238 If the file does not exist, an error is thrown."
11239 (let* ((file (if (equal path "")
11240 buffer-file-name
11241 (substitute-in-file-name (expand-file-name path))))
11242 (file-apps (append org-file-apps (org-default-apps)))
11243 (apps (org-remove-if
11244 'org-file-apps-entry-match-against-dlink-p file-apps))
11245 (apps-dlink (org-remove-if-not
11246 'org-file-apps-entry-match-against-dlink-p file-apps))
11247 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11248 (dirp (if remp nil (file-directory-p file)))
11249 (file (if (and dirp org-open-directory-means-index-dot-org)
11250 (concat (file-name-as-directory file) "index.org")
11251 file))
11252 (a-m-a-p (assq 'auto-mode apps))
11253 (dfile (downcase file))
11254 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
11255 (link (cond ((and (eq line nil)
11256 (eq search nil))
11257 file)
11258 (line
11259 (concat file "::" (number-to-string line)))
11260 (search
11261 (concat file "::" search))))
11262 (dlink (downcase link))
11263 (old-buffer (current-buffer))
11264 (old-pos (point))
11265 (old-mode major-mode)
11266 ext cmd link-match-data)
11267 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11268 (setq ext (match-string 1 dfile))
11269 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11270 (setq ext (match-string 1 dfile))))
11271 (cond
11272 ((member in-emacs '((16) system))
11273 (setq cmd (cdr (assoc 'system apps))))
11274 (in-emacs (setq cmd 'emacs))
11276 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11277 (and dirp (cdr (assoc 'directory apps)))
11278 ; first, try matching against apps-dlink
11279 ; if we get a match here, store the match data for later
11280 (let ((match (assoc-default dlink apps-dlink
11281 'string-match)))
11282 (if match
11283 (progn (setq link-match-data (match-data))
11284 match)
11285 (progn (setq in-emacs (or in-emacs line search))
11286 nil))) ; if we have no match in apps-dlink,
11287 ; always open the file in emacs if line or search
11288 ; is given (for backwards compatibility)
11289 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11290 'string-match)
11291 (cdr (assoc ext apps))
11292 (cdr (assoc t apps))))))
11293 (when (eq cmd 'system)
11294 (setq cmd (cdr (assoc 'system apps))))
11295 (when (eq cmd 'default)
11296 (setq cmd (cdr (assoc t apps))))
11297 (when (eq cmd 'mailcap)
11298 (require 'mailcap)
11299 (mailcap-parse-mailcaps)
11300 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11301 (command (mailcap-mime-info mime-type)))
11302 (if (stringp command)
11303 (setq cmd command)
11304 (setq cmd 'emacs))))
11305 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11306 (not (file-exists-p file))
11307 (not org-open-non-existing-files))
11308 (user-error "No such file: %s" file))
11309 (cond
11310 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11311 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11312 (while (string-match "['\"]%s['\"]" cmd)
11313 (setq cmd (replace-match "%s" t t cmd)))
11314 (while (string-match "%s" cmd)
11315 (setq cmd (replace-match
11316 (save-match-data
11317 (shell-quote-argument
11318 (convert-standard-filename file)))
11319 t t cmd)))
11321 ;; Replace "%1", "%2" etc. in command with group matches from regex
11322 (save-match-data
11323 (let ((match-index 1)
11324 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11325 (set-match-data link-match-data)
11326 (while (<= match-index number-of-groups)
11327 (let ((regex (concat "%" (number-to-string match-index)))
11328 (replace-with (match-string match-index dlink)))
11329 (while (string-match regex cmd)
11330 (setq cmd (replace-match replace-with t t cmd))))
11331 (setq match-index (+ match-index 1)))))
11333 (save-window-excursion
11334 (message "Running %s...done" cmd)
11335 (start-process-shell-command cmd nil cmd)
11336 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11337 ((or (stringp cmd)
11338 (eq cmd 'emacs))
11339 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11340 (widen)
11341 (if line (progn (org-goto-line line)
11342 (if (derived-mode-p 'org-mode)
11343 (org-reveal)))
11344 (if search (org-link-search search))))
11345 ((consp cmd)
11346 (let ((file (convert-standard-filename file)))
11347 (save-match-data
11348 (set-match-data link-match-data)
11349 (eval cmd))))
11350 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11351 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11352 (or (not (equal old-buffer (current-buffer)))
11353 (not (equal old-pos (point))))
11354 (org-mark-ring-push old-pos old-buffer))))
11356 (defun org-file-apps-entry-match-against-dlink-p (entry)
11357 "This function returns non-nil if `entry' uses a regular
11358 expression which should be matched against the whole link by
11359 org-open-file.
11361 It assumes that is the case when the entry uses a regular
11362 expression which has at least one grouping construct and the
11363 action is either a lisp form or a command string containing
11364 '%1', i.e. using at least one subexpression match as a
11365 parameter."
11366 (let ((selector (car entry))
11367 (action (cdr entry)))
11368 (if (stringp selector)
11369 (and (> (regexp-opt-depth selector) 0)
11370 (or (and (stringp action)
11371 (string-match "%[0-9]" action))
11372 (consp action)))
11373 nil)))
11375 (defun org-default-apps ()
11376 "Return the default applications for this operating system."
11377 (cond
11378 ((eq system-type 'darwin)
11379 org-file-apps-defaults-macosx)
11380 ((eq system-type 'windows-nt)
11381 org-file-apps-defaults-windowsnt)
11382 (t org-file-apps-defaults-gnu)))
11384 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11385 "Convert extensions to regular expressions in the cars of LIST.
11386 Also, weed out any non-string entries, because the return value is used
11387 only for regexp matching.
11388 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11389 point to the symbol `emacs', indicating that the file should
11390 be opened in Emacs."
11391 (append
11392 (delq nil
11393 (mapcar (lambda (x)
11394 (if (not (stringp (car x)))
11396 (if (string-match "\\W" (car x))
11398 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11399 list))
11400 (if add-auto-mode
11401 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11403 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11404 (defun org-file-remote-p (file)
11405 "Test whether FILE specifies a location on a remote system.
11406 Return non-nil if the location is indeed remote.
11408 For example, the filename \"/user@host:/foo\" specifies a location
11409 on the system \"/user@host:\"."
11410 (cond ((fboundp 'file-remote-p)
11411 (file-remote-p file))
11412 ((fboundp 'tramp-handle-file-remote-p)
11413 (tramp-handle-file-remote-p file))
11414 ((and (boundp 'ange-ftp-name-format)
11415 (string-match (car ange-ftp-name-format) file))
11416 t)))
11419 ;;;; Refiling
11421 (defun org-get-org-file ()
11422 "Read a filename, with default directory `org-directory'."
11423 (let ((default (or org-default-notes-file remember-data-file)))
11424 (read-file-name (format "File name [%s]: " default)
11425 (file-name-as-directory org-directory)
11426 default)))
11428 (defun org-notes-order-reversed-p ()
11429 "Check if the current file should receive notes in reversed order."
11430 (cond
11431 ((not org-reverse-note-order) nil)
11432 ((eq t org-reverse-note-order) t)
11433 ((not (listp org-reverse-note-order)) nil)
11434 (t (catch 'exit
11435 (let ((all org-reverse-note-order)
11436 entry)
11437 (while (setq entry (pop all))
11438 (if (string-match (car entry) buffer-file-name)
11439 (throw 'exit (cdr entry))))
11440 nil)))))
11442 (defvar org-refile-target-table nil
11443 "The list of refile targets, created by `org-refile'.")
11445 (defvar org-agenda-new-buffers nil
11446 "Buffers created to visit agenda files.")
11448 (defvar org-refile-cache nil
11449 "Cache for refile targets.")
11451 (defvar org-refile-markers nil
11452 "All the markers used for caching refile locations.")
11454 (defun org-refile-marker (pos)
11455 "Get a new refile marker, but only if caching is in use."
11456 (if (not org-refile-use-cache)
11458 (let ((m (make-marker)))
11459 (move-marker m pos)
11460 (push m org-refile-markers)
11461 m)))
11463 (defun org-refile-cache-clear ()
11464 "Clear the refile cache and disable all the markers."
11465 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11466 (setq org-refile-markers nil)
11467 (setq org-refile-cache nil)
11468 (message "Refile cache has been cleared"))
11470 (defun org-refile-cache-check-set (set)
11471 "Check if all the markers in the cache still have live buffers."
11472 (let (marker)
11473 (catch 'exit
11474 (while (and set (setq marker (nth 3 (pop set))))
11475 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11476 (when (and marker (null (marker-buffer marker)))
11477 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11478 (sit-for 3)
11479 (throw 'exit nil)))
11480 t)))
11482 (defun org-refile-cache-put (set &rest identifiers)
11483 "Push the refile targets SET into the cache, under IDENTIFIERS."
11484 (let* ((key (sha1 (prin1-to-string identifiers)))
11485 (entry (assoc key org-refile-cache)))
11486 (if entry
11487 (setcdr entry set)
11488 (push (cons key set) org-refile-cache))))
11490 (defun org-refile-cache-get (&rest identifiers)
11491 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11492 (cond
11493 ((not org-refile-cache) nil)
11494 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11496 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11497 org-refile-cache))))
11498 (and set (org-refile-cache-check-set set) set)))))
11500 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11501 "Produce a table with refile targets."
11502 (let ((case-fold-search nil)
11503 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11504 (entries (or org-refile-targets '((nil . (:level . 1)))))
11505 targets tgs txt re files f desc descre fast-path-p level pos0)
11506 (message "Getting targets...")
11507 (with-current-buffer (or default-buffer (current-buffer))
11508 (while (setq entry (pop entries))
11509 (setq files (car entry) desc (cdr entry))
11510 (setq fast-path-p nil)
11511 (cond
11512 ((null files) (setq files (list (current-buffer))))
11513 ((eq files 'org-agenda-files)
11514 (setq files (org-agenda-files 'unrestricted)))
11515 ((and (symbolp files) (fboundp files))
11516 (setq files (funcall files)))
11517 ((and (symbolp files) (boundp files))
11518 (setq files (symbol-value files))))
11519 (if (stringp files) (setq files (list files)))
11520 (cond
11521 ((eq (car desc) :tag)
11522 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11523 ((eq (car desc) :todo)
11524 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11525 ((eq (car desc) :regexp)
11526 (setq descre (cdr desc)))
11527 ((eq (car desc) :level)
11528 (setq descre (concat "^\\*\\{" (number-to-string
11529 (if org-odd-levels-only
11530 (1- (* 2 (cdr desc)))
11531 (cdr desc)))
11532 "\\}[ \t]")))
11533 ((eq (car desc) :maxlevel)
11534 (setq fast-path-p t)
11535 (setq descre (concat "^\\*\\{1," (number-to-string
11536 (if org-odd-levels-only
11537 (1- (* 2 (cdr desc)))
11538 (cdr desc)))
11539 "\\}[ \t]")))
11540 (t (error "Bad refiling target description %s" desc)))
11541 (while (setq f (pop files))
11542 (with-current-buffer
11543 (if (bufferp f) f (org-get-agenda-file-buffer f))
11545 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11546 (progn
11547 (if (bufferp f) (setq f (buffer-file-name
11548 (buffer-base-buffer f))))
11549 (setq f (and f (expand-file-name f)))
11550 (if (eq org-refile-use-outline-path 'file)
11551 (push (list (file-name-nondirectory f) f nil nil) tgs))
11552 (save-excursion
11553 (save-restriction
11554 (widen)
11555 (goto-char (point-min))
11556 (while (re-search-forward descre nil t)
11557 (goto-char (setq pos0 (point-at-bol)))
11558 (catch 'next
11559 (when org-refile-target-verify-function
11560 (save-match-data
11561 (or (funcall org-refile-target-verify-function)
11562 (throw 'next t))))
11563 (when (and (looking-at org-complex-heading-regexp)
11564 (not (member (match-string 4) excluded-entries))
11565 (match-string 4))
11566 (setq level (org-reduced-level
11567 (- (match-end 1) (match-beginning 1)))
11568 txt (org-link-display-format (match-string 4))
11569 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11570 re (format org-complex-heading-regexp-format
11571 (regexp-quote (match-string 4))))
11572 (when org-refile-use-outline-path
11573 (setq txt (mapconcat
11574 'org-protect-slash
11575 (append
11576 (if (eq org-refile-use-outline-path
11577 'file)
11578 (list (file-name-nondirectory
11579 (buffer-file-name
11580 (buffer-base-buffer))))
11581 (if (eq org-refile-use-outline-path
11582 'full-file-path)
11583 (list (buffer-file-name
11584 (buffer-base-buffer)))))
11585 (org-get-outline-path fast-path-p
11586 level txt)
11587 (list txt))
11588 "/")))
11589 (push (list txt f re (org-refile-marker (point)))
11590 tgs)))
11591 (when (= (point) pos0)
11592 ;; verification function has not moved point
11593 (goto-char (point-at-eol))))))))
11594 (when org-refile-use-cache
11595 (org-refile-cache-put tgs (buffer-file-name) descre))
11596 (setq targets (append tgs targets))))))
11597 (message "Getting targets...done")
11598 (nreverse targets)))
11600 (defun org-protect-slash (s)
11601 (while (string-match "/" s)
11602 (setq s (replace-match "\\" t t s)))
11605 (defvar org-olpa (make-vector 20 nil))
11607 (defun org-get-outline-path (&optional fastp level heading)
11608 "Return the outline path to the current entry, as a list.
11610 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11611 routine which makes outline path derivations for an entire file,
11612 avoiding backtracing. Refile target collection makes use of that."
11613 (if fastp
11614 (progn
11615 (if (> level 19)
11616 (error "Outline path failure, more than 19 levels"))
11617 (loop for i from level upto 19 do
11618 (aset org-olpa i nil))
11619 (prog1
11620 (delq nil (append org-olpa nil))
11621 (aset org-olpa level heading)))
11622 (let (rtn case-fold-search)
11623 (save-excursion
11624 (save-restriction
11625 (widen)
11626 (while (org-up-heading-safe)
11627 (when (looking-at org-complex-heading-regexp)
11628 (push (org-trim
11629 (replace-regexp-in-string
11630 ;; Remove statistical/checkboxes cookies
11631 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11632 (org-match-string-no-properties 4)))
11633 rtn)))
11634 rtn)))))
11636 (defun org-format-outline-path (path &optional width prefix separator)
11637 "Format the outline path PATH for display.
11638 WIDTH is the maximum number of characters that is available.
11639 PREFIX is a prefix to be included in the returned string,
11640 such as the file name.
11641 SEPARATOR is inserted between the different parts of the path,
11642 the default is \"/\"."
11643 (setq width (or width 79))
11644 (if prefix (setq width (- width (length prefix))))
11645 (if (not path)
11646 (or prefix "")
11647 (let* ((nsteps (length path))
11648 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11649 (maxwidth (if (<= total-width width)
11650 10000 ;; everything fits
11651 ;; we need to shorten the level headings
11652 (/ (- width nsteps) nsteps)))
11653 (org-odd-levels-only nil)
11654 (n 0)
11655 (total (1+ (length prefix))))
11656 (setq maxwidth (max maxwidth 10))
11657 (concat prefix
11658 (if prefix (or separator "/"))
11659 (mapconcat
11660 (lambda (h)
11661 (setq n (1+ n))
11662 (if (and (= n nsteps) (< maxwidth 10000))
11663 (setq maxwidth (- total-width total)))
11664 (if (< (length h) maxwidth)
11665 (progn (setq total (+ total (length h) 1)) h)
11666 (setq h (substring h 0 (- maxwidth 2))
11667 total (+ total maxwidth 1))
11668 (if (string-match "[ \t]+\\'" h)
11669 (setq h (substring h 0 (match-beginning 0))))
11670 (setq h (concat h "..")))
11671 (org-add-props h nil 'face
11672 (nth (% (1- n) org-n-level-faces)
11673 org-level-faces))
11675 path (or separator "/"))))))
11677 (defun org-display-outline-path (&optional file current separator just-return-string)
11678 "Display the current outline path in the echo area.
11680 If FILE is non-nil, prepend the output with the file name.
11681 If CURRENT is non-nil, append the current heading to the output.
11682 SEPARATOR is passed through to `org-format-outline-path'. It separates
11683 the different parts of the path and defaults to \"/\".
11684 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11685 (interactive "P")
11686 (let* (case-fold-search
11687 (bfn (buffer-file-name (buffer-base-buffer)))
11688 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11689 res)
11690 (if current (setq path (append path
11691 (save-excursion
11692 (org-back-to-heading t)
11693 (if (looking-at org-complex-heading-regexp)
11694 (list (match-string 4)))))))
11695 (setq res
11696 (org-format-outline-path
11697 path
11698 (1- (frame-width))
11699 (and file bfn (concat (file-name-nondirectory bfn) separator))
11700 separator))
11701 (if just-return-string
11702 (org-no-properties res)
11703 (org-unlogged-message "%s" res))))
11705 (defvar org-refile-history nil
11706 "History for refiling operations.")
11708 (defvar org-after-refile-insert-hook nil
11709 "Hook run after `org-refile' has inserted its stuff at the new location.
11710 Note that this is still *before* the stuff will be removed from
11711 the *old* location.")
11713 (defvar org-capture-last-stored-marker)
11714 (defvar org-refile-keep nil
11715 "Non-nil means `org-refile' will copy instead of refile.")
11717 (defun org-copy ()
11718 "Like `org-refile', but copy."
11719 (interactive)
11720 (let ((org-refile-keep t))
11721 (funcall 'org-refile nil nil nil "Copy")))
11723 (defun org-refile (&optional arg default-buffer rfloc msg)
11724 "Move the entry or entries at point to another heading.
11725 The list of target headings is compiled using the information in
11726 `org-refile-targets', which see.
11728 At the target location, the entry is filed as a subitem of the
11729 target heading. Depending on `org-reverse-note-order', the new
11730 subitem will either be the first or the last subitem.
11732 If there is an active region, all entries in that region will be
11733 refiled. However, the region must fulfill the requirement that
11734 the first heading sets the top-level of the moved text.
11736 With prefix arg ARG, the command will only visit the target
11737 location and not actually move anything.
11739 With a double prefix arg \\[universal-argument] \\[universal-argument], go to the location where the last
11740 refiling operation has put the subtree.
11742 With a numeric prefix argument of `2', refile to the running clock.
11744 With a numeric prefix argument of `3', emulate `org-refile-keep'
11745 being set to `t' and copy to the target location, don't move it.
11746 Beware that keeping refiled entries may result in duplicated ID
11747 properties.
11749 RFLOC can be a refile location obtained in a different way.
11751 MSG is a string to replace \"Refile\" in the default prompt with
11752 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11754 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11756 If you are using target caching (see `org-refile-use-cache'), you
11757 have to clear the target cache in order to find new targets.
11758 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11759 prefix argument (`C-u C-u C-u C-c C-w')."
11760 (interactive "P")
11761 (if (member arg '(0 (64)))
11762 (org-refile-cache-clear)
11763 (let* ((actionmsg (cond (msg msg)
11764 ((equal arg 3) "Refile (and keep)")
11765 (t "Refile")))
11766 (cbuf (current-buffer))
11767 (regionp (org-region-active-p))
11768 (region-start (and regionp (region-beginning)))
11769 (region-end (and regionp (region-end)))
11770 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11771 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11772 pos it nbuf file re level reversed)
11773 (setq last-command nil)
11774 (when regionp
11775 (goto-char region-start)
11776 (or (bolp) (goto-char (point-at-bol)))
11777 (setq region-start (point))
11778 (unless (or (org-kill-is-subtree-p
11779 (buffer-substring region-start region-end))
11780 (prog1 org-refile-active-region-within-subtree
11781 (let ((s (point-at-eol)))
11782 (org-toggle-heading)
11783 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11784 (user-error "The region is not a (sequence of) subtree(s)")))
11785 (if (equal arg '(16))
11786 (org-refile-goto-last-stored)
11787 (when (or
11788 (and (equal arg 2)
11789 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11790 (prog1
11791 (setq it (list (or org-clock-heading "running clock")
11792 (buffer-file-name
11793 (marker-buffer org-clock-hd-marker))
11795 (marker-position org-clock-hd-marker)))
11796 (setq arg nil)))
11797 (setq it (or rfloc
11798 (let (heading-text)
11799 (save-excursion
11800 (unless (and arg (listp arg))
11801 (org-back-to-heading t)
11802 (setq heading-text
11803 (replace-regexp-in-string
11804 org-bracket-link-regexp
11805 "\\3"
11806 (nth 4 (org-heading-components)))))
11807 (org-refile-get-location
11808 (cond ((and arg (listp arg)) "Goto")
11809 (regionp (concat actionmsg " region to"))
11810 (t (concat actionmsg " subtree \""
11811 heading-text "\" to")))
11812 default-buffer
11813 (and (not (equal '(4) arg))
11814 org-refile-allow-creating-parent-nodes)
11815 arg))))))
11816 (setq file (nth 1 it)
11817 re (nth 2 it)
11818 pos (nth 3 it))
11819 (if (and (not arg)
11821 (equal (buffer-file-name) file)
11822 (if regionp
11823 (and (>= pos region-start)
11824 (<= pos region-end))
11825 (and (>= pos (point))
11826 (< pos (save-excursion
11827 (org-end-of-subtree t t))))))
11828 (error "Cannot refile to position inside the tree or region"))
11829 (setq nbuf (or (find-buffer-visiting file)
11830 (find-file-noselect file)))
11831 (if (and arg (not (equal arg 3)))
11832 (progn
11833 (org-pop-to-buffer-same-window nbuf)
11834 (goto-char pos)
11835 (org-show-context 'org-goto))
11836 (if regionp
11837 (progn
11838 (org-kill-new (buffer-substring region-start region-end))
11839 (org-save-markers-in-region region-start region-end))
11840 (org-copy-subtree 1 nil t))
11841 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11842 (find-file-noselect file)))
11843 (setq reversed (org-notes-order-reversed-p))
11844 (save-excursion
11845 (save-restriction
11846 (widen)
11847 (if pos
11848 (progn
11849 (goto-char pos)
11850 (looking-at org-outline-regexp)
11851 (setq level (org-get-valid-level (funcall outline-level) 1))
11852 (goto-char
11853 (if reversed
11854 (or (outline-next-heading) (point-max))
11855 (or (save-excursion (org-get-next-sibling))
11856 (org-end-of-subtree t t)
11857 (point-max)))))
11858 (setq level 1)
11859 (if (not reversed)
11860 (goto-char (point-max))
11861 (goto-char (point-min))
11862 (or (outline-next-heading) (goto-char (point-max)))))
11863 (if (not (bolp)) (newline))
11864 (org-paste-subtree level)
11865 (when org-log-refile
11866 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11867 (unless (eq org-log-refile 'note)
11868 (save-excursion (org-add-log-note))))
11869 (and org-auto-align-tags
11870 (let ((org-loop-over-headlines-in-active-region nil))
11871 (org-set-tags nil t)))
11872 (let ((bookmark-name (plist-get org-bookmark-names-plist
11873 :last-refile)))
11874 (when bookmark-name
11875 (with-demoted-errors
11876 (bookmark-set bookmark-name))))
11877 ;; If we are refiling for capture, make sure that the
11878 ;; last-capture pointers point here
11879 (when (org-bound-and-true-p org-refile-for-capture)
11880 (let ((bookmark-name (plist-get org-bookmark-names-plist
11881 :last-capture-marker)))
11882 (when bookmark-name
11883 (with-demoted-errors
11884 (bookmark-set bookmark-name))))
11885 (move-marker org-capture-last-stored-marker (point)))
11886 (if (fboundp 'deactivate-mark) (deactivate-mark))
11887 (run-hooks 'org-after-refile-insert-hook))))
11888 (unless org-refile-keep
11889 (if regionp
11890 (delete-region (point) (+ (point) (- region-end region-start)))
11891 (delete-region
11892 (and (org-back-to-heading t) (point))
11893 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11894 (when (featurep 'org-inlinetask)
11895 (org-inlinetask-remove-END-maybe))
11896 (setq org-markers-to-move nil)
11897 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11899 (defun org-refile-goto-last-stored ()
11900 "Go to the location where the last refile was stored."
11901 (interactive)
11902 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11903 (message "This is the location of the last refile"))
11905 (defun org-refile--get-location (refloc tbl)
11906 "When user refile to REFLOC, find the associated target in TBL.
11907 Also check `org-refile-target-table'."
11908 (car (delq
11910 (mapcar
11911 (lambda (r) (or (assoc r tbl)
11912 (assoc r org-refile-target-table)))
11913 (list (replace-regexp-in-string "/$" "" refloc)
11914 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11916 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11917 no-exclude)
11918 "Prompt the user for a refile location, using PROMPT.
11919 PROMPT should not be suffixed with a colon and a space, because
11920 this function appends the default value from
11921 `org-refile-history' automatically, if that is not empty.
11922 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11923 this is used for the GOTO interface."
11924 (let ((org-refile-targets org-refile-targets)
11925 (org-refile-use-outline-path org-refile-use-outline-path)
11926 excluded-entries)
11927 (when (and (derived-mode-p 'org-mode)
11928 (not org-refile-use-cache)
11929 (not no-exclude))
11930 (org-map-tree
11931 (lambda()
11932 (setq excluded-entries
11933 (append excluded-entries (list (org-get-heading t t)))))))
11934 (setq org-refile-target-table
11935 (org-refile-get-targets default-buffer excluded-entries)))
11936 (unless org-refile-target-table
11937 (user-error "No refile targets"))
11938 (let* ((cbuf (current-buffer))
11939 (partial-completion-mode nil)
11940 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11941 (cfunc (if (and org-refile-use-outline-path
11942 org-outline-path-complete-in-steps)
11943 'org-olpath-completing-read
11944 'org-icompleting-read))
11945 (extra (if org-refile-use-outline-path "/" ""))
11946 (cbnex (concat (buffer-name) extra))
11947 (filename (and cfn (expand-file-name cfn)))
11948 (tbl (mapcar
11949 (lambda (x)
11950 (if (and (not (member org-refile-use-outline-path
11951 '(file full-file-path)))
11952 (not (equal filename (nth 1 x))))
11953 (cons (concat (car x) extra " ("
11954 (file-name-nondirectory (nth 1 x)) ")")
11955 (cdr x))
11956 (cons (concat (car x) extra) (cdr x))))
11957 org-refile-target-table))
11958 (completion-ignore-case t)
11959 cdef
11960 (prompt (concat prompt
11961 (or (and (car org-refile-history)
11962 (concat " (default " (car org-refile-history) ")"))
11963 (and (assoc cbnex tbl) (setq cdef cbnex)
11964 (concat " (default " cbnex ")"))) ": "))
11965 pa answ parent-target child parent old-hist)
11966 (setq old-hist org-refile-history)
11967 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11968 nil 'org-refile-history (or cdef (car org-refile-history))))
11969 (if (setq pa (org-refile--get-location answ tbl))
11970 (progn
11971 (org-refile-check-position pa)
11972 (when (or (not org-refile-history)
11973 (not (eq old-hist org-refile-history))
11974 (not (equal (car pa) (car org-refile-history))))
11975 (setq org-refile-history
11976 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11977 org-refile-history
11978 (cdr org-refile-history))))
11979 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11980 (pop org-refile-history)))
11982 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11983 (progn
11984 (setq parent (match-string 1 answ)
11985 child (match-string 2 answ))
11986 (setq parent-target (org-refile--get-location parent tbl))
11987 (when (and parent-target
11988 (or (eq new-nodes t)
11989 (and (eq new-nodes 'confirm)
11990 (y-or-n-p (format "Create new node \"%s\"? "
11991 child)))))
11992 (org-refile-new-child parent-target child)))
11993 (user-error "Invalid target location")))))
11995 (declare-function org-string-nw-p "org-macs" (s))
11996 (defun org-refile-check-position (refile-pointer)
11997 "Check if the refile pointer matches the headline to which it points."
11998 (let* ((file (nth 1 refile-pointer))
11999 (re (nth 2 refile-pointer))
12000 (pos (nth 3 refile-pointer))
12001 buffer)
12002 (if (and (not (markerp pos)) (not file))
12003 (user-error "Please indicate a target file in the refile path")
12004 (when (org-string-nw-p re)
12005 (setq buffer (if (markerp pos)
12006 (marker-buffer pos)
12007 (or (find-buffer-visiting file)
12008 (find-file-noselect file))))
12009 (with-current-buffer buffer
12010 (save-excursion
12011 (save-restriction
12012 (widen)
12013 (goto-char pos)
12014 (beginning-of-line 1)
12015 (unless (org-looking-at-p re)
12016 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
12018 (defun org-refile-new-child (parent-target child)
12019 "Use refile target PARENT-TARGET to add new CHILD below it."
12020 (unless parent-target
12021 (error "Cannot find parent for new node"))
12022 (let ((file (nth 1 parent-target))
12023 (pos (nth 3 parent-target))
12024 level)
12025 (with-current-buffer (or (find-buffer-visiting file)
12026 (find-file-noselect file))
12027 (save-excursion
12028 (save-restriction
12029 (widen)
12030 (if pos
12031 (goto-char pos)
12032 (goto-char (point-max))
12033 (if (not (bolp)) (newline)))
12034 (when (looking-at org-outline-regexp)
12035 (setq level (funcall outline-level))
12036 (org-end-of-subtree t t))
12037 (org-back-over-empty-lines)
12038 (insert "\n" (make-string
12039 (if pos (org-get-valid-level level 1) 1) ?*)
12040 " " child "\n")
12041 (beginning-of-line 0)
12042 (list (concat (car parent-target) "/" child) file "" (point)))))))
12044 (defun org-olpath-completing-read (prompt collection &rest args)
12045 "Read an outline path like a file name."
12046 (let ((thetable collection)
12047 (org-completion-use-ido nil) ; does not work with ido.
12048 (org-completion-use-iswitchb nil)) ; or iswitchb
12049 (apply
12050 'org-icompleting-read prompt
12051 (lambda (string predicate &optional flag)
12052 (let (rtn r f (l (length string)))
12053 (cond
12054 ((eq flag nil)
12055 ;; try completion
12056 (try-completion string thetable))
12057 ((eq flag t)
12058 ;; all-completions
12059 (setq rtn (all-completions string thetable predicate))
12060 (mapcar
12061 (lambda (x)
12062 (setq r (substring x l))
12063 (if (string-match " ([^)]*)$" x)
12064 (setq f (match-string 0 x))
12065 (setq f ""))
12066 (if (string-match "/" r)
12067 (concat string (substring r 0 (match-end 0)) f)
12069 rtn))
12070 ((eq flag 'lambda)
12071 ;; exact match?
12072 (assoc string thetable)))))
12073 args)))
12075 ;;;; Dynamic blocks
12077 (defun org-find-dblock (name)
12078 "Find the first dynamic block with name NAME in the buffer.
12079 If not found, stay at current position and return nil."
12080 (let ((case-fold-search t) pos)
12081 (save-excursion
12082 (goto-char (point-min))
12083 (setq pos (and (re-search-forward
12084 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12085 (match-beginning 0))))
12086 (if pos (goto-char pos))
12087 pos))
12089 (defun org-create-dblock (plist)
12090 "Create a dynamic block section, with parameters taken from PLIST.
12091 PLIST must contain a :name entry which is used as the name of the block."
12092 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12093 (end-of-line 1)
12094 (newline))
12095 (let ((col (current-column))
12096 (name (plist-get plist :name)))
12097 (insert "#+BEGIN: " name)
12098 (while plist
12099 (if (eq (car plist) :name)
12100 (setq plist (cddr plist))
12101 (insert " " (prin1-to-string (pop plist)))))
12102 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12103 (beginning-of-line -2)))
12105 (defun org-prepare-dblock ()
12106 "Prepare dynamic block for refresh.
12107 This empties the block, puts the cursor at the insert position and returns
12108 the property list including an extra property :name with the block name."
12109 (unless (looking-at org-dblock-start-re)
12110 (user-error "Not at a dynamic block"))
12111 (let* ((begdel (1+ (match-end 0)))
12112 (name (org-no-properties (match-string 1)))
12113 (params (append (list :name name)
12114 (read (concat "(" (match-string 3) ")")))))
12115 (save-excursion
12116 (beginning-of-line 1)
12117 (skip-chars-forward " \t")
12118 (setq params (plist-put params :indentation-column (current-column))))
12119 (unless (re-search-forward org-dblock-end-re nil t)
12120 (error "Dynamic block not terminated"))
12121 (setq params
12122 (append params
12123 (list :content (buffer-substring
12124 begdel (match-beginning 0)))))
12125 (delete-region begdel (match-beginning 0))
12126 (goto-char begdel)
12127 (open-line 1)
12128 params))
12130 (defun org-map-dblocks (&optional command)
12131 "Apply COMMAND to all dynamic blocks in the current buffer.
12132 If COMMAND is not given, use `org-update-dblock'."
12133 (let ((cmd (or command 'org-update-dblock)))
12134 (save-excursion
12135 (goto-char (point-min))
12136 (while (re-search-forward org-dblock-start-re nil t)
12137 (goto-char (match-beginning 0))
12138 (save-excursion
12139 (condition-case nil
12140 (funcall cmd)
12141 (error (message "Error during update of dynamic block"))))
12142 (unless (re-search-forward org-dblock-end-re nil t)
12143 (error "Dynamic block not terminated"))))))
12145 (defun org-dblock-update (&optional arg)
12146 "User command for updating dynamic blocks.
12147 Update the dynamic block at point. With prefix ARG, update all dynamic
12148 blocks in the buffer."
12149 (interactive "P")
12150 (if arg
12151 (org-update-all-dblocks)
12152 (or (looking-at org-dblock-start-re)
12153 (org-beginning-of-dblock))
12154 (org-update-dblock)))
12156 (defun org-update-dblock ()
12157 "Update the dynamic block at point.
12158 This means to empty the block, parse for parameters and then call
12159 the correct writing function."
12160 (interactive)
12161 (save-excursion
12162 (let* ((win (selected-window))
12163 (pos (point))
12164 (line (org-current-line))
12165 (params (org-prepare-dblock))
12166 (name (plist-get params :name))
12167 (indent (plist-get params :indentation-column))
12168 (cmd (intern (concat "org-dblock-write:" name))))
12169 (message "Updating dynamic block `%s' at line %d..." name line)
12170 (funcall cmd params)
12171 (message "Updating dynamic block `%s' at line %d...done" name line)
12172 (goto-char pos)
12173 (when (and indent (> indent 0))
12174 (setq indent (make-string indent ?\ ))
12175 (save-excursion
12176 (select-window win)
12177 (org-beginning-of-dblock)
12178 (forward-line 1)
12179 (while (not (looking-at org-dblock-end-re))
12180 (insert indent)
12181 (beginning-of-line 2))
12182 (when (looking-at org-dblock-end-re)
12183 (and (looking-at "[ \t]+")
12184 (replace-match ""))
12185 (insert indent)))))))
12187 (defun org-beginning-of-dblock ()
12188 "Find the beginning of the dynamic block at point.
12189 Error if there is no such block at point."
12190 (let ((pos (point))
12191 beg)
12192 (end-of-line 1)
12193 (if (and (re-search-backward org-dblock-start-re nil t)
12194 (setq beg (match-beginning 0))
12195 (re-search-forward org-dblock-end-re nil t)
12196 (> (match-end 0) pos))
12197 (goto-char beg)
12198 (goto-char pos)
12199 (error "Not in a dynamic block"))))
12201 (defun org-update-all-dblocks ()
12202 "Update all dynamic blocks in the buffer.
12203 This function can be used in a hook."
12204 (interactive)
12205 (when (derived-mode-p 'org-mode)
12206 (org-map-dblocks 'org-update-dblock)))
12209 ;;;; Completion
12211 (declare-function org-export-backend-name "org-export" (cl-x))
12212 (declare-function org-export-backend-options "org-export" (cl-x))
12213 (defun org-get-export-keywords ()
12214 "Return a list of all currently understood export keywords.
12215 Export keywords include options, block names, attributes and
12216 keywords relative to each registered export back-end."
12217 (let (keywords)
12218 (dolist (backend
12219 (org-bound-and-true-p org-export--registered-backends)
12220 (delq nil keywords))
12221 ;; Back-end name (for keywords, like #+LATEX:)
12222 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12223 (dolist (option-entry (org-export-backend-options backend))
12224 ;; Back-end options.
12225 (push (nth 1 option-entry) keywords)))))
12227 (defconst org-options-keywords
12228 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12229 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12230 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12231 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12232 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12234 (defcustom org-structure-template-alist
12235 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC" "<src lang=\"?\">\n\n</src>")
12236 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE" "<example>\n?\n</example>")
12237 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE" "<quote>\n?\n</quote>")
12238 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE" "<verse>\n?\n</verse>")
12239 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM" "<verbatim>\n?\n</verbatim>")
12240 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER" "<center>\n?\n</center>")
12241 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
12242 "<literal style=\"latex\">\n?\n</literal>")
12243 ("L" "#+LaTeX: " "<literal style=\"latex\">?</literal>")
12244 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
12245 "<literal style=\"html\">\n?\n</literal>")
12246 ("H" "#+HTML: " "<literal style=\"html\">?</literal>")
12247 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII" "")
12248 ("A" "#+ASCII: " "")
12249 ("i" "#+INDEX: ?" "#+INDEX: ?")
12250 ("I" "#+INCLUDE: %file ?"
12251 "<include file=%file markup=\"?\">"))
12252 "Structure completion elements.
12253 This is a list of abbreviation keys and values. The value gets inserted
12254 if you type `<' followed by the key and then press the completion key,
12255 usually `M-TAB'. %file will be replaced by a file name after prompting
12256 for the file using completion. The cursor will be placed at the position
12257 of the `?` in the template.
12258 There are two templates for each key, the first uses the original Org syntax,
12259 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12260 the default when the /org-mtags.el/ module has been loaded. See also the
12261 variable `org-mtags-prefer-muse-templates'."
12262 :group 'org-completion
12263 :type '(repeat
12264 (list
12265 (string :tag "Key")
12266 (string :tag "Template")
12267 (string :tag "Muse Template"))))
12269 (defun org-try-structure-completion ()
12270 "Try to complete a structure template before point.
12271 This looks for strings like \"<e\" on an otherwise empty line and
12272 expands them."
12273 (let ((l (buffer-substring (point-at-bol) (point)))
12275 (when (and (looking-at "[ \t]*$")
12276 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12277 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12278 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12279 (match-beginning 1)) a)
12280 t)))
12282 (defun org-complete-expand-structure-template (start cell)
12283 "Expand a structure template."
12284 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
12285 (rpl (nth (if musep 2 1) cell))
12286 (ind ""))
12287 (delete-region start (point))
12288 (when (string-match "\\`[ \t]*#\\+" rpl)
12289 (cond
12290 ((bolp))
12291 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12292 (setq ind (buffer-substring (point-at-bol) (point))))
12293 (t (newline))))
12294 (setq start (point))
12295 (if (string-match "%file" rpl)
12296 (setq rpl (replace-match
12297 (concat
12298 "\""
12299 (save-match-data
12300 (abbreviate-file-name (read-file-name "Include file: ")))
12301 "\"")
12302 t t rpl)))
12303 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12304 (concat "\n" ind)))
12305 (insert rpl)
12306 (if (re-search-backward "\\?" start t) (delete-char 1))))
12308 ;;;; TODO, DEADLINE, Comments
12310 (defun org-toggle-comment ()
12311 "Change the COMMENT state of an entry."
12312 (interactive)
12313 (save-excursion
12314 (org-back-to-heading)
12315 (looking-at org-complex-heading-regexp)
12316 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12317 (skip-chars-forward " \t")
12318 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12319 (if (org-in-commented-heading-p t)
12320 (delete-region (point)
12321 (progn (search-forward " " (line-end-position) 'move)
12322 (skip-chars-forward " \t")
12323 (point)))
12324 (insert org-comment-string)
12325 (unless (eolp) (insert " ")))))
12327 (defvar org-last-todo-state-is-todo nil
12328 "This is non-nil when the last TODO state change led to a TODO state.
12329 If the last change removed the TODO tag or switched to DONE, then
12330 this is nil.")
12332 (defvar org-setting-tags nil) ; dynamically skipped
12334 (defvar org-todo-setup-filter-hook nil
12335 "Hook for functions that pre-filter todo specs.
12336 Each function takes a todo spec and returns either nil or the spec
12337 transformed into canonical form." )
12339 (defvar org-todo-get-default-hook nil
12340 "Hook for functions that get a default item for todo.
12341 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12342 nil or a string to be used for the todo mark." )
12344 (defvar org-agenda-headline-snapshot-before-repeat)
12346 (defun org-current-effective-time ()
12347 "Return current time adjusted for `org-extend-today-until' variable."
12348 (let* ((ct (org-current-time))
12349 (dct (decode-time ct))
12350 (ct1
12351 (cond
12352 (org-use-last-clock-out-time-as-effective-time
12353 (or (org-clock-get-last-clock-out-time) ct))
12354 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12355 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12356 (t ct))))
12357 ct1))
12359 (defun org-todo-yesterday (&optional arg)
12360 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12361 (interactive "P")
12362 (if (eq major-mode 'org-agenda-mode)
12363 (apply 'org-agenda-todo-yesterday arg)
12364 (let* ((hour (third (decode-time
12365 (org-current-time))))
12366 (org-extend-today-until (1+ hour)))
12367 (org-todo arg))))
12369 (defvar org-block-entry-blocking ""
12370 "First entry preventing the TODO state change.")
12372 (defun org-cancel-repeater ()
12373 "Cancel a repeater by setting its numeric value to zero."
12374 (interactive)
12375 (save-excursion
12376 (org-back-to-heading t)
12377 (let ((bound1 (point))
12378 (bound0 (save-excursion (outline-next-heading) (point))))
12379 (when (re-search-forward
12380 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12381 org-deadline-time-regexp "\\)\\|\\("
12382 org-ts-regexp "\\)")
12383 bound0 t)
12384 (if (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]" bound1 t)
12385 (replace-match "0" t nil nil 1))))))
12387 (defun org-todo (&optional arg)
12388 "Change the TODO state of an item.
12389 The state of an item is given by a keyword at the start of the heading,
12390 like
12391 *** TODO Write paper
12392 *** DONE Call mom
12394 The different keywords are specified in the variable `org-todo-keywords'.
12395 By default the available states are \"TODO\" and \"DONE\".
12396 So for this example: when the item starts with TODO, it is changed to DONE.
12397 When it starts with DONE, the DONE is removed. And when neither TODO nor
12398 DONE are present, add TODO at the beginning of the heading.
12400 With \\[universal-argument] prefix arg, use completion to determine the new \
12401 state.
12402 With numeric prefix arg, switch to that state.
12403 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12404 keywords (nextset).
12405 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12406 With a numeric prefix arg of 0, inhibit note taking for the change.
12407 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12409 When called through ELisp, arg is also interpreted in the following way:
12410 'none -> empty state
12411 \"\"(empty string) -> switch to empty state
12412 'done -> switch to DONE
12413 'nextset -> switch to the next set of keywords
12414 'previousset -> switch to the previous set of keywords
12415 \"WAITING\" -> switch to the specified keyword, but only if it
12416 really is a member of `org-todo-keywords'."
12417 (interactive "P")
12418 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12419 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12420 'region-start-level 'region))
12421 org-loop-over-headlines-in-active-region)
12422 (org-map-entries
12423 `(org-todo ,arg)
12424 org-loop-over-headlines-in-active-region
12425 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12426 (if (equal arg '(16)) (setq arg 'nextset))
12427 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12428 (let ((org-blocker-hook org-blocker-hook)
12429 commentp
12430 case-fold-search)
12431 (when (equal arg '(64))
12432 (setq arg nil org-blocker-hook nil))
12433 (when (and org-blocker-hook
12434 (or org-inhibit-blocking
12435 (org-entry-get nil "NOBLOCKING")))
12436 (setq org-blocker-hook nil))
12437 (save-excursion
12438 (catch 'exit
12439 (org-back-to-heading t)
12440 (when (org-in-commented-heading-p t)
12441 (org-toggle-comment)
12442 (setq commentp t))
12443 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12444 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12445 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12446 (let* ((match-data (match-data))
12447 (startpos (point-at-bol))
12448 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12449 (org-log-done org-log-done)
12450 (org-log-repeat org-log-repeat)
12451 (org-todo-log-states org-todo-log-states)
12452 (org-inhibit-logging
12453 (if (equal arg 0)
12454 (progn (setq arg nil) 'note) org-inhibit-logging))
12455 (this (match-string 1))
12456 (hl-pos (match-beginning 0))
12457 (head (org-get-todo-sequence-head this))
12458 (ass (assoc head org-todo-kwd-alist))
12459 (interpret (nth 1 ass))
12460 (done-word (nth 3 ass))
12461 (final-done-word (nth 4 ass))
12462 (org-last-state (or this ""))
12463 (completion-ignore-case t)
12464 (member (member this org-todo-keywords-1))
12465 (tail (cdr member))
12466 (org-state (cond
12467 ((and org-todo-key-trigger
12468 (or (and (equal arg '(4))
12469 (eq org-use-fast-todo-selection 'prefix))
12470 (and (not arg) org-use-fast-todo-selection
12471 (not (eq org-use-fast-todo-selection
12472 'prefix)))))
12473 ;; Use fast selection
12474 (org-fast-todo-selection))
12475 ((and (equal arg '(4))
12476 (or (not org-use-fast-todo-selection)
12477 (not org-todo-key-trigger)))
12478 ;; Read a state with completion
12479 (org-icompleting-read
12480 "State: " (mapcar 'list org-todo-keywords-1)
12481 nil t))
12482 ((eq arg 'right)
12483 (if this
12484 (if tail (car tail) nil)
12485 (car org-todo-keywords-1)))
12486 ((eq arg 'left)
12487 (if (equal member org-todo-keywords-1)
12489 (if this
12490 (nth (- (length org-todo-keywords-1)
12491 (length tail) 2)
12492 org-todo-keywords-1)
12493 (org-last org-todo-keywords-1))))
12494 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12495 (setq arg nil))) ; hack to fall back to cycling
12496 (arg
12497 ;; user or caller requests a specific state
12498 (cond
12499 ((equal arg "") nil)
12500 ((eq arg 'none) nil)
12501 ((eq arg 'done) (or done-word (car org-done-keywords)))
12502 ((eq arg 'nextset)
12503 (or (car (cdr (member head org-todo-heads)))
12504 (car org-todo-heads)))
12505 ((eq arg 'previousset)
12506 (let ((org-todo-heads (reverse org-todo-heads)))
12507 (or (car (cdr (member head org-todo-heads)))
12508 (car org-todo-heads))))
12509 ((car (member arg org-todo-keywords-1)))
12510 ((stringp arg)
12511 (user-error "State `%s' not valid in this file" arg))
12512 ((nth (1- (prefix-numeric-value arg))
12513 org-todo-keywords-1))))
12514 ((null member) (or head (car org-todo-keywords-1)))
12515 ((equal this final-done-word) nil) ;; -> make empty
12516 ((null tail) nil) ;; -> first entry
12517 ((memq interpret '(type priority))
12518 (if (eq this-command last-command)
12519 (car tail)
12520 (if (> (length tail) 0)
12521 (or done-word (car org-done-keywords))
12522 nil)))
12524 (car tail))))
12525 (org-state (or
12526 (run-hook-with-args-until-success
12527 'org-todo-get-default-hook org-state org-last-state)
12528 org-state))
12529 (next (if org-state (concat " " org-state " ") " "))
12530 (change-plist (list :type 'todo-state-change :from this :to org-state
12531 :position startpos))
12532 dolog now-done-p)
12533 (when org-blocker-hook
12534 (setq org-last-todo-state-is-todo
12535 (not (member this org-done-keywords)))
12536 (unless (save-excursion
12537 (save-match-data
12538 (org-with-wide-buffer
12539 (run-hook-with-args-until-failure
12540 'org-blocker-hook change-plist))))
12541 (if (org-called-interactively-p 'interactive)
12542 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12543 this org-state org-block-entry-blocking)
12544 ;; fail silently
12545 (message "TODO state change from %s to %s blocked (by \"%s\")"
12546 this org-state org-block-entry-blocking)
12547 (throw 'exit nil))))
12548 (store-match-data match-data)
12549 (replace-match next t t)
12550 (cond ((equal this org-state)
12551 (message "TODO state was already %s" (org-trim next)))
12552 ((pos-visible-in-window-p hl-pos)
12553 (message "TODO state changed to %s" (org-trim next))))
12554 (unless head
12555 (setq head (org-get-todo-sequence-head org-state)
12556 ass (assoc head org-todo-kwd-alist)
12557 interpret (nth 1 ass)
12558 done-word (nth 3 ass)
12559 final-done-word (nth 4 ass)))
12560 (when (memq arg '(nextset previousset))
12561 (message "Keyword-Set %d/%d: %s"
12562 (- (length org-todo-sets) -1
12563 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12564 (length org-todo-sets)
12565 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12566 (setq org-last-todo-state-is-todo
12567 (not (member org-state org-done-keywords)))
12568 (setq now-done-p (and (member org-state org-done-keywords)
12569 (not (member this org-done-keywords))))
12570 (and logging (org-local-logging logging))
12571 (when (and (or org-todo-log-states org-log-done)
12572 (not (eq org-inhibit-logging t))
12573 (not (memq arg '(nextset previousset))))
12574 ;; we need to look at recording a time and note
12575 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12576 (nth 2 (assoc this org-todo-log-states))))
12577 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12578 (setq dolog 'time))
12579 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12580 (and org-state
12581 (member org-state org-not-done-keywords)
12582 (not (member this org-not-done-keywords))))
12583 ;; This is now a todo state and was not one before
12584 ;; If there was a CLOSED time stamp, get rid of it.
12585 (org-add-planning-info nil nil 'closed))
12586 (when (and now-done-p org-log-done)
12587 ;; It is now done, and it was not done before
12588 (org-add-planning-info 'closed (org-current-effective-time))
12589 (if (and (not dolog) (eq 'note org-log-done))
12590 (org-add-log-setup 'done org-state this 'findpos 'note)))
12591 (when (and org-state dolog)
12592 ;; This is a non-nil state, and we need to log it
12593 (org-add-log-setup 'state org-state this 'findpos dolog)))
12594 ;; Fixup tag positioning
12595 (org-todo-trigger-tag-changes org-state)
12596 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12597 (when org-provide-todo-statistics
12598 (org-update-parent-todo-statistics))
12599 (run-hooks 'org-after-todo-state-change-hook)
12600 (if (and arg (not (member org-state org-done-keywords)))
12601 (setq head (org-get-todo-sequence-head org-state)))
12602 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12603 ;; Do we need to trigger a repeat?
12604 (when now-done-p
12605 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12606 ;; This is for the agenda, take a snapshot of the headline.
12607 (save-match-data
12608 (setq org-agenda-headline-snapshot-before-repeat
12609 (org-get-heading))))
12610 (org-auto-repeat-maybe org-state))
12611 ;; Fixup cursor location if close to the keyword
12612 (if (and (outline-on-heading-p)
12613 (not (bolp))
12614 (save-excursion (beginning-of-line 1)
12615 (looking-at org-todo-line-regexp))
12616 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12617 (progn
12618 (goto-char (or (match-end 2) (match-end 1)))
12619 (and (looking-at " ") (just-one-space))))
12620 (when org-trigger-hook
12621 (save-excursion
12622 (run-hook-with-args 'org-trigger-hook change-plist)))
12623 (when commentp (org-toggle-comment))))))))
12625 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12626 "Block turning an entry into a TODO, using the hierarchy.
12627 This checks whether the current task should be blocked from state
12628 changes. Such blocking occurs when:
12630 1. The task has children which are not all in a completed state.
12632 2. A task has a parent with the property :ORDERED:, and there
12633 are siblings prior to the current task with incomplete
12634 status.
12636 3. The parent of the task is blocked because it has siblings that should
12637 be done first, or is child of a block grandparent TODO entry."
12639 (if (not org-enforce-todo-dependencies)
12640 t ; if locally turned off don't block
12641 (catch 'dont-block
12642 ;; If this is not a todo state change, or if this entry is already DONE,
12643 ;; do not block
12644 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12645 (member (plist-get change-plist :from)
12646 (cons 'done org-done-keywords))
12647 (member (plist-get change-plist :to)
12648 (cons 'todo org-not-done-keywords))
12649 (not (plist-get change-plist :to)))
12650 (throw 'dont-block t))
12651 ;; If this task has children, and any are undone, it's blocked
12652 (save-excursion
12653 (org-back-to-heading t)
12654 (let ((this-level (funcall outline-level)))
12655 (outline-next-heading)
12656 (let ((child-level (funcall outline-level)))
12657 (while (and (not (eobp))
12658 (> child-level this-level))
12659 ;; this todo has children, check whether they are all
12660 ;; completed
12661 (if (and (not (org-entry-is-done-p))
12662 (org-entry-is-todo-p))
12663 (progn (setq org-block-entry-blocking (org-get-heading))
12664 (throw 'dont-block nil)))
12665 (outline-next-heading)
12666 (setq child-level (funcall outline-level))))))
12667 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12668 ;; any previous siblings are undone, it's blocked
12669 (save-excursion
12670 (org-back-to-heading t)
12671 (let* ((pos (point))
12672 (parent-pos (and (org-up-heading-safe) (point))))
12673 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12674 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12675 (forward-line 1)
12676 (re-search-forward org-not-done-heading-regexp pos t))
12677 (setq org-block-entry-blocking (match-string 0))
12678 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12679 ;; Search further up the hierarchy, to see if an ancestor is blocked
12680 (while t
12681 (goto-char parent-pos)
12682 (if (not (looking-at org-not-done-heading-regexp))
12683 (throw 'dont-block t)) ; do not block, parent is not a TODO
12684 (setq pos (point))
12685 (setq parent-pos (and (org-up-heading-safe) (point)))
12686 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12687 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12688 (forward-line 1)
12689 (re-search-forward org-not-done-heading-regexp pos t)
12690 (setq org-block-entry-blocking (org-get-heading)))
12691 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12693 (defcustom org-track-ordered-property-with-tag nil
12694 "Should the ORDERED property also be shown as a tag?
12695 The ORDERED property decides if an entry should require subtasks to be
12696 completed in sequence. Since a property is not very visible, setting
12697 this option means that toggling the ORDERED property with the command
12698 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12699 not relevant for the behavior, but it makes things more visible.
12701 Note that toggling the tag with tags commands will not change the property
12702 and therefore not influence behavior!
12704 This can be t, meaning the tag ORDERED should be used, It can also be a
12705 string to select a different tag for this task."
12706 :group 'org-todo
12707 :type '(choice
12708 (const :tag "No tracking" nil)
12709 (const :tag "Track with ORDERED tag" t)
12710 (string :tag "Use other tag")))
12712 (defun org-toggle-ordered-property ()
12713 "Toggle the ORDERED property of the current entry.
12714 For better visibility, you can track the value of this property with a tag.
12715 See variable `org-track-ordered-property-with-tag'."
12716 (interactive)
12717 (let* ((t1 org-track-ordered-property-with-tag)
12718 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12719 (save-excursion
12720 (org-back-to-heading)
12721 (if (org-entry-get nil "ORDERED")
12722 (progn
12723 (org-delete-property "ORDERED")
12724 (and tag (org-toggle-tag tag 'off))
12725 (message "Subtasks can be completed in arbitrary order"))
12726 (org-entry-put nil "ORDERED" "t")
12727 (and tag (org-toggle-tag tag 'on))
12728 (message "Subtasks must be completed in sequence")))))
12730 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12731 (defun org-block-todo-from-checkboxes (change-plist)
12732 "Block turning an entry into a TODO, using checkboxes.
12733 This checks whether the current task should be blocked from state
12734 changes because there are unchecked boxes in this entry."
12735 (if (not org-enforce-todo-checkbox-dependencies)
12736 t ; if locally turned off don't block
12737 (catch 'dont-block
12738 ;; If this is not a todo state change, or if this entry is already DONE,
12739 ;; do not block
12740 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12741 (member (plist-get change-plist :from)
12742 (cons 'done org-done-keywords))
12743 (member (plist-get change-plist :to)
12744 (cons 'todo org-not-done-keywords))
12745 (not (plist-get change-plist :to)))
12746 (throw 'dont-block t))
12747 ;; If this task has checkboxes that are not checked, it's blocked
12748 (save-excursion
12749 (org-back-to-heading t)
12750 (let ((beg (point)) end)
12751 (outline-next-heading)
12752 (setq end (point))
12753 (goto-char beg)
12754 (if (org-list-search-forward
12755 (concat (org-item-beginning-re)
12756 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12757 "\\[[- ]\\]")
12758 end t)
12759 (progn
12760 (if (boundp 'org-blocked-by-checkboxes)
12761 (setq org-blocked-by-checkboxes t))
12762 (throw 'dont-block nil)))))
12763 t))) ; do not block
12765 (defun org-entry-blocked-p ()
12766 "Is the current entry blocked?"
12767 (org-with-silent-modifications
12768 (if (org-entry-get nil "NOBLOCKING")
12769 nil ;; Never block this entry
12770 (not (run-hook-with-args-until-failure
12771 'org-blocker-hook
12772 (list :type 'todo-state-change
12773 :position (point)
12774 :from 'todo
12775 :to 'done))))))
12777 (defun org-update-statistics-cookies (all)
12778 "Update the statistics cookie, either from TODO or from checkboxes.
12779 This should be called with the cursor in a line with a statistics cookie."
12780 (interactive "P")
12781 (if all
12782 (progn
12783 (org-update-checkbox-count 'all)
12784 (org-map-entries 'org-update-parent-todo-statistics))
12785 (if (not (org-at-heading-p))
12786 (org-update-checkbox-count)
12787 (let ((pos (point-marker))
12788 end l1 l2)
12789 (ignore-errors (org-back-to-heading t))
12790 (if (not (org-at-heading-p))
12791 (org-update-checkbox-count)
12792 (setq l1 (org-outline-level))
12793 (setq end (save-excursion
12794 (outline-next-heading)
12795 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12796 (point)))
12797 (if (and (save-excursion
12798 (re-search-forward
12799 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12800 (not (save-excursion (re-search-forward
12801 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12802 (org-update-checkbox-count)
12803 (if (and l2 (> l2 l1))
12804 (progn
12805 (goto-char end)
12806 (org-update-parent-todo-statistics))
12807 (goto-char pos)
12808 (beginning-of-line 1)
12809 (while (re-search-forward
12810 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12811 (point-at-eol) t)
12812 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12813 (goto-char pos)
12814 (move-marker pos nil)))))
12816 (defvar org-entry-property-inherited-from) ;; defined below
12817 (defun org-update-parent-todo-statistics ()
12818 "Update any statistics cookie in the parent of the current headline.
12819 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12820 the entire subtree and this will travel up the hierarchy and update
12821 statistics everywhere."
12822 (let* ((prop (save-excursion (org-up-heading-safe)
12823 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12824 (recursive (or (not org-hierarchical-todo-statistics)
12825 (and prop (string-match "\\<recursive\\>" prop))))
12826 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12828 (first t)
12829 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12830 level ltoggle l1 new ndel
12831 (cnt-all 0) (cnt-done 0) is-percent kwd
12832 checkbox-beg ov ovs ove cookie-present)
12833 (catch 'exit
12834 (save-excursion
12835 (beginning-of-line 1)
12836 (setq ltoggle (funcall outline-level))
12837 ;; Three situations are to consider:
12839 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12840 ;; to the top-level ancestor on the headline;
12842 ;; 2. If parent has "recursive" property, repeat up to the
12843 ;; headline setting that property, taking inheritance into
12844 ;; account;
12846 ;; 3. Else, move up to direct parent and proceed only once.
12847 (while (and (setq level (org-up-heading-safe))
12848 (or recursive first)
12849 (>= (point) lim))
12850 (setq first nil cookie-present nil)
12851 (unless (and level
12852 (not (string-match
12853 "\\<checkbox\\>"
12854 (downcase (or (org-entry-get nil "COOKIE_DATA")
12855 "")))))
12856 (throw 'exit nil))
12857 (while (re-search-forward box-re (point-at-eol) t)
12858 (setq cnt-all 0 cnt-done 0 cookie-present t)
12859 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12860 (save-match-data
12861 (unless (outline-next-heading) (throw 'exit nil))
12862 (while (and (looking-at org-complex-heading-regexp)
12863 (> (setq l1 (length (match-string 1))) level))
12864 (setq kwd (and (or recursive (= l1 ltoggle))
12865 (match-string 2)))
12866 (if (or (eq org-provide-todo-statistics 'all-headlines)
12867 (and (eq org-provide-todo-statistics t)
12868 (or (member kwd org-done-keywords)))
12869 (and (listp org-provide-todo-statistics)
12870 (stringp (car org-provide-todo-statistics))
12871 (or (member kwd org-provide-todo-statistics)
12872 (member kwd org-done-keywords)))
12873 (and (listp org-provide-todo-statistics)
12874 (listp (car org-provide-todo-statistics))
12875 (or (member kwd (car org-provide-todo-statistics))
12876 (and (member kwd org-done-keywords)
12877 (member kwd (cadr org-provide-todo-statistics))))))
12878 (setq cnt-all (1+ cnt-all))
12879 (if (eq org-provide-todo-statistics t)
12880 (and kwd (setq cnt-all (1+ cnt-all)))))
12881 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12882 (member kwd org-done-keywords))
12883 (and (listp org-provide-todo-statistics)
12884 (listp (car org-provide-todo-statistics))
12885 (member kwd org-done-keywords)
12886 (member kwd (cadr org-provide-todo-statistics)))
12887 (and (listp org-provide-todo-statistics)
12888 (stringp (car org-provide-todo-statistics))
12889 (member kwd org-done-keywords)))
12890 (setq cnt-done (1+ cnt-done)))
12891 (outline-next-heading)))
12892 (setq new
12893 (if is-percent
12894 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12895 (format "[%d/%d]" cnt-done cnt-all))
12896 ndel (- (match-end 0) checkbox-beg))
12897 ;; handle overlays when updating cookie from column view
12898 (when (setq ov (car (overlays-at checkbox-beg)))
12899 (setq ovs (overlay-start ov) ove (overlay-end ov))
12900 (delete-overlay ov))
12901 (goto-char checkbox-beg)
12902 (insert new)
12903 (delete-region (point) (+ (point) ndel))
12904 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12905 (when ov (move-overlay ov ovs ove)))
12906 (when cookie-present
12907 (run-hook-with-args 'org-after-todo-statistics-hook
12908 cnt-done (- cnt-all cnt-done))))))
12909 (run-hooks 'org-todo-statistics-hook)))
12911 (defvar org-after-todo-statistics-hook nil
12912 "Hook that is called after a TODO statistics cookie has been updated.
12913 Each function is called with two arguments: the number of not-done entries
12914 and the number of done entries.
12916 For example, the following function, when added to this hook, will switch
12917 an entry to DONE when all children are done, and back to TODO when new
12918 entries are set to a TODO status. Note that this hook is only called
12919 when there is a statistics cookie in the headline!
12921 (defun org-summary-todo (n-done n-not-done)
12922 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12923 (let (org-log-done org-log-states) ; turn off logging
12924 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12927 (defvar org-todo-statistics-hook nil
12928 "Hook that is run whenever Org thinks TODO statistics should be updated.
12929 This hook runs even if there is no statistics cookie present, in which case
12930 `org-after-todo-statistics-hook' would not run.")
12932 (defun org-todo-trigger-tag-changes (state)
12933 "Apply the changes defined in `org-todo-state-tags-triggers'."
12934 (let ((l org-todo-state-tags-triggers)
12935 changes)
12936 (when (or (not state) (equal state ""))
12937 (setq changes (append changes (cdr (assoc "" l)))))
12938 (when (and (stringp state) (> (length state) 0))
12939 (setq changes (append changes (cdr (assoc state l)))))
12940 (when (member state org-not-done-keywords)
12941 (setq changes (append changes (cdr (assoc 'todo l)))))
12942 (when (member state org-done-keywords)
12943 (setq changes (append changes (cdr (assoc 'done l)))))
12944 (dolist (c changes)
12945 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12947 (defun org-local-logging (value)
12948 "Get logging settings from a property VALUE."
12949 (let* (words w a)
12950 ;; directly set the variables, they are already local.
12951 (setq org-log-done nil
12952 org-log-repeat nil
12953 org-todo-log-states nil)
12954 (setq words (org-split-string value))
12955 (while (setq w (pop words))
12956 (cond
12957 ((setq a (assoc w org-startup-options))
12958 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12959 (set (nth 1 a) (nth 2 a))))
12960 ((setq a (org-extract-log-state-settings w))
12961 (and (member (car a) org-todo-keywords-1)
12962 (push a org-todo-log-states)))))))
12964 (defun org-get-todo-sequence-head (kwd)
12965 "Return the head of the TODO sequence to which KWD belongs.
12966 If KWD is not set, check if there is a text property remembering the
12967 right sequence."
12968 (let (p)
12969 (cond
12970 ((not kwd)
12971 (or (get-text-property (point-at-bol) 'org-todo-head)
12972 (progn
12973 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12974 nil (point-at-eol)))
12975 (get-text-property p 'org-todo-head))))
12976 ((not (member kwd org-todo-keywords-1))
12977 (car org-todo-keywords-1))
12978 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12980 (defun org-fast-todo-selection ()
12981 "Fast TODO keyword selection with single keys.
12982 Returns the new TODO keyword, or nil if no state change should occur."
12983 (let* ((fulltable org-todo-key-alist)
12984 (done-keywords org-done-keywords) ;; needed for the faces.
12985 (maxlen (apply 'max (mapcar
12986 (lambda (x)
12987 (if (stringp (car x)) (string-width (car x)) 0))
12988 fulltable)))
12989 (expert nil)
12990 (fwidth (+ maxlen 3 1 3))
12991 (ncol (/ (- (window-width) 4) fwidth))
12992 tg cnt e c tbl
12993 groups ingroup)
12994 (save-excursion
12995 (save-window-excursion
12996 (if expert
12997 (set-buffer (get-buffer-create " *Org todo*"))
12998 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12999 (erase-buffer)
13000 (org-set-local 'org-done-keywords done-keywords)
13001 (setq tbl fulltable cnt 0)
13002 (while (setq e (pop tbl))
13003 (cond
13004 ((equal e '(:startgroup))
13005 (push '() groups) (setq ingroup t)
13006 (when (not (= cnt 0))
13007 (setq cnt 0)
13008 (insert "\n"))
13009 (insert "{ "))
13010 ((equal e '(:endgroup))
13011 (setq ingroup nil cnt 0)
13012 (insert "}\n"))
13013 ((equal e '(:newline))
13014 (when (not (= cnt 0))
13015 (setq cnt 0)
13016 (insert "\n")
13017 (setq e (car tbl))
13018 (while (equal (car tbl) '(:newline))
13019 (insert "\n")
13020 (setq tbl (cdr tbl)))))
13022 (setq tg (car e) c (cdr e))
13023 (if ingroup (push tg (car groups)))
13024 (setq tg (org-add-props tg nil 'face
13025 (org-get-todo-face tg)))
13026 (if (and (= cnt 0) (not ingroup)) (insert " "))
13027 (insert "[" c "] " tg (make-string
13028 (- fwidth 4 (length tg)) ?\ ))
13029 (when (= (setq cnt (1+ cnt)) ncol)
13030 (insert "\n")
13031 (if ingroup (insert " "))
13032 (setq cnt 0)))))
13033 (insert "\n")
13034 (goto-char (point-min))
13035 (if (not expert) (org-fit-window-to-buffer))
13036 (message "[a-z..]:Set [SPC]:clear")
13037 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13038 (cond
13039 ((or (= c ?\C-g)
13040 (and (= c ?q) (not (rassoc c fulltable))))
13041 (setq quit-flag t))
13042 ((= c ?\ ) nil)
13043 ((setq e (rassoc c fulltable) tg (car e))
13045 (t (setq quit-flag t)))))))
13047 (defun org-entry-is-todo-p ()
13048 (member (org-get-todo-state) org-not-done-keywords))
13050 (defun org-entry-is-done-p ()
13051 (member (org-get-todo-state) org-done-keywords))
13053 (defun org-get-todo-state ()
13054 "Return the TODO keyword of the current subtree."
13055 (save-excursion
13056 (org-back-to-heading t)
13057 (and (looking-at org-todo-line-regexp)
13058 (match-end 2)
13059 (match-string 2))))
13061 (defun org-at-date-range-p (&optional inactive-ok)
13062 "Is the cursor inside a date range?"
13063 (interactive)
13064 (save-excursion
13065 (catch 'exit
13066 (let ((pos (point)))
13067 (skip-chars-backward "^[<\r\n")
13068 (skip-chars-backward "<[")
13069 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13070 (>= (match-end 0) pos)
13071 (throw 'exit t))
13072 (skip-chars-backward "^<[\r\n")
13073 (skip-chars-backward "<[")
13074 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13075 (>= (match-end 0) pos)
13076 (throw 'exit t)))
13077 nil)))
13079 (defun org-get-repeat (&optional tagline)
13080 "Check if there is a deadline/schedule with repeater in this entry."
13081 (save-match-data
13082 (save-excursion
13083 (org-back-to-heading t)
13084 (and (re-search-forward (if tagline
13085 (concat tagline "\\s-*" org-repeat-re)
13086 org-repeat-re)
13087 (org-entry-end-position) t)
13088 (match-string-no-properties 1)))))
13090 (defvar org-last-changed-timestamp)
13091 (defvar org-last-inserted-timestamp)
13092 (defvar org-log-post-message)
13093 (defvar org-log-note-purpose)
13094 (defvar org-log-note-how)
13095 (defvar org-log-note-extra)
13096 (defun org-auto-repeat-maybe (done-word)
13097 "Check if the current headline contains a repeated deadline/schedule.
13098 If yes, set TODO state back to what it was and change the base date
13099 of repeating deadline/scheduled time stamps to new date.
13100 This function is run automatically after each state change to a DONE state."
13101 ;; last-state is dynamically scoped into this function
13102 (let* ((repeat (org-get-repeat))
13103 (aa (assoc org-last-state org-todo-kwd-alist))
13104 (interpret (nth 1 aa))
13105 (head (nth 2 aa))
13106 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13107 (msg "Entry repeats: ")
13108 (org-log-done nil)
13109 (org-todo-log-states nil)
13110 re type n what ts time to-state)
13111 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13112 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
13113 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
13114 org-todo-repeat-to-state))
13115 (unless (and to-state (member to-state org-todo-keywords-1))
13116 (setq to-state (if (eq interpret 'type) org-last-state head)))
13117 (org-todo to-state)
13118 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
13119 (org-entry-put nil "LAST_REPEAT" (format-time-string
13120 (org-time-stamp-format t t))))
13121 (when org-log-repeat
13122 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13123 (memq 'org-add-log-note post-command-hook))
13124 ;; OK, we are already setup for some record
13125 (if (eq org-log-repeat 'note)
13126 ;; make sure we take a note, not only a time stamp
13127 (setq org-log-note-how 'note))
13128 ;; Set up for taking a record
13129 (org-add-log-setup 'state (or done-word (car org-done-keywords))
13130 org-last-state
13131 'findpos org-log-repeat)))
13132 (org-back-to-heading t)
13133 (org-add-planning-info nil nil 'closed)
13134 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
13135 org-deadline-time-regexp "\\)\\|\\("
13136 org-ts-regexp "\\)"))
13137 (while (re-search-forward
13138 re (save-excursion (outline-next-heading) (point)) t)
13139 (setq type (if (match-end 1) org-scheduled-string
13140 (if (match-end 3) org-deadline-string "Plain:"))
13141 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
13142 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
13143 (setq n (string-to-number (match-string 2 ts))
13144 what (match-string 3 ts))
13145 (if (equal what "w") (setq n (* n 7) what "d"))
13146 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
13147 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
13148 ;; Preparation, see if we need to modify the start date for the change
13149 (when (match-end 1)
13150 (setq time (save-match-data (org-time-string-to-time ts)))
13151 (cond
13152 ((equal (match-string 1 ts) ".")
13153 ;; Shift starting date to today
13154 (org-timestamp-change
13155 (- (org-today) (time-to-days time))
13156 'day))
13157 ((equal (match-string 1 ts) "+")
13158 (let ((nshiftmax 10) (nshift 0))
13159 (while (or (= nshift 0)
13160 (<= (time-to-days time)
13161 (time-to-days (current-time))))
13162 (when (= (incf nshift) nshiftmax)
13163 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
13164 (user-error "Abort")))
13165 (org-timestamp-change n (cdr (assoc what whata)))
13166 (org-at-timestamp-p t)
13167 (setq ts (match-string 1))
13168 (setq time (save-match-data (org-time-string-to-time ts)))))
13169 (org-timestamp-change (- n) (cdr (assoc what whata)))
13170 ;; rematch, so that we have everything in place for the real shift
13171 (org-at-timestamp-p t)
13172 (setq ts (match-string 1))
13173 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
13174 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
13175 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
13176 (setq org-log-post-message msg)
13177 (message "%s" msg))))
13179 (defun org-show-todo-tree (arg)
13180 "Make a compact tree which shows all headlines marked with TODO.
13181 The tree will show the lines where the regexp matches, and all higher
13182 headlines above the match.
13183 With a \\[universal-argument] prefix, prompt for a regexp to match.
13184 With a numeric prefix N, construct a sparse tree for the Nth element
13185 of `org-todo-keywords-1'."
13186 (interactive "P")
13187 (let ((case-fold-search nil)
13188 (kwd-re
13189 (cond ((null arg) org-not-done-regexp)
13190 ((equal arg '(4))
13191 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
13192 (mapcar 'list org-todo-keywords-1))))
13193 (concat "\\("
13194 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13195 "\\)\\>")))
13196 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13197 (regexp-quote (nth (1- (prefix-numeric-value arg))
13198 org-todo-keywords-1)))
13199 (t (user-error "Invalid prefix argument: %s" arg)))))
13200 (message "%d TODO entries found"
13201 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13203 (defun org-deadline (arg &optional time)
13204 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13205 With one universal prefix argument, remove any deadline from the item.
13206 With two universal prefix arguments, prompt for a warning delay.
13207 With argument TIME, set the deadline at the corresponding date. TIME
13208 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13209 (interactive "P")
13210 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13211 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13212 'region-start-level 'region))
13213 org-loop-over-headlines-in-active-region)
13214 (org-map-entries
13215 `(org-deadline ',arg ,time)
13216 org-loop-over-headlines-in-active-region
13217 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13218 (let* ((old-date (org-entry-get nil "DEADLINE"))
13219 (old-date-time (if old-date (org-time-string-to-time old-date)))
13220 (repeater (and old-date
13221 (string-match
13222 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13223 old-date)
13224 (match-string 1 old-date))))
13225 (cond
13226 ((equal arg '(4))
13227 (when (and old-date org-log-redeadline)
13228 (org-add-log-setup 'deldeadline nil old-date 'findpos
13229 org-log-redeadline))
13230 (org-remove-timestamp-with-keyword org-deadline-string)
13231 (message "Item no longer has a deadline."))
13232 ((equal arg '(16))
13233 (save-excursion
13234 (org-back-to-heading t)
13235 (if (re-search-forward
13236 org-deadline-time-regexp
13237 (save-excursion (outline-next-heading) (point)) t)
13238 (let* ((rpl0 (match-string 1))
13239 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13240 (replace-match
13241 (concat org-deadline-string
13242 " <" rpl
13243 (format " -%dd"
13244 (abs
13245 (- (time-to-days
13246 (save-match-data
13247 (org-read-date nil t nil "Warn starting from" old-date-time)))
13248 (time-to-days old-date-time))))
13249 ">") t t))
13250 (user-error "No deadline information to update"))))
13252 (org-add-planning-info 'deadline time 'closed)
13253 (when (and old-date org-log-redeadline
13254 (not (equal old-date
13255 (substring org-last-inserted-timestamp 1 -1))))
13256 (org-add-log-setup 'redeadline nil old-date 'findpos
13257 org-log-redeadline))
13258 (when repeater
13259 (save-excursion
13260 (org-back-to-heading t)
13261 (when (re-search-forward (concat org-deadline-string " "
13262 org-last-inserted-timestamp)
13263 (save-excursion
13264 (outline-next-heading) (point)) t)
13265 (goto-char (1- (match-end 0)))
13266 (insert " " repeater)
13267 (setq org-last-inserted-timestamp
13268 (concat (substring org-last-inserted-timestamp 0 -1)
13269 " " repeater
13270 (substring org-last-inserted-timestamp -1))))))
13271 (message "Deadline on %s" org-last-inserted-timestamp))))))
13273 (defun org-schedule (arg &optional time)
13274 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13275 With one universal prefix argument, remove any scheduling date from the item.
13276 With two universal prefix arguments, prompt for a delay cookie.
13277 With argument TIME, scheduled at the corresponding date. TIME can
13278 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13279 (interactive "P")
13280 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13281 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13282 'region-start-level 'region))
13283 org-loop-over-headlines-in-active-region)
13284 (org-map-entries
13285 `(org-schedule ',arg ,time)
13286 org-loop-over-headlines-in-active-region
13287 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13288 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13289 (old-date-time (if old-date (org-time-string-to-time old-date)))
13290 (repeater (and old-date
13291 (string-match
13292 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13293 old-date)
13294 (match-string 1 old-date))))
13295 (cond
13296 ((equal arg '(4))
13297 (progn
13298 (when (and old-date org-log-reschedule)
13299 (org-add-log-setup 'delschedule nil old-date 'findpos
13300 org-log-reschedule))
13301 (org-remove-timestamp-with-keyword org-scheduled-string)
13302 (message "Item is no longer scheduled.")))
13303 ((equal arg '(16))
13304 (save-excursion
13305 (org-back-to-heading t)
13306 (if (re-search-forward
13307 org-scheduled-time-regexp
13308 (save-excursion (outline-next-heading) (point)) t)
13309 (let* ((rpl0 (match-string 1))
13310 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13311 (replace-match
13312 (concat org-scheduled-string
13313 " <" rpl
13314 (format " -%dd"
13315 (abs
13316 (- (time-to-days
13317 (save-match-data
13318 (org-read-date nil t nil "Delay until" old-date-time)))
13319 (time-to-days old-date-time))))
13320 ">") t t))
13321 (user-error "No scheduled information to update"))))
13323 (org-add-planning-info 'scheduled time 'closed)
13324 (when (and old-date org-log-reschedule
13325 (not (equal old-date
13326 (substring org-last-inserted-timestamp 1 -1))))
13327 (org-add-log-setup 'reschedule nil old-date 'findpos
13328 org-log-reschedule))
13329 (when repeater
13330 (save-excursion
13331 (org-back-to-heading t)
13332 (when (re-search-forward (concat org-scheduled-string " "
13333 org-last-inserted-timestamp)
13334 (save-excursion
13335 (outline-next-heading) (point)) t)
13336 (goto-char (1- (match-end 0)))
13337 (insert " " repeater)
13338 (setq org-last-inserted-timestamp
13339 (concat (substring org-last-inserted-timestamp 0 -1)
13340 " " repeater
13341 (substring org-last-inserted-timestamp -1))))))
13342 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13344 (defun org-get-scheduled-time (pom &optional inherit)
13345 "Get the scheduled time as a time tuple, of a format suitable
13346 for calling org-schedule with, or if there is no scheduling,
13347 returns nil."
13348 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13349 (when time
13350 (apply 'encode-time (org-parse-time-string time)))))
13352 (defun org-get-deadline-time (pom &optional inherit)
13353 "Get the deadline as a time tuple, of a format suitable for
13354 calling org-deadline with, or if there is no scheduling, returns
13355 nil."
13356 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13357 (when time
13358 (apply 'encode-time (org-parse-time-string time)))))
13360 (defun org-remove-timestamp-with-keyword (keyword)
13361 "Remove all time stamps with KEYWORD in the current entry."
13362 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13363 beg)
13364 (save-excursion
13365 (org-back-to-heading t)
13366 (setq beg (point))
13367 (outline-next-heading)
13368 (while (re-search-backward re beg t)
13369 (replace-match "")
13370 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13371 (equal (char-before) ?\ ))
13372 (backward-delete-char 1)
13373 (if (string-match "^[ \t]*$" (buffer-substring
13374 (point-at-bol) (point-at-eol)))
13375 (delete-region (point-at-bol)
13376 (min (point-max) (1+ (point-at-eol))))))))))
13378 (defvar org-time-was-given) ; dynamically scoped parameter
13379 (defvar org-end-time-was-given) ; dynamically scoped parameter
13381 (defun org-add-planning-info (what &optional time &rest remove)
13382 "Insert new timestamp with keyword in the line directly after the headline.
13383 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13384 If non is given, the user is prompted for a date.
13385 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13386 be removed."
13387 (interactive)
13388 (let (org-time-was-given org-end-time-was-given ts
13389 end default-time default-input)
13391 (catch 'exit
13392 (when (and (memq what '(scheduled deadline))
13393 (or (not time)
13394 (and (stringp time)
13395 (string-match "^[-+]+[0-9]" time))))
13396 ;; Try to get a default date/time from existing timestamp
13397 (save-excursion
13398 (org-back-to-heading t)
13399 (setq end (save-excursion (outline-next-heading) (point)))
13400 (when (re-search-forward (if (eq what 'scheduled)
13401 org-scheduled-time-regexp
13402 org-deadline-time-regexp)
13403 end t)
13404 (setq ts (match-string 1)
13405 default-time
13406 (apply 'encode-time (org-parse-time-string ts))
13407 default-input (and ts (org-get-compact-tod ts))))))
13408 (when what
13409 (setq time
13410 (if (stringp time)
13411 ;; This is a string (relative or absolute), set proper date
13412 (apply 'encode-time
13413 (org-read-date-analyze
13414 time default-time (decode-time default-time)))
13415 ;; If necessary, get the time from the user
13416 (or time (org-read-date nil 'to-time nil nil
13417 default-time default-input)))))
13419 (when (and org-insert-labeled-timestamps-at-point
13420 (member what '(scheduled deadline)))
13421 (insert
13422 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13423 (org-insert-time-stamp time org-time-was-given
13424 nil nil nil (list org-end-time-was-given))
13425 (setq what nil))
13426 (save-excursion
13427 (save-restriction
13428 (let (col list elt ts buffer-invisibility-spec)
13429 (org-back-to-heading t)
13430 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13431 (goto-char (match-end 1))
13432 (setq col (current-column))
13433 (goto-char (match-end 0))
13434 (if (eobp) (insert "\n") (forward-char 1))
13435 (when (and (not what)
13436 (not (looking-at
13437 (concat "[ \t]*"
13438 org-keyword-time-not-clock-regexp))))
13439 ;; Nothing to add, nothing to remove...... :-)
13440 (throw 'exit nil))
13441 (if (and (not (looking-at org-outline-regexp))
13442 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13443 "[^\r\n]*"))
13444 (not (equal (match-string 1) org-clock-string)))
13445 (narrow-to-region (match-beginning 0) (match-end 0))
13446 (insert-before-markers "\n")
13447 (backward-char 1)
13448 (narrow-to-region (point) (point))
13449 (and org-adapt-indentation (org-indent-to-column col)))
13450 ;; Check if we have to remove something.
13451 (setq list (cons what remove))
13452 (while list
13453 (setq elt (pop list))
13454 (when (or (and (eq elt 'scheduled)
13455 (re-search-forward org-scheduled-time-regexp nil t))
13456 (and (eq elt 'deadline)
13457 (re-search-forward org-deadline-time-regexp nil t))
13458 (and (eq elt 'closed)
13459 (re-search-forward org-closed-time-regexp nil t)))
13460 (replace-match "")
13461 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13462 (and (looking-at "[ \t]+") (replace-match ""))
13463 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13464 (when what
13465 (insert
13466 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13467 (cond ((eq what 'scheduled) org-scheduled-string)
13468 ((eq what 'deadline) org-deadline-string)
13469 ((eq what 'closed) org-closed-string))
13470 " ")
13471 (setq ts (org-insert-time-stamp
13472 time
13473 (or org-time-was-given
13474 (and (eq what 'closed) org-log-done-with-time))
13475 (eq what 'closed)
13476 nil nil (list org-end-time-was-given)))
13477 (insert
13478 (if (not (or (bolp) (eq (char-before) ?\ )
13479 (memq (char-after) '(32 10))
13480 (eobp))) " " ""))
13481 (end-of-line 1))
13482 (goto-char (point-min))
13483 (widen)
13484 (if (and (looking-at "[ \t]*\n")
13485 (equal (char-before) ?\n))
13486 (delete-region (1- (point)) (point-at-eol)))
13487 ts))))))
13489 (defvar org-log-note-marker (make-marker))
13490 (defvar org-log-note-purpose nil)
13491 (defvar org-log-note-state nil)
13492 (defvar org-log-note-previous-state nil)
13493 (defvar org-log-note-how nil)
13494 (defvar org-log-note-extra nil)
13495 (defvar org-log-note-window-configuration nil)
13496 (defvar org-log-note-return-to (make-marker))
13497 (defvar org-log-note-effective-time nil
13498 "Remembered current time so that dynamically scoped
13499 `org-extend-today-until' affects tha timestamps in state change
13500 log")
13502 (defvar org-log-post-message nil
13503 "Message to be displayed after a log note has been stored.
13504 The auto-repeater uses this.")
13506 (defun org-add-note ()
13507 "Add a note to the current entry.
13508 This is done in the same way as adding a state change note."
13509 (interactive)
13510 (org-add-log-setup 'note nil nil 'findpos nil))
13512 (defvar org-property-end-re)
13513 (defun org-add-log-setup (&optional purpose state prev-state
13514 findpos how extra)
13515 "Set up the post command hook to take a note.
13516 If this is about to TODO state change, the new state is expected in STATE.
13517 When FINDPOS is non-nil, find the correct position for the note in
13518 the current entry. If not, assume that it can be inserted at point.
13519 HOW is an indicator what kind of note should be created.
13520 EXTRA is additional text that will be inserted into the notes buffer."
13521 (let* ((org-log-into-drawer (org-log-into-drawer))
13522 (drawer (cond ((stringp org-log-into-drawer)
13523 org-log-into-drawer)
13524 (org-log-into-drawer "LOGBOOK"))))
13525 (save-restriction
13526 (save-excursion
13527 (when findpos
13528 (org-back-to-heading t)
13529 (narrow-to-region (point) (save-excursion
13530 (outline-next-heading) (point)))
13531 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13532 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13533 "[^\r\n]*\\)?"))
13534 (goto-char (match-end 0))
13535 (cond
13536 (drawer
13537 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13538 nil t)
13539 (progn
13540 (goto-char (match-end 0))
13541 (or org-log-states-order-reversed
13542 (and (re-search-forward org-property-end-re nil t)
13543 (goto-char (1- (match-beginning 0))))))
13544 (insert "\n:" drawer ":\n:END:")
13545 (beginning-of-line 0)
13546 (org-indent-line)
13547 (beginning-of-line 2)
13548 (org-indent-line)
13549 (end-of-line 0)))
13550 ((and org-log-state-notes-insert-after-drawers
13551 (save-excursion
13552 (forward-line) (looking-at org-drawer-regexp)))
13553 (forward-line)
13554 (while (looking-at org-drawer-regexp)
13555 (goto-char (match-end 0))
13556 (re-search-forward org-property-end-re (point-max) t)
13557 (forward-line))
13558 (forward-line -1)))
13559 (unless org-log-states-order-reversed
13560 (and (= (char-after) ?\n) (forward-char 1))
13561 (org-skip-over-state-notes)
13562 (skip-chars-backward " \t\n\r")))
13563 (move-marker org-log-note-marker (point))
13564 (setq org-log-note-purpose purpose
13565 org-log-note-state state
13566 org-log-note-previous-state prev-state
13567 org-log-note-how how
13568 org-log-note-extra extra
13569 org-log-note-effective-time (org-current-effective-time))
13570 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13572 (defun org-skip-over-state-notes ()
13573 "Skip past the list of State notes in an entry."
13574 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13575 (when (ignore-errors (goto-char (org-in-item-p)))
13576 (let* ((struct (org-list-struct))
13577 (prevs (org-list-prevs-alist struct)))
13578 (while (looking-at "[ \t]*- State")
13579 (goto-char (or (org-list-get-next-item (point) struct prevs)
13580 (org-list-get-item-end (point) struct)))))))
13582 (defun org-add-log-note (&optional purpose)
13583 "Pop up a window for taking a note, and add this note later at point."
13584 (remove-hook 'post-command-hook 'org-add-log-note)
13585 (setq org-log-note-window-configuration (current-window-configuration))
13586 (delete-other-windows)
13587 (move-marker org-log-note-return-to (point))
13588 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13589 (goto-char org-log-note-marker)
13590 (org-switch-to-buffer-other-window "*Org Note*")
13591 (erase-buffer)
13592 (if (memq org-log-note-how '(time state))
13593 (let (current-prefix-arg) (org-store-log-note))
13594 (let ((org-inhibit-startup t)) (org-mode))
13595 (insert (format "# Insert note for %s.
13596 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13597 (cond
13598 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13599 ((eq org-log-note-purpose 'done) "closed todo item")
13600 ((eq org-log-note-purpose 'state)
13601 (format "state change from \"%s\" to \"%s\""
13602 (or org-log-note-previous-state "")
13603 (or org-log-note-state "")))
13604 ((eq org-log-note-purpose 'reschedule)
13605 "rescheduling")
13606 ((eq org-log-note-purpose 'delschedule)
13607 "no longer scheduled")
13608 ((eq org-log-note-purpose 'redeadline)
13609 "changing deadline")
13610 ((eq org-log-note-purpose 'deldeadline)
13611 "removing deadline")
13612 ((eq org-log-note-purpose 'refile)
13613 "refiling")
13614 ((eq org-log-note-purpose 'note)
13615 "this entry")
13616 (t (error "This should not happen")))))
13617 (if org-log-note-extra (insert org-log-note-extra))
13618 (org-set-local 'org-finish-function 'org-store-log-note)
13619 (run-hooks 'org-log-buffer-setup-hook)))
13621 (defvar org-note-abort nil) ; dynamically scoped
13622 (defun org-store-log-note ()
13623 "Finish taking a log note, and insert it to where it belongs."
13624 (let ((txt (buffer-string)))
13625 (kill-buffer (current-buffer))
13626 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13627 lines ind bul)
13628 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13629 (setq txt (replace-match "" t t txt)))
13630 (if (string-match "\\s-+\\'" txt)
13631 (setq txt (replace-match "" t t txt)))
13632 (setq lines (org-split-string txt "\n"))
13633 (when (and note (string-match "\\S-" note))
13634 (setq note
13635 (org-replace-escapes
13636 note
13637 (list (cons "%u" (user-login-name))
13638 (cons "%U" user-full-name)
13639 (cons "%t" (format-time-string
13640 (org-time-stamp-format 'long 'inactive)
13641 org-log-note-effective-time))
13642 (cons "%T" (format-time-string
13643 (org-time-stamp-format 'long nil)
13644 org-log-note-effective-time))
13645 (cons "%d" (format-time-string
13646 (org-time-stamp-format nil 'inactive)
13647 org-log-note-effective-time))
13648 (cons "%D" (format-time-string
13649 (org-time-stamp-format nil nil)
13650 org-log-note-effective-time))
13651 (cons "%s" (if org-log-note-state
13652 (concat "\"" org-log-note-state "\"")
13653 ""))
13654 (cons "%S" (if org-log-note-previous-state
13655 (concat "\"" org-log-note-previous-state "\"")
13656 "\"\"")))))
13657 (if lines (setq note (concat note " \\\\")))
13658 (push note lines))
13659 (when (or current-prefix-arg org-note-abort)
13660 (when org-log-into-drawer
13661 (org-remove-empty-drawer-at org-log-note-marker))
13662 (setq lines nil))
13663 (when lines
13664 (with-current-buffer (marker-buffer org-log-note-marker)
13665 (save-excursion
13666 (goto-char org-log-note-marker)
13667 (move-marker org-log-note-marker nil)
13668 (end-of-line 1)
13669 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13670 (setq ind (save-excursion
13671 (if (ignore-errors (goto-char (org-in-item-p)))
13672 (let ((struct (org-list-struct)))
13673 (org-list-get-ind
13674 (org-list-get-top-point struct) struct))
13675 (skip-chars-backward " \r\t\n")
13676 (cond
13677 ((and (org-at-heading-p)
13678 org-adapt-indentation)
13679 (1+ (org-current-level)))
13680 ((org-at-heading-p) 0)
13681 (t (org-get-indentation))))))
13682 (setq bul (org-list-bullet-string "-"))
13683 (org-indent-line-to ind)
13684 (insert bul (pop lines))
13685 (let ((ind-body (+ (length bul) ind)))
13686 (while lines
13687 (insert "\n")
13688 (org-indent-line-to ind-body)
13689 (insert (pop lines))))
13690 (message "Note stored")
13691 (org-back-to-heading t)
13692 (org-cycle-hide-drawers 'children))
13693 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13694 ;; from within `org-add-log-note' because `buffer-undo-list'
13695 ;; is then modified outside of `org-with-remote-undo'.
13696 (when (eq this-command 'org-agenda-todo)
13697 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13698 ;; Don't add undo information when called from `org-agenda-todo'
13699 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13700 (set-window-configuration org-log-note-window-configuration)
13701 (with-current-buffer (marker-buffer org-log-note-return-to)
13702 (goto-char org-log-note-return-to))
13703 (move-marker org-log-note-return-to nil)
13704 (and org-log-post-message (message "%s" org-log-post-message))))
13706 (defun org-remove-empty-drawer-at (pos)
13707 "Remove an empty drawer at position POS.
13708 POS may also be a marker."
13709 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13710 (org-with-wide-buffer
13711 (goto-char pos)
13712 (let ((drawer (org-element-at-point)))
13713 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13714 (not (org-element-property :contents-begin drawer)))
13715 (delete-region (org-element-property :begin drawer)
13716 (progn (goto-char (org-element-property :end drawer))
13717 (skip-chars-backward " \r\t\n")
13718 (forward-line)
13719 (point))))))))
13721 (defvar org-ts-type nil)
13722 (defun org-sparse-tree (&optional arg type)
13723 "Create a sparse tree, prompt for the details.
13724 This command can create sparse trees. You first need to select the type
13725 of match used to create the tree:
13727 t Show all TODO entries.
13728 T Show entries with a specific TODO keyword.
13729 m Show entries selected by a tags/property match.
13730 p Enter a property name and its value (both with completion on existing
13731 names/values) and show entries with that property.
13732 r Show entries matching a regular expression (`/' can be used as well).
13733 b Show deadlines and scheduled items before a date.
13734 a Show deadlines and scheduled items after a date.
13735 d Show deadlines due within `org-deadline-warning-days'.
13736 D Show deadlines and scheduled items between a date range."
13737 (interactive "P")
13738 (setq type (or type org-sparse-tree-default-date-type))
13739 (setq org-ts-type type)
13740 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty
13741 [d]eadlines [b]efore-date [a]fter-date [D]ates range
13742 [c]ycle through date types: %s"
13743 (case type
13744 (all "all timestamps")
13745 (scheduled "only scheduled")
13746 (deadline "only deadline")
13747 (active "only active timestamps")
13748 (inactive "only inactive timestamps")
13749 (scheduled-or-deadline "scheduled/deadline")
13750 (closed "with a closed time-stamp")
13751 (otherwise "scheduled/deadline")))
13752 (let ((answer (read-char-exclusive)))
13753 (case answer
13755 (org-sparse-tree
13757 (cadr (memq type '(scheduled-or-deadline all scheduled deadline active
13758 inactive closed)))))
13759 (?d (call-interactively 'org-check-deadlines))
13760 (?b (call-interactively 'org-check-before-date))
13761 (?a (call-interactively 'org-check-after-date))
13762 (?D (call-interactively 'org-check-dates-range))
13763 (?t (call-interactively 'org-show-todo-tree))
13764 (?T (org-show-todo-tree '(4)))
13765 (?m (call-interactively 'org-match-sparse-tree))
13766 ((?p ?P)
13767 (let* ((kwd (org-icompleting-read
13768 "Property: " (mapcar 'list (org-buffer-property-keys))))
13769 (value (org-icompleting-read
13770 "Value: " (mapcar 'list (org-property-values kwd)))))
13771 (unless (string-match "\\`{.*}\\'" value)
13772 (setq value (concat "\"" value "\"")))
13773 (org-match-sparse-tree arg (concat kwd "=" value))))
13774 ((?r ?R ?/) (call-interactively 'org-occur))
13775 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13777 (defvar org-occur-highlights nil
13778 "List of overlays used for occur matches.")
13779 (make-variable-buffer-local 'org-occur-highlights)
13780 (defvar org-occur-parameters nil
13781 "Parameters of the active org-occur calls.
13782 This is a list, each call to org-occur pushes as cons cell,
13783 containing the regular expression and the callback, onto the list.
13784 The list can contain several entries if `org-occur' has been called
13785 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13786 will only contain one set of parameters. When the highlights are
13787 removed (for example with `C-c C-c', or with the next edit (depending
13788 on `org-remove-highlights-with-change'), this variable is emptied
13789 as well.")
13790 (make-variable-buffer-local 'org-occur-parameters)
13792 (defun org-occur (regexp &optional keep-previous callback)
13793 "Make a compact tree which shows all matches of REGEXP.
13794 The tree will show the lines where the regexp matches, and all higher
13795 headlines above the match. It will also show the heading after the match,
13796 to make sure editing the matching entry is easy.
13797 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13798 call to `org-occur' will be kept, to allow stacking of calls to this
13799 command.
13800 If CALLBACK is non-nil, it is a function which is called to confirm
13801 that the match should indeed be shown."
13802 (interactive "sRegexp: \nP")
13803 (when (equal regexp "")
13804 (user-error "Regexp cannot be empty"))
13805 (unless keep-previous
13806 (org-remove-occur-highlights nil nil t))
13807 (push (cons regexp callback) org-occur-parameters)
13808 (let ((cnt 0))
13809 (save-excursion
13810 (goto-char (point-min))
13811 (if (or (not keep-previous) ; do not want to keep
13812 (not org-occur-highlights)) ; no previous matches
13813 ;; hide everything
13814 (org-overview))
13815 (while (re-search-forward regexp nil t)
13816 (when (or (not callback)
13817 (save-match-data (funcall callback)))
13818 (setq cnt (1+ cnt))
13819 (when org-highlight-sparse-tree-matches
13820 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13821 (org-show-context 'occur-tree))))
13822 (when org-remove-highlights-with-change
13823 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13824 nil 'local))
13825 (unless org-sparse-tree-open-archived-trees
13826 (org-hide-archived-subtrees (point-min) (point-max)))
13827 (run-hooks 'org-occur-hook)
13828 (if (org-called-interactively-p 'interactive)
13829 (message "%d match(es) for regexp %s" cnt regexp))
13830 cnt))
13832 (defun org-occur-next-match (&optional n reset)
13833 "Function for `next-error-function' to find sparse tree matches.
13834 N is the number of matches to move, when negative move backwards.
13835 RESET is entirely ignored - this function always goes back to the
13836 starting point when no match is found."
13837 (let* ((limit (if (< n 0) (point-min) (point-max)))
13838 (search-func (if (< n 0)
13839 'previous-single-char-property-change
13840 'next-single-char-property-change))
13841 (n (abs n))
13842 (pos (point))
13844 (catch 'exit
13845 (while (setq p1 (funcall search-func (point) 'org-type))
13846 (when (equal p1 limit)
13847 (goto-char pos)
13848 (user-error "No more matches"))
13849 (when (equal (get-char-property p1 'org-type) 'org-occur)
13850 (setq n (1- n))
13851 (when (= n 0)
13852 (goto-char p1)
13853 (throw 'exit (point))))
13854 (goto-char p1))
13855 (goto-char p1)
13856 (user-error "No more matches"))))
13858 (defun org-show-context (&optional key)
13859 "Make sure point and context are visible.
13860 How much context is shown depends upon the variables
13861 `org-show-hierarchy-above', `org-show-following-heading',
13862 `org-show-entry-below' and `org-show-siblings'."
13863 (let ((heading-p (org-at-heading-p t))
13864 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13865 (following-p (org-get-alist-option org-show-following-heading key))
13866 (entry-p (org-get-alist-option org-show-entry-below key))
13867 (siblings-p (org-get-alist-option org-show-siblings key)))
13868 ;; Show heading or entry text
13869 (if (and heading-p (not entry-p))
13870 (org-flag-heading nil) ; only show the heading
13871 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13872 (org-show-hidden-entry))) ; show entire entry
13873 (when following-p
13874 ;; Show next sibling, or heading below text
13875 (save-excursion
13876 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13877 (org-flag-heading nil))))
13878 (when siblings-p (org-show-siblings))
13879 (when hierarchy-p
13880 ;; show all higher headings, possibly with siblings
13881 (save-excursion
13882 (while (and (ignore-errors (progn (org-up-heading-all 1) t))
13883 (not (bobp)))
13884 (org-flag-heading nil)
13885 (when siblings-p (org-show-siblings)))))
13886 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13888 (defvar org-reveal-start-hook nil
13889 "Hook run before revealing a location.")
13891 (defun org-reveal (&optional siblings)
13892 "Show current entry, hierarchy above it, and the following headline.
13893 This can be used to show a consistent set of context around locations
13894 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13895 not t for the search context.
13897 With optional argument SIBLINGS, on each level of the hierarchy all
13898 siblings are shown. This repairs the tree structure to what it would
13899 look like when opened with hierarchical calls to `org-cycle'.
13900 With double optional argument \\[universal-argument] \\[universal-argument], \
13901 go to the parent and show the
13902 entire tree."
13903 (interactive "P")
13904 (run-hooks 'org-reveal-start-hook)
13905 (let ((org-show-hierarchy-above t)
13906 (org-show-following-heading t)
13907 (org-show-siblings (if siblings t org-show-siblings)))
13908 (org-show-context nil))
13909 (when (equal siblings '(16))
13910 (save-excursion
13911 (when (org-up-heading-safe)
13912 (org-show-subtree)
13913 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13915 (defun org-highlight-new-match (beg end)
13916 "Highlight from BEG to END and mark the highlight is an occur headline."
13917 (let ((ov (make-overlay beg end)))
13918 (overlay-put ov 'face 'secondary-selection)
13919 (overlay-put ov 'org-type 'org-occur)
13920 (push ov org-occur-highlights)))
13922 (defun org-remove-occur-highlights (&optional beg end noremove)
13923 "Remove the occur highlights from the buffer.
13924 BEG and END are ignored. If NOREMOVE is nil, remove this function
13925 from the `before-change-functions' in the current buffer."
13926 (interactive)
13927 (unless org-inhibit-highlight-removal
13928 (mapc 'delete-overlay org-occur-highlights)
13929 (setq org-occur-highlights nil)
13930 (setq org-occur-parameters nil)
13931 (unless noremove
13932 (remove-hook 'before-change-functions
13933 'org-remove-occur-highlights 'local))))
13935 ;;;; Priorities
13937 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13938 "Regular expression matching the priority indicator.")
13940 (defvar org-remove-priority-next-time nil)
13942 (defun org-priority-up ()
13943 "Increase the priority of the current item."
13944 (interactive)
13945 (org-priority 'up))
13947 (defun org-priority-down ()
13948 "Decrease the priority of the current item."
13949 (interactive)
13950 (org-priority 'down))
13952 (defun org-priority (&optional action show)
13953 "Change the priority of an item.
13954 ACTION can be `set', `up', `down', or a character."
13955 (interactive "P")
13956 (if (equal action '(4))
13957 (org-show-priority)
13958 (unless org-enable-priority-commands
13959 (user-error "Priority commands are disabled"))
13960 (setq action (or action 'set))
13961 (let (current new news have remove)
13962 (save-excursion
13963 (org-back-to-heading t)
13964 (if (looking-at org-priority-regexp)
13965 (setq current (string-to-char (match-string 2))
13966 have t))
13967 (cond
13968 ((eq action 'remove)
13969 (setq remove t new ?\ ))
13970 ((or (eq action 'set)
13971 (if (featurep 'xemacs) (characterp action) (integerp action)))
13972 (if (not (eq action 'set))
13973 (setq new action)
13974 (message "Priority %c-%c, SPC to remove: "
13975 org-highest-priority org-lowest-priority)
13976 (save-match-data
13977 (setq new (read-char-exclusive))))
13978 (if (and (= (upcase org-highest-priority) org-highest-priority)
13979 (= (upcase org-lowest-priority) org-lowest-priority))
13980 (setq new (upcase new)))
13981 (cond ((equal new ?\ ) (setq remove t))
13982 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13983 (user-error "Priority must be between `%c' and `%c'"
13984 org-highest-priority org-lowest-priority))))
13985 ((eq action 'up)
13986 (setq new (if have
13987 (1- current) ; normal cycling
13988 ;; last priority was empty
13989 (if (eq last-command this-command)
13990 org-lowest-priority ; wrap around empty to lowest
13991 ;; default
13992 (if org-priority-start-cycle-with-default
13993 org-default-priority
13994 (1- org-default-priority))))))
13995 ((eq action 'down)
13996 (setq new (if have
13997 (1+ current) ; normal cycling
13998 ;; last priority was empty
13999 (if (eq last-command this-command)
14000 org-highest-priority ; wrap around empty to highest
14001 ;; default
14002 (if org-priority-start-cycle-with-default
14003 org-default-priority
14004 (1+ org-default-priority))))))
14005 (t (user-error "Invalid action")))
14006 (if (or (< (upcase new) org-highest-priority)
14007 (> (upcase new) org-lowest-priority))
14008 (if (and (memq action '(up down))
14009 (not have) (not (eq last-command this-command)))
14010 ;; `new' is from default priority
14011 (error
14012 "The default can not be set, see `org-default-priority' why")
14013 ;; normal cycling: `new' is beyond highest/lowest priority
14014 ;; and is wrapped around to the empty priority
14015 (setq remove t)))
14016 (setq news (format "%c" new))
14017 (if have
14018 (if remove
14019 (replace-match "" t t nil 1)
14020 (replace-match news t t nil 2))
14021 (if remove
14022 (user-error "No priority cookie found in line")
14023 (let ((case-fold-search nil))
14024 (looking-at org-todo-line-regexp))
14025 (if (match-end 2)
14026 (progn
14027 (goto-char (match-end 2))
14028 (insert " [#" news "]"))
14029 (goto-char (match-beginning 3))
14030 (insert "[#" news "] "))))
14031 (org-set-tags nil 'align))
14032 (if remove
14033 (message "Priority removed")
14034 (message "Priority of current item set to %s" news)))))
14036 (defun org-show-priority ()
14037 "Show the priority of the current item.
14038 This priority is composed of the main priority given with the [#A] cookies,
14039 and by additional input from the age of a schedules or deadline entry."
14040 (interactive)
14041 (let ((pri (if (eq major-mode 'org-agenda-mode)
14042 (org-get-at-bol 'priority)
14043 (save-excursion
14044 (save-match-data
14045 (beginning-of-line)
14046 (and (looking-at org-heading-regexp)
14047 (org-get-priority (match-string 0))))))))
14048 (message "Priority is %d" (if pri pri -1000))))
14050 (defun org-get-priority (s)
14051 "Find priority cookie and return priority."
14052 (save-match-data
14053 (if (functionp org-get-priority-function)
14054 (funcall org-get-priority-function)
14055 (if (not (string-match org-priority-regexp s))
14056 (* 1000 (- org-lowest-priority org-default-priority))
14057 (* 1000 (- org-lowest-priority
14058 (string-to-char (match-string 2 s))))))))
14060 ;;;; Tags
14062 (defvar org-agenda-archives-mode)
14063 (defvar org-map-continue-from nil
14064 "Position from where mapping should continue.
14065 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14067 (defvar org-scanner-tags nil
14068 "The current tag list while the tags scanner is running.")
14069 (defvar org-trust-scanner-tags nil
14070 "Should `org-get-tags-at' use the tags for the scanner.
14071 This is for internal dynamical scoping only.
14072 When this is non-nil, the function `org-get-tags-at' will return the value
14073 of `org-scanner-tags' instead of building the list by itself. This
14074 can lead to large speed-ups when the tags scanner is used in a file with
14075 many entries, and when the list of tags is retrieved, for example to
14076 obtain a list of properties. Building the tags list for each entry in such
14077 a file becomes an N^2 operation - but with this variable set, it scales
14078 as N.")
14080 (defun org-scan-tags (action matcher todo-only &optional start-level)
14081 "Sca headline tags with inheritance and produce output ACTION.
14083 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14084 or `agenda' to produce an entry list for an agenda view. It can also be
14085 a Lisp form or a function that should be called at each matched headline, in
14086 this case the return value is a list of all return values from these calls.
14088 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
14089 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
14090 only lines with a not-done TODO keyword are included in the output.
14091 This should be the same variable that was scoped into
14092 and set by `org-make-tags-matcher' when it constructed MATCHER.
14094 START-LEVEL can be a string with asterisks, reducing the scope to
14095 headlines matching this string."
14096 (require 'org-agenda)
14097 (let* ((re (concat "^"
14098 (if start-level
14099 ;; Get the correct level to match
14100 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14101 org-outline-regexp)
14102 " *\\(\\<\\("
14103 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
14104 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
14105 (props (list 'face 'default
14106 'done-face 'org-agenda-done
14107 'undone-face 'default
14108 'mouse-face 'highlight
14109 'org-not-done-regexp org-not-done-regexp
14110 'org-todo-regexp org-todo-regexp
14111 'org-complex-heading-regexp org-complex-heading-regexp
14112 'help-echo
14113 (format "mouse-2 or RET jump to org file %s"
14114 (abbreviate-file-name
14115 (or (buffer-file-name (buffer-base-buffer))
14116 (buffer-name (buffer-base-buffer)))))))
14117 (org-map-continue-from nil)
14118 lspos tags tags-list
14119 (tags-alist (list (cons 0 org-file-tags)))
14120 (llast 0) rtn rtn1 level category i txt
14121 todo marker entry priority)
14122 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
14123 (setq action (list 'lambda nil action)))
14124 (save-excursion
14125 (goto-char (point-min))
14126 (when (eq action 'sparse-tree)
14127 (org-overview)
14128 (org-remove-occur-highlights))
14129 (while (let (case-fold-search)
14130 (re-search-forward re nil t))
14131 (setq org-map-continue-from nil)
14132 (catch :skip
14133 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
14134 tags (if (match-end 4) (org-match-string-no-properties 4)))
14135 (goto-char (setq lspos (match-beginning 0)))
14136 (setq level (org-reduced-level (org-outline-level))
14137 category (org-get-category))
14138 (setq i llast llast level)
14139 ;; remove tag lists from same and sublevels
14140 (while (>= i level)
14141 (when (setq entry (assoc i tags-alist))
14142 (setq tags-alist (delete entry tags-alist)))
14143 (setq i (1- i)))
14144 ;; add the next tags
14145 (when tags
14146 (setq tags (org-split-string tags ":")
14147 tags-alist
14148 (cons (cons level tags) tags-alist)))
14149 ;; compile tags for current headline
14150 (setq tags-list
14151 (if org-use-tag-inheritance
14152 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14153 tags)
14154 org-scanner-tags tags-list)
14155 (when org-use-tag-inheritance
14156 (setcdr (car tags-alist)
14157 (mapcar (lambda (x)
14158 (setq x (copy-sequence x))
14159 (org-add-prop-inherited x))
14160 (cdar tags-alist))))
14161 (when (and tags org-use-tag-inheritance
14162 (or (not (eq t org-use-tag-inheritance))
14163 org-tags-exclude-from-inheritance))
14164 ;; selective inheritance, remove uninherited ones
14165 (setcdr (car tags-alist)
14166 (org-remove-uninherited-tags (cdar tags-alist))))
14167 (when (and
14169 ;; eval matcher only when the todo condition is OK
14170 (and (or (not todo-only) (member todo org-not-done-keywords))
14171 (let ((case-fold-search t) (org-trust-scanner-tags t))
14172 (eval matcher)))
14174 ;; Call the skipper, but return t if it does not skip,
14175 ;; so that the `and' form continues evaluating
14176 (progn
14177 (unless (eq action 'sparse-tree) (org-agenda-skip))
14180 ;; Check if timestamps are deselecting this entry
14181 (or (not todo-only)
14182 (and (member todo org-not-done-keywords)
14183 (or (not org-agenda-tags-todo-honor-ignore-options)
14184 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14186 ;; select this headline
14187 (cond
14188 ((eq action 'sparse-tree)
14189 (and org-highlight-sparse-tree-matches
14190 (org-get-heading) (match-end 0)
14191 (org-highlight-new-match
14192 (match-beginning 1) (match-end 1)))
14193 (org-show-context 'tags-tree))
14194 ((eq action 'agenda)
14195 (setq txt (org-agenda-format-item
14197 (concat
14198 (if (eq org-tags-match-list-sublevels 'indented)
14199 (make-string (1- level) ?.) "")
14200 (org-get-heading))
14201 level category
14202 tags-list)
14203 priority (org-get-priority txt))
14204 (goto-char lspos)
14205 (setq marker (org-agenda-new-marker))
14206 (org-add-props txt props
14207 'org-marker marker 'org-hd-marker marker 'org-category category
14208 'todo-state todo
14209 'priority priority 'type "tagsmatch")
14210 (push txt rtn))
14211 ((functionp action)
14212 (setq org-map-continue-from nil)
14213 (save-excursion
14214 (setq rtn1 (funcall action))
14215 (push rtn1 rtn)))
14216 (t (user-error "Invalid action")))
14218 ;; if we are to skip sublevels, jump to end of subtree
14219 (unless org-tags-match-list-sublevels
14220 (org-end-of-subtree t)
14221 (backward-char 1))))
14222 ;; Get the correct position from where to continue
14223 (if org-map-continue-from
14224 (goto-char org-map-continue-from)
14225 (and (= (point) lspos) (end-of-line 1)))))
14226 (when (and (eq action 'sparse-tree)
14227 (not org-sparse-tree-open-archived-trees))
14228 (org-hide-archived-subtrees (point-min) (point-max)))
14229 (nreverse rtn)))
14231 (defun org-remove-uninherited-tags (tags)
14232 "Remove all tags that are not inherited from the list TAGS."
14233 (cond
14234 ((eq org-use-tag-inheritance t)
14235 (if org-tags-exclude-from-inheritance
14236 (org-delete-all org-tags-exclude-from-inheritance tags)
14237 tags))
14238 ((not org-use-tag-inheritance) nil)
14239 ((stringp org-use-tag-inheritance)
14240 (delq nil (mapcar
14241 (lambda (x)
14242 (if (and (string-match org-use-tag-inheritance x)
14243 (not (member x org-tags-exclude-from-inheritance)))
14244 x nil))
14245 tags)))
14246 ((listp org-use-tag-inheritance)
14247 (delq nil (mapcar
14248 (lambda (x)
14249 (if (member x org-use-tag-inheritance) x nil))
14250 tags)))))
14252 (defun org-match-sparse-tree (&optional todo-only match)
14253 "Create a sparse tree according to tags string MATCH.
14254 MATCH can contain positive and negative selection of tags, like
14255 \"+WORK+URGENT-WITHBOSS\".
14256 If optional argument TODO-ONLY is non-nil, only select lines that are
14257 also TODO lines."
14258 (interactive "P")
14259 (org-agenda-prepare-buffers (list (current-buffer)))
14260 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
14262 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14264 (defvar org-cached-props nil)
14265 (defun org-cached-entry-get (pom property)
14266 (if (or (eq t org-use-property-inheritance)
14267 (and (stringp org-use-property-inheritance)
14268 (string-match org-use-property-inheritance property))
14269 (and (listp org-use-property-inheritance)
14270 (member property org-use-property-inheritance)))
14271 ;; Caching is not possible, check it directly
14272 (org-entry-get pom property 'inherit)
14273 ;; Get all properties, so that we can do complicated checks easily
14274 (cdr (assoc property (or org-cached-props
14275 (setq org-cached-props
14276 (org-entry-properties pom)))))))
14278 (defun org-global-tags-completion-table (&optional files)
14279 "Return the list of all tags in all agenda buffer/files.
14280 Optional FILES argument is a list of files which can be used
14281 instead of the agenda files."
14282 (save-excursion
14283 (org-uniquify
14284 (delq nil
14285 (apply 'append
14286 (mapcar
14287 (lambda (file)
14288 (set-buffer (find-file-noselect file))
14289 (append (org-get-buffer-tags)
14290 (mapcar (lambda (x) (if (stringp (car-safe x))
14291 (list (car-safe x)) nil))
14292 org-tag-alist)))
14293 (if (and files (car files))
14294 files
14295 (org-agenda-files))))))))
14297 (defun org-make-tags-matcher (match)
14298 "Create the TAGS/TODO matcher form for the selection string MATCH.
14300 The variable `todo-only' is scoped dynamically into this function.
14301 It will be set to t if the matcher restricts matching to TODO entries,
14302 otherwise will not be touched.
14304 Returns a cons of the selection string MATCH and the constructed
14305 lisp form implementing the matcher. The matcher is to be evaluated
14306 at an Org entry, with point on the headline, and returns t if the
14307 entry matches the selection string MATCH. The returned lisp form
14308 references two variables with information about the entry, which
14309 must be bound around the form's evaluation: todo, the TODO keyword
14310 at the entry (or nil of none); and tags-list, the list of all tags
14311 at the entry including inherited ones. Additionally, the category
14312 of the entry (if any) must be specified as the text property
14313 'org-category on the headline.
14315 See also `org-scan-tags'.
14317 (declare (special todo-only))
14318 (unless (boundp 'todo-only)
14319 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14320 (unless match
14321 ;; Get a new match request, with completion against the global
14322 ;; tags table and the local tags in current buffer
14323 (let ((org-last-tags-completion-table
14324 (org-uniquify
14325 (delq nil (append (org-get-buffer-tags)
14326 (org-global-tags-completion-table))))))
14327 (setq match (org-completing-read-no-i
14328 "Match: " 'org-tags-completion-function nil nil nil
14329 'org-tags-history))))
14331 ;; Parse the string and create a lisp form
14332 (let ((match0 match)
14333 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14334 minus tag mm
14335 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14336 orterms term orlist re-p str-p level-p level-op time-p
14337 prop-p pn pv po gv rest (start 0) (ss 0))
14338 ;; Expand group tags
14339 (setq match (org-tags-expand match))
14341 ;; Check if there is a TODO part of this match, which would be the
14342 ;; part after a "/". TO make sure that this slash is not part of
14343 ;; a property value to be matched against, we also check that there
14344 ;; is no " after that slash.
14345 ;; First, find the last slash
14346 (while (string-match "/+" match ss)
14347 (setq start (match-beginning 0) ss (match-end 0)))
14348 (if (and (string-match "/+" match start)
14349 (not (save-match-data (string-match "\"" match start))))
14350 ;; match contains also a todo-matching request
14351 (progn
14352 (setq tagsmatch (substring match 0 (match-beginning 0))
14353 todomatch (substring match (match-end 0)))
14354 (if (string-match "^!" todomatch)
14355 (setq todo-only t todomatch (substring todomatch 1)))
14356 (if (string-match "^\\s-*$" todomatch)
14357 (setq todomatch nil)))
14358 ;; only matching tags
14359 (setq tagsmatch match todomatch nil))
14361 ;; Make the tags matcher
14362 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14363 (setq tagsmatcher t)
14364 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14365 (while (setq term (pop orterms))
14366 (while (and (equal (substring term -1) "\\") orterms)
14367 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14368 (while (string-match re term)
14369 (setq rest (substring term (match-end 0))
14370 minus (and (match-end 1)
14371 (equal (match-string 1 term) "-"))
14372 tag (save-match-data (replace-regexp-in-string
14373 "\\\\-" "-"
14374 (match-string 2 term)))
14375 re-p (equal (string-to-char tag) ?{)
14376 level-p (match-end 4)
14377 prop-p (match-end 5)
14378 mm (cond
14379 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14380 (level-p
14381 (setq level-op (org-op-to-function (match-string 3 term)))
14382 `(,level-op level ,(string-to-number
14383 (match-string 4 term))))
14384 (prop-p
14385 (setq pn (match-string 5 term)
14386 po (match-string 6 term)
14387 pv (match-string 7 term)
14388 re-p (equal (string-to-char pv) ?{)
14389 str-p (equal (string-to-char pv) ?\")
14390 time-p (save-match-data
14391 (string-match "^\"[[<].*[]>]\"$" pv))
14392 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14393 (if time-p (setq pv (org-matcher-time pv)))
14394 (setq po (org-op-to-function po (if time-p 'time str-p)))
14395 (cond
14396 ((equal pn "CATEGORY")
14397 (setq gv '(get-text-property (point) 'org-category)))
14398 ((equal pn "TODO")
14399 (setq gv 'todo))
14401 (setq gv `(org-cached-entry-get nil ,pn))))
14402 (if re-p
14403 (if (eq po 'org<>)
14404 `(not (string-match ,pv (or ,gv "")))
14405 `(string-match ,pv (or ,gv "")))
14406 (if str-p
14407 `(,po (or ,gv "") ,pv)
14408 `(,po (string-to-number (or ,gv ""))
14409 ,(string-to-number pv) ))))
14410 (t `(member ,tag tags-list)))
14411 mm (if minus (list 'not mm) mm)
14412 term rest)
14413 (push mm tagsmatcher))
14414 (push (if (> (length tagsmatcher) 1)
14415 (cons 'and tagsmatcher)
14416 (car tagsmatcher))
14417 orlist)
14418 (setq tagsmatcher nil))
14419 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14420 (setq tagsmatcher
14421 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14422 ;; Make the todo matcher
14423 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14424 (setq todomatcher t)
14425 (setq orterms (org-split-string todomatch "|") orlist nil)
14426 (while (setq term (pop orterms))
14427 (while (string-match re term)
14428 (setq minus (and (match-end 1)
14429 (equal (match-string 1 term) "-"))
14430 kwd (match-string 2 term)
14431 re-p (equal (string-to-char kwd) ?{)
14432 term (substring term (match-end 0))
14433 mm (if re-p
14434 `(string-match ,(substring kwd 1 -1) todo)
14435 (list 'equal 'todo kwd))
14436 mm (if minus (list 'not mm) mm))
14437 (push mm todomatcher))
14438 (push (if (> (length todomatcher) 1)
14439 (cons 'and todomatcher)
14440 (car todomatcher))
14441 orlist)
14442 (setq todomatcher nil))
14443 (setq todomatcher (if (> (length orlist) 1)
14444 (cons 'or orlist) (car orlist))))
14446 ;; Return the string and lisp forms of the matcher
14447 (setq matcher (if todomatcher
14448 (list 'and tagsmatcher todomatcher)
14449 tagsmatcher))
14450 (when todo-only
14451 (setq matcher (list 'and '(member todo org-not-done-keywords)
14452 matcher)))
14453 (cons match0 matcher)))
14455 (defun org-tags-expand (match &optional single-as-list downcased)
14456 "Expand group tags in MATCH.
14458 This replaces every group tag in MATCH with a regexp tag search.
14459 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14460 will be replaced like this:
14462 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14463 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14464 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14466 Replacing by a regexp preserves the structure of the match.
14467 E.g., this expansion
14469 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14471 will match anything tagged with \"Lab\" and \"Home\", or tagged
14472 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14474 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14475 assumed to be a single group tag, and the function will return
14476 the list of tags in this group.
14478 When DOWNCASE is non-nil, expand downcased TAGS."
14479 (if org-group-tags
14480 (let* ((case-fold-search t)
14481 (stable org-mode-syntax-table)
14482 (tal (or org-tag-groups-alist-for-agenda
14483 org-tag-groups-alist))
14484 (tal (if downcased
14485 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14486 (tml (mapcar 'car tal))
14487 (rtnmatch match) rpl)
14488 ;; @ and _ are allowed as word-components in tags
14489 (modify-syntax-entry ?@ "w" stable)
14490 (modify-syntax-entry ?_ "w" stable)
14491 (while (and tml
14492 (with-syntax-table stable
14493 (string-match
14494 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14495 (regexp-opt tml) "\\>\\)") rtnmatch)))
14496 (let* ((dir (match-string 1 rtnmatch))
14497 (tag (match-string 2 rtnmatch))
14498 (tag (if downcased (downcase tag) tag)))
14499 (setq tml (delete tag tml))
14500 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14501 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14502 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14503 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14504 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14505 (if single-as-list
14506 (or (reverse rpl) (list rtnmatch))
14507 rtnmatch))
14508 (if single-as-list (list (if downcased (downcase match) match))
14509 match)))
14511 (defun org-op-to-function (op &optional stringp)
14512 "Turn an operator into the appropriate function."
14513 (setq op
14514 (cond
14515 ((equal op "<" ) '(< string< org-time<))
14516 ((equal op ">" ) '(> org-string> org-time>))
14517 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14518 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14519 ((member op '("=" "==")) '(= string= org-time=))
14520 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14521 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14523 (defun org<> (a b) (not (= a b)))
14524 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14525 (defun org-string>= (a b) (not (string< a b)))
14526 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14527 (defun org-string<> (a b) (not (string= a b)))
14528 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14529 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14530 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14531 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14532 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14533 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14534 (defun org-2ft (s)
14535 "Convert S to a floating point time.
14536 If S is already a number, just return it. If it is a string, parse
14537 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14538 (cond
14539 ((numberp s) s)
14540 ((stringp s)
14541 (condition-case nil
14542 (float-time (apply 'encode-time (org-parse-time-string s)))
14543 (error 0.)))
14544 (t 0.)))
14546 (defun org-time-today ()
14547 "Time in seconds today at 0:00.
14548 Returns the float number of seconds since the beginning of the
14549 epoch to the beginning of today (00:00)."
14550 (float-time (apply 'encode-time
14551 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14553 (defun org-matcher-time (s)
14554 "Interpret a time comparison value."
14555 (save-match-data
14556 (cond
14557 ((string= s "<now>") (float-time))
14558 ((string= s "<today>") (org-time-today))
14559 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14560 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14561 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14562 (+ (org-time-today)
14563 (* (string-to-number (match-string 1 s))
14564 (cdr (assoc (match-string 2 s)
14565 '(("d" . 86400.0) ("w" . 604800.0)
14566 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14567 (t (org-2ft s)))))
14569 (defun org-match-any-p (re list)
14570 "Does re match any element of list?"
14571 (setq list (mapcar (lambda (x) (string-match re x)) list))
14572 (delq nil list))
14574 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14575 (defvar org-tags-overlay (make-overlay 1 1))
14576 (org-detach-overlay org-tags-overlay)
14578 (defun org-get-local-tags-at (&optional pos)
14579 "Get a list of tags defined in the current headline."
14580 (org-get-tags-at pos 'local))
14582 (defun org-get-local-tags ()
14583 "Get a list of tags defined in the current headline."
14584 (org-get-tags-at nil 'local))
14586 (defun org-get-tags-at (&optional pos local)
14587 "Get a list of all headline tags applicable at POS.
14588 POS defaults to point. If tags are inherited, the list contains
14589 the targets in the same sequence as the headlines appear, i.e.
14590 the tags of the current headline come last.
14591 When LOCAL is non-nil, only return tags from the current headline,
14592 ignore inherited ones."
14593 (interactive)
14594 (if (and org-trust-scanner-tags
14595 (or (not pos) (equal pos (point)))
14596 (not local))
14597 org-scanner-tags
14598 (let (tags ltags lastpos parent)
14599 (save-excursion
14600 (save-restriction
14601 (widen)
14602 (goto-char (or pos (point)))
14603 (save-match-data
14604 (catch 'done
14605 (condition-case nil
14606 (progn
14607 (org-back-to-heading t)
14608 (while (not (equal lastpos (point)))
14609 (setq lastpos (point))
14610 (when (looking-at
14611 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14612 (setq ltags (org-split-string
14613 (org-match-string-no-properties 1) ":"))
14614 (when parent
14615 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14616 (setq tags (append
14617 (if parent
14618 (org-remove-uninherited-tags ltags)
14619 ltags)
14620 tags)))
14621 (or org-use-tag-inheritance (throw 'done t))
14622 (if local (throw 'done t))
14623 (or (org-up-heading-safe) (error nil))
14624 (setq parent t)))
14625 (error nil)))))
14626 (if local
14627 tags
14628 (reverse (delete-dups
14629 (reverse (append
14630 (org-remove-uninherited-tags
14631 org-file-tags) tags)))))))))
14633 (defun org-add-prop-inherited (s)
14634 (add-text-properties 0 (length s) '(inherited t) s)
14637 (defun org-toggle-tag (tag &optional onoff)
14638 "Toggle the tag TAG for the current line.
14639 If ONOFF is `on' or `off', don't toggle but set to this state."
14640 (let (res current)
14641 (save-excursion
14642 (org-back-to-heading t)
14643 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14644 (point-at-eol) t)
14645 (progn
14646 (setq current (match-string 1))
14647 (replace-match ""))
14648 (setq current ""))
14649 (setq current (nreverse (org-split-string current ":")))
14650 (cond
14651 ((eq onoff 'on)
14652 (setq res t)
14653 (or (member tag current) (push tag current)))
14654 ((eq onoff 'off)
14655 (or (not (member tag current)) (setq current (delete tag current))))
14656 (t (if (member tag current)
14657 (setq current (delete tag current))
14658 (setq res t)
14659 (push tag current))))
14660 (end-of-line 1)
14661 (if current
14662 (progn
14663 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14664 (org-set-tags nil t))
14665 (delete-horizontal-space))
14666 (run-hooks 'org-after-tags-change-hook))
14667 res))
14669 (defun org-align-tags-here (to-col)
14670 ;; Assumes that this is a headline
14671 "Align tags on the current headline to TO-COL."
14672 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14673 (beginning-of-line 1)
14674 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14675 (< pos (match-beginning 2)))
14676 (progn
14677 (setq tags-l (- (match-end 2) (match-beginning 2)))
14678 (goto-char (match-beginning 1))
14679 (insert " ")
14680 (delete-region (point) (1+ (match-beginning 2)))
14681 (setq ncol (max (current-column)
14682 (1+ col)
14683 (if (> to-col 0)
14684 to-col
14685 (- (abs to-col) tags-l))))
14686 (setq p (point))
14687 (insert (make-string (- ncol (current-column)) ?\ ))
14688 (setq ncol (current-column))
14689 (when indent-tabs-mode (tabify p (point-at-eol)))
14690 (org-move-to-column (min ncol col)))
14691 (goto-char pos))))
14693 (defun org-set-tags-command (&optional arg just-align)
14694 "Call the set-tags command for the current entry."
14695 (interactive "P")
14696 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14697 (org-set-tags arg just-align)
14698 (save-excursion
14699 (unless (and (org-region-active-p)
14700 org-loop-over-headlines-in-active-region)
14701 (org-back-to-heading t))
14702 (org-set-tags arg just-align))))
14704 (defun org-set-tags-to (data)
14705 "Set the tags of the current entry to DATA, replacing the current tags.
14706 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14707 If DATA is nil or the empty string, any tags will be removed."
14708 (interactive "sTags: ")
14709 (setq data
14710 (cond
14711 ((eq data nil) "")
14712 ((equal data "") "")
14713 ((stringp data)
14714 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14715 ":"))
14716 ((listp data)
14717 (concat ":" (mapconcat 'identity data ":") ":"))))
14718 (when data
14719 (save-excursion
14720 (org-back-to-heading t)
14721 (when (looking-at org-complex-heading-regexp)
14722 (if (match-end 5)
14723 (progn
14724 (goto-char (match-beginning 5))
14725 (insert data)
14726 (delete-region (point) (point-at-eol))
14727 (org-set-tags nil 'align))
14728 (goto-char (point-at-eol))
14729 (insert " " data)
14730 (org-set-tags nil 'align)))
14731 (beginning-of-line 1)
14732 (if (looking-at ".*?\\([ \t]+\\)$")
14733 (delete-region (match-beginning 1) (match-end 1))))))
14735 (defun org-align-all-tags ()
14736 "Align the tags i all headings."
14737 (interactive)
14738 (save-excursion
14739 (or (ignore-errors (org-back-to-heading t))
14740 (outline-next-heading))
14741 (if (org-at-heading-p)
14742 (org-set-tags t)
14743 (message "No headings"))))
14745 (defvar org-indent-indentation-per-level)
14746 (defun org-set-tags (&optional arg just-align)
14747 "Set the tags for the current headline.
14748 With prefix ARG, realign all tags in headings in the current buffer.
14749 When JUST-ALIGN is non-nil, only align tags."
14750 (interactive "P")
14751 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14752 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14753 'region-start-level 'region))
14754 org-loop-over-headlines-in-active-region)
14755 (org-map-entries
14756 ;; We don't use ARG and JUST-ALIGN here because these args
14757 ;; are not useful when looping over headlines.
14758 `(org-set-tags)
14759 org-loop-over-headlines-in-active-region
14760 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14761 (let* ((re org-outline-regexp-bol)
14762 (current (unless arg (org-get-tags-string)))
14763 (col (current-column))
14764 (org-setting-tags t)
14765 table current-tags inherited-tags ; computed below when needed
14766 tags p0 c0 c1 rpl di tc level)
14767 (if arg
14768 (save-excursion
14769 (goto-char (point-min))
14770 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14771 (while (re-search-forward re nil t)
14772 (org-set-tags nil t)
14773 (end-of-line 1)))
14774 (message "All tags realigned to column %d" org-tags-column))
14775 (if just-align
14776 (setq tags current)
14777 ;; Get a new set of tags from the user
14778 (save-excursion
14779 (setq table (append org-tag-persistent-alist
14780 (or org-tag-alist (org-get-buffer-tags))
14781 (and
14782 org-complete-tags-always-offer-all-agenda-tags
14783 (org-global-tags-completion-table
14784 (org-agenda-files))))
14785 org-last-tags-completion-table table
14786 current-tags (org-split-string current ":")
14787 inherited-tags (nreverse
14788 (nthcdr (length current-tags)
14789 (nreverse (org-get-tags-at))))
14790 tags
14791 (if (or (eq t org-use-fast-tag-selection)
14792 (and org-use-fast-tag-selection
14793 (delq nil (mapcar 'cdr table))))
14794 (org-fast-tag-selection
14795 current-tags inherited-tags table
14796 (if org-fast-tag-selection-include-todo
14797 org-todo-key-alist))
14798 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14799 (org-trim
14800 (org-icompleting-read "Tags: "
14801 'org-tags-completion-function
14802 nil nil current 'org-tags-history))))))
14803 (while (string-match "[-+&]+" tags)
14804 ;; No boolean logic, just a list
14805 (setq tags (replace-match ":" t t tags))))
14807 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14809 (if org-tags-sort-function
14810 (setq tags (mapconcat 'identity
14811 (sort (org-split-string
14812 tags (org-re "[^[:alnum:]_@#%]+"))
14813 org-tags-sort-function) ":")))
14815 (if (string-match "\\`[\t ]*\\'" tags)
14816 (setq tags "")
14817 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14818 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14820 ;; Insert new tags at the correct column
14821 (beginning-of-line 1)
14822 (setq level (or (and (looking-at org-outline-regexp)
14823 (- (match-end 0) (point) 1))
14825 (cond
14826 ((and (equal current "") (equal tags "")))
14827 ((re-search-forward
14828 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14829 (point-at-eol) t)
14830 (if (equal tags "")
14831 (setq rpl "")
14832 (goto-char (match-beginning 0))
14833 (setq c0 (current-column)
14834 ;; compute offset for the case of org-indent-mode active
14835 di (if (org-bound-and-true-p org-indent-mode)
14836 (* (1- org-indent-indentation-per-level) (1- level))
14838 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14839 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14840 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (string-width tags))))
14841 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14842 (replace-match rpl t t)
14843 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14844 tags)
14845 (t (error "Tags alignment failed")))
14846 (org-move-to-column col)
14847 (unless just-align
14848 (run-hooks 'org-after-tags-change-hook))))))
14850 (defun org-change-tag-in-region (beg end tag off)
14851 "Add or remove TAG for each entry in the region.
14852 This works in the agenda, and also in an org-mode buffer."
14853 (interactive
14854 (list (region-beginning) (region-end)
14855 (let ((org-last-tags-completion-table
14856 (if (derived-mode-p 'org-mode)
14857 (org-uniquify
14858 (delq nil (append (org-get-buffer-tags)
14859 (org-global-tags-completion-table))))
14860 (org-global-tags-completion-table))))
14861 (org-icompleting-read
14862 "Tag: " 'org-tags-completion-function nil nil nil
14863 'org-tags-history))
14864 (progn
14865 (message "[s]et or [r]emove? ")
14866 (equal (read-char-exclusive) ?r))))
14867 (if (fboundp 'deactivate-mark) (deactivate-mark))
14868 (let ((agendap (equal major-mode 'org-agenda-mode))
14869 l1 l2 m buf pos newhead (cnt 0))
14870 (goto-char end)
14871 (setq l2 (1- (org-current-line)))
14872 (goto-char beg)
14873 (setq l1 (org-current-line))
14874 (loop for l from l1 to l2 do
14875 (org-goto-line l)
14876 (setq m (get-text-property (point) 'org-hd-marker))
14877 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14878 (and agendap m))
14879 (setq buf (if agendap (marker-buffer m) (current-buffer))
14880 pos (if agendap m (point)))
14881 (with-current-buffer buf
14882 (save-excursion
14883 (save-restriction
14884 (goto-char pos)
14885 (setq cnt (1+ cnt))
14886 (org-toggle-tag tag (if off 'off 'on))
14887 (setq newhead (org-get-heading)))))
14888 (and agendap (org-agenda-change-all-lines newhead m))))
14889 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14891 (defun org-tags-completion-function (string predicate &optional flag)
14892 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14893 (confirm (lambda (x) (stringp (car x)))))
14894 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14895 (setq s1 (match-string 1 string)
14896 s2 (match-string 2 string))
14897 (setq s1 "" s2 string))
14898 (cond
14899 ((eq flag nil)
14900 ;; try completion
14901 (setq rtn (try-completion s2 ctable confirm))
14902 (if (stringp rtn)
14903 (setq rtn
14904 (concat s1 s2 (substring rtn (length s2))
14905 (if (and org-add-colon-after-tag-completion
14906 (assoc rtn ctable))
14907 ":" ""))))
14908 rtn)
14909 ((eq flag t)
14910 ;; all-completions
14911 (all-completions s2 ctable confirm))
14912 ((eq flag 'lambda)
14913 ;; exact match?
14914 (assoc s2 ctable)))))
14916 (defun org-fast-tag-insert (kwd tags face &optional end)
14917 "Insert KDW, and the TAGS, the latter with face FACE.
14918 Also insert END."
14919 (insert (format "%-12s" (concat kwd ":"))
14920 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14921 (or end "")))
14923 (defun org-fast-tag-show-exit (flag)
14924 (save-excursion
14925 (org-goto-line 3)
14926 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14927 (replace-match ""))
14928 (when flag
14929 (end-of-line 1)
14930 (org-move-to-column (- (window-width) 19) t)
14931 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14933 (defun org-set-current-tags-overlay (current prefix)
14934 "Add an overlay to CURRENT tag with PREFIX."
14935 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14936 (if (featurep 'xemacs)
14937 (org-overlay-display org-tags-overlay (concat prefix s)
14938 'secondary-selection)
14939 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14940 (org-overlay-display org-tags-overlay (concat prefix s)))))
14942 (defvar org-last-tag-selection-key nil)
14943 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14944 "Fast tag selection with single keys.
14945 CURRENT is the current list of tags in the headline, INHERITED is the
14946 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14947 possibly with grouping information. TODO-TABLE is a similar table with
14948 TODO keywords, should these have keys assigned to them.
14949 If the keys are nil, a-z are automatically assigned.
14950 Returns the new tags string, or nil to not change the current settings."
14951 (let* ((fulltable (append table todo-table))
14952 (maxlen (apply 'max (mapcar
14953 (lambda (x)
14954 (if (stringp (car x)) (string-width (car x)) 0))
14955 fulltable)))
14956 (buf (current-buffer))
14957 (expert (eq org-fast-tag-selection-single-key 'expert))
14958 (buffer-tags nil)
14959 (fwidth (+ maxlen 3 1 3))
14960 (ncol (/ (- (window-width) 4) fwidth))
14961 (i-face 'org-done)
14962 (c-face 'org-todo)
14963 tg cnt e c char c1 c2 ntable tbl rtn
14964 ov-start ov-end ov-prefix
14965 (exit-after-next org-fast-tag-selection-single-key)
14966 (done-keywords org-done-keywords)
14967 groups ingroup)
14968 (save-excursion
14969 (beginning-of-line 1)
14970 (if (looking-at
14971 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14972 (setq ov-start (match-beginning 1)
14973 ov-end (match-end 1)
14974 ov-prefix "")
14975 (setq ov-start (1- (point-at-eol))
14976 ov-end (1+ ov-start))
14977 (skip-chars-forward "^\n\r")
14978 (setq ov-prefix
14979 (concat
14980 (buffer-substring (1- (point)) (point))
14981 (if (> (current-column) org-tags-column)
14983 (make-string (- org-tags-column (current-column)) ?\ ))))))
14984 (move-overlay org-tags-overlay ov-start ov-end)
14985 (save-window-excursion
14986 (if expert
14987 (set-buffer (get-buffer-create " *Org tags*"))
14988 (delete-other-windows)
14989 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
14990 (org-switch-to-buffer-other-window " *Org tags*"))
14991 (erase-buffer)
14992 (org-set-local 'org-done-keywords done-keywords)
14993 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14994 (org-fast-tag-insert "Current" current c-face "\n\n")
14995 (org-fast-tag-show-exit exit-after-next)
14996 (org-set-current-tags-overlay current ov-prefix)
14997 (setq tbl fulltable char ?a cnt 0)
14998 (while (setq e (pop tbl))
14999 (cond
15000 ((equal (car e) :startgroup)
15001 (push '() groups) (setq ingroup t)
15002 (when (not (= cnt 0))
15003 (setq cnt 0)
15004 (insert "\n"))
15005 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15006 ((equal (car e) :endgroup)
15007 (setq ingroup nil cnt 0)
15008 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15009 ((equal e '(:newline))
15010 (when (not (= cnt 0))
15011 (setq cnt 0)
15012 (insert "\n")
15013 (setq e (car tbl))
15014 (while (equal (car tbl) '(:newline))
15015 (insert "\n")
15016 (setq tbl (cdr tbl)))))
15017 ((equal e '(:grouptags)) nil)
15019 (setq tg (copy-sequence (car e)) c2 nil)
15020 (if (cdr e)
15021 (setq c (cdr e))
15022 ;; automatically assign a character.
15023 (setq c1 (string-to-char
15024 (downcase (substring
15025 tg (if (= (string-to-char tg) ?@) 1 0)))))
15026 (if (or (rassoc c1 ntable) (rassoc c1 table))
15027 (while (or (rassoc char ntable) (rassoc char table))
15028 (setq char (1+ char)))
15029 (setq c2 c1))
15030 (setq c (or c2 char)))
15031 (if ingroup (push tg (car groups)))
15032 (setq tg (org-add-props tg nil 'face
15033 (cond
15034 ((not (assoc tg table))
15035 (org-get-todo-face tg))
15036 ((member tg current) c-face)
15037 ((member tg inherited) i-face))))
15038 (if (equal (caar tbl) :grouptags)
15039 (org-add-props tg nil 'face 'org-tag-group))
15040 (if (and (= cnt 0) (not ingroup)) (insert " "))
15041 (insert "[" c "] " tg (make-string
15042 (- fwidth 4 (length tg)) ?\ ))
15043 (push (cons tg c) ntable)
15044 (when (= (setq cnt (1+ cnt)) ncol)
15045 (insert "\n")
15046 (if ingroup (insert " "))
15047 (setq cnt 0)))))
15048 (setq ntable (nreverse ntable))
15049 (insert "\n")
15050 (goto-char (point-min))
15051 (if (not expert) (org-fit-window-to-buffer))
15052 (setq rtn
15053 (catch 'exit
15054 (while t
15055 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15056 (if (not groups) "no " "")
15057 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15058 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15059 (setq org-last-tag-selection-key c)
15060 (cond
15061 ((= c ?\r) (throw 'exit t))
15062 ((= c ?!)
15063 (setq groups (not groups))
15064 (goto-char (point-min))
15065 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15066 ((= c ?\C-c)
15067 (if (not expert)
15068 (org-fast-tag-show-exit
15069 (setq exit-after-next (not exit-after-next)))
15070 (setq expert nil)
15071 (delete-other-windows)
15072 (set-window-buffer (split-window-vertically) " *Org tags*")
15073 (org-switch-to-buffer-other-window " *Org tags*")
15074 (org-fit-window-to-buffer)))
15075 ((or (= c ?\C-g)
15076 (and (= c ?q) (not (rassoc c ntable))))
15077 (org-detach-overlay org-tags-overlay)
15078 (setq quit-flag t))
15079 ((= c ?\ )
15080 (setq current nil)
15081 (if exit-after-next (setq exit-after-next 'now)))
15082 ((= c ?\t)
15083 (condition-case nil
15084 (setq tg (org-icompleting-read
15085 "Tag: "
15086 (or buffer-tags
15087 (with-current-buffer buf
15088 (org-get-buffer-tags)))))
15089 (quit (setq tg "")))
15090 (when (string-match "\\S-" tg)
15091 (add-to-list 'buffer-tags (list tg))
15092 (if (member tg current)
15093 (setq current (delete tg current))
15094 (push tg current)))
15095 (if exit-after-next (setq exit-after-next 'now)))
15096 ((setq e (rassoc c todo-table) tg (car e))
15097 (with-current-buffer buf
15098 (save-excursion (org-todo tg)))
15099 (if exit-after-next (setq exit-after-next 'now)))
15100 ((setq e (rassoc c ntable) tg (car e))
15101 (if (member tg current)
15102 (setq current (delete tg current))
15103 (loop for g in groups do
15104 (if (member tg g)
15105 (mapc (lambda (x)
15106 (setq current (delete x current)))
15107 g)))
15108 (push tg current))
15109 (if exit-after-next (setq exit-after-next 'now))))
15111 ;; Create a sorted list
15112 (setq current
15113 (sort current
15114 (lambda (a b)
15115 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15116 (if (eq exit-after-next 'now) (throw 'exit t))
15117 (goto-char (point-min))
15118 (beginning-of-line 2)
15119 (delete-region (point) (point-at-eol))
15120 (org-fast-tag-insert "Current" current c-face)
15121 (org-set-current-tags-overlay current ov-prefix)
15122 (while (re-search-forward
15123 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
15124 (setq tg (match-string 1))
15125 (add-text-properties
15126 (match-beginning 1) (match-end 1)
15127 (list 'face
15128 (cond
15129 ((member tg current) c-face)
15130 ((member tg inherited) i-face)
15131 (t (get-text-property (match-beginning 1) 'face))))))
15132 (goto-char (point-min)))))
15133 (org-detach-overlay org-tags-overlay)
15134 (if rtn
15135 (mapconcat 'identity current ":")
15136 nil))))
15138 (defun org-get-tags-string ()
15139 "Get the TAGS string in the current headline."
15140 (unless (org-at-heading-p t)
15141 (user-error "Not on a heading"))
15142 (save-excursion
15143 (beginning-of-line 1)
15144 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
15145 (org-match-string-no-properties 1)
15146 "")))
15148 (defun org-get-tags ()
15149 "Get the list of tags specified in the current headline."
15150 (org-split-string (org-get-tags-string) ":"))
15152 (defun org-get-buffer-tags ()
15153 "Get a table of all tags used in the buffer, for completion."
15154 (let (tags)
15155 (save-excursion
15156 (goto-char (point-min))
15157 (while (re-search-forward
15158 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
15159 (when (equal (char-after (point-at-bol 0)) ?*)
15160 (mapc (lambda (x) (add-to-list 'tags x))
15161 (org-split-string (org-match-string-no-properties 1) ":")))))
15162 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
15163 (mapcar 'list tags)))
15165 ;;;; The mapping API
15167 (defun org-map-entries (func &optional match scope &rest skip)
15168 "Call FUNC at each headline selected by MATCH in SCOPE.
15170 FUNC is a function or a lisp form. The function will be called without
15171 arguments, with the cursor positioned at the beginning of the headline.
15172 The return values of all calls to the function will be collected and
15173 returned as a list.
15175 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15176 does not need to preserve point. After evaluation, the cursor will be
15177 moved to the end of the line (presumably of the headline of the
15178 processed entry) and search continues from there. Under some
15179 circumstances, this may not produce the wanted results. For example,
15180 if you have removed (e.g. archived) the current (sub)tree it could
15181 mean that the next entry will be skipped entirely. In such cases, you
15182 can specify the position from where search should continue by making
15183 FUNC set the variable `org-map-continue-from' to the desired buffer
15184 position.
15186 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15187 Only headlines that are matched by this query will be considered during
15188 the iteration. When MATCH is nil or t, all headlines will be
15189 visited by the iteration.
15191 SCOPE determines the scope of this command. It can be any of:
15193 nil The current buffer, respecting the restriction if any
15194 tree The subtree started with the entry at point
15195 region The entries within the active region, if any
15196 region-start-level
15197 The entries within the active region, but only those at
15198 the same level than the first one.
15199 file The current buffer, without restriction
15200 file-with-archives
15201 The current buffer, and any archives associated with it
15202 agenda All agenda files
15203 agenda-with-archives
15204 All agenda files with any archive files associated with them
15205 \(file1 file2 ...)
15206 If this is a list, all files in the list will be scanned
15208 The remaining args are treated as settings for the skipping facilities of
15209 the scanner. The following items can be given here:
15211 archive skip trees with the archive tag
15212 comment skip trees with the COMMENT keyword
15213 function or Emacs Lisp form:
15214 will be used as value for `org-agenda-skip-function', so
15215 whenever the function returns a position, FUNC will not be
15216 called for that entry and search will continue from the
15217 position returned
15219 If your function needs to retrieve the tags including inherited tags
15220 at the *current* entry, you can use the value of the variable
15221 `org-scanner-tags' which will be much faster than getting the value
15222 with `org-get-tags-at'. If your function gets properties with
15223 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15224 to t around the call to `org-entry-properties' to get the same speedup.
15225 Note that if your function moves around to retrieve tags and properties at
15226 a *different* entry, you cannot use these techniques."
15227 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15228 (not (org-region-active-p)))
15229 (let* ((org-agenda-archives-mode nil) ; just to make sure
15230 (org-agenda-skip-archived-trees (memq 'archive skip))
15231 (org-agenda-skip-comment-trees (memq 'comment skip))
15232 (org-agenda-skip-function
15233 (car (org-delete-all '(comment archive) skip)))
15234 (org-tags-match-list-sublevels t)
15235 (start-level (eq scope 'region-start-level))
15236 matcher file res
15237 org-todo-keywords-for-agenda
15238 org-done-keywords-for-agenda
15239 org-todo-keyword-alist-for-agenda
15240 org-tag-alist-for-agenda
15241 todo-only)
15243 (cond
15244 ((eq match t) (setq matcher t))
15245 ((eq match nil) (setq matcher t))
15246 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15248 (save-excursion
15249 (save-restriction
15250 (cond ((eq scope 'tree)
15251 (org-back-to-heading t)
15252 (org-narrow-to-subtree)
15253 (setq scope nil))
15254 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15255 (org-region-active-p))
15256 ;; If needed, set start-level to a string like "2"
15257 (when start-level
15258 (save-excursion
15259 (goto-char (region-beginning))
15260 (unless (org-at-heading-p) (outline-next-heading))
15261 (setq start-level (org-current-level))))
15262 (narrow-to-region (region-beginning)
15263 (save-excursion
15264 (goto-char (region-end))
15265 (unless (and (bolp) (org-at-heading-p))
15266 (outline-next-heading))
15267 (point)))
15268 (setq scope nil)))
15270 (if (not scope)
15271 (progn
15272 (org-agenda-prepare-buffers
15273 (list (buffer-file-name (current-buffer))))
15274 (setq res (org-scan-tags func matcher todo-only start-level)))
15275 ;; Get the right scope
15276 (cond
15277 ((and scope (listp scope) (symbolp (car scope)))
15278 (setq scope (eval scope)))
15279 ((eq scope 'agenda)
15280 (setq scope (org-agenda-files t)))
15281 ((eq scope 'agenda-with-archives)
15282 (setq scope (org-agenda-files t))
15283 (setq scope (org-add-archive-files scope)))
15284 ((eq scope 'file)
15285 (setq scope (list (buffer-file-name))))
15286 ((eq scope 'file-with-archives)
15287 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15288 (org-agenda-prepare-buffers scope)
15289 (while (setq file (pop scope))
15290 (with-current-buffer (org-find-base-buffer-visiting file)
15291 (save-excursion
15292 (save-restriction
15293 (widen)
15294 (goto-char (point-min))
15295 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
15296 res)))
15298 ;;;; Properties
15300 ;;; Setting and retrieving properties
15302 (defconst org-special-properties
15303 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
15304 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
15305 "The special properties valid in Org-mode.
15307 These are properties that are not defined in the property drawer,
15308 but in some other way.")
15310 (defconst org-default-properties
15311 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15312 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15313 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15314 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15315 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
15316 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15317 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15318 "Some properties that are used by Org-mode for various purposes.
15319 Being in this list makes sure that they are offered for completion.")
15321 (defun org-property-action ()
15322 "Do an action on properties."
15323 (interactive)
15324 (let (c)
15325 (org-at-property-p)
15326 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15327 (setq c (read-char-exclusive))
15328 (cond
15329 ((equal c ?s)
15330 (call-interactively 'org-set-property))
15331 ((equal c ?d)
15332 (call-interactively 'org-delete-property))
15333 ((equal c ?D)
15334 (call-interactively 'org-delete-property-globally))
15335 ((equal c ?c)
15336 (call-interactively 'org-compute-property-at-point))
15337 (t (user-error "No such property action %c" c)))))
15339 (defun org-inc-effort ()
15340 "Increment the value of the effort property in the current entry."
15341 (interactive)
15342 (org-set-effort nil t))
15344 (defvar org-clock-effort) ;; Defined in org-clock.el
15345 (defvar org-clock-current-task) ;; Defined in org-clock.el
15346 (defun org-set-effort (&optional value increment)
15347 "Set the effort property of the current entry.
15348 With numerical prefix arg, use the nth allowed value, 0 stands for the
15349 10th allowed value.
15351 When INCREMENT is non-nil, set the property to the next allowed value."
15352 (interactive "P")
15353 (if (equal value 0) (setq value 10))
15354 (let* ((completion-ignore-case t)
15355 (prop org-effort-property)
15356 (cur (org-entry-get nil prop))
15357 (allowed (org-property-get-allowed-values nil prop 'table))
15358 (existing (mapcar 'list (org-property-values prop)))
15359 (heading (nth 4 (org-heading-components)))
15361 (val (cond
15362 ((stringp value) value)
15363 ((and allowed (integerp value))
15364 (or (car (nth (1- value) allowed))
15365 (car (org-last allowed))))
15366 ((and allowed increment)
15367 (or (caadr (member (list cur) allowed))
15368 (user-error "Allowed effort values are not set")))
15369 (allowed
15370 (message "Select 1-9,0, [RET%s]: %s"
15371 (if cur (concat "=" cur) "")
15372 (mapconcat 'car allowed " "))
15373 (setq rpl (read-char-exclusive))
15374 (if (equal rpl ?\r)
15376 (setq rpl (- rpl ?0))
15377 (if (equal rpl 0) (setq rpl 10))
15378 (if (and (> rpl 0) (<= rpl (length allowed)))
15379 (car (nth (1- rpl) allowed))
15380 (org-completing-read "Effort: " allowed nil))))
15382 (let (org-completion-use-ido org-completion-use-iswitchb)
15383 (org-completing-read
15384 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15385 (concat "[" cur "]") "")
15386 ": ")
15387 existing nil nil "" nil cur))))))
15388 (unless (equal (org-entry-get nil prop) val)
15389 (org-entry-put nil prop val))
15390 (org-refresh-property
15391 '((effort . identity)
15392 (effort-minutes . org-duration-string-to-minutes))
15393 val)
15394 (when (string= heading org-clock-current-task)
15395 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15396 (org-clock-update-mode-line))
15397 (message "%s is now %s" prop val)))
15399 (defun org-at-property-p ()
15400 "Non-nil when point is inside a property drawer.
15401 See `org-property-re' for match data, if applicable."
15402 (when (eq (org-element-type (org-element-at-point)) 'node-property)
15403 (save-excursion
15404 (beginning-of-line)
15405 (looking-at org-property-re))))
15407 (defun org-get-property-block (&optional beg end force)
15408 "Return the (beg . end) range of the body of the property drawer.
15409 BEG and END are the beginning and end of the current subtree, or of
15410 the part before the first headline. If they are not given, they will
15411 be found. If the drawer does not exist and FORCE is non-nil, create
15412 the drawer."
15413 (catch 'exit
15414 (save-excursion
15415 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15416 (progn (org-back-to-heading t) (point))))
15417 (end (or end (and (not (outline-next-heading)) (point-max))
15418 (point))))
15419 (goto-char beg)
15420 (if (re-search-forward org-property-start-re end t)
15421 (setq beg (1+ (match-end 0)))
15422 (if force
15423 (save-excursion
15424 (org-insert-property-drawer)
15425 (setq end (progn (outline-next-heading) (point))))
15426 (throw 'exit nil))
15427 (goto-char beg)
15428 (if (re-search-forward org-property-start-re end t)
15429 (setq beg (1+ (match-end 0)))))
15430 (if (re-search-forward org-property-end-re end t)
15431 (setq end (match-beginning 0))
15432 (or force (throw 'exit nil))
15433 (goto-char beg)
15434 (setq end beg)
15435 (org-indent-line)
15436 (insert ":END:\n"))
15437 (cons beg end)))))
15439 (defun org-entry-properties (&optional pom which specific)
15440 "Get all properties of the entry at point-or-marker POM.
15441 This includes the TODO keyword, the tags, time strings for deadline,
15442 scheduled, and clocking, and any additional properties defined in the
15443 entry. The return value is an alist, keys may occur multiple times
15444 if the property key was used several times.
15445 POM may also be nil, in which case the current entry is used.
15446 If WHICH is nil or `all', get all properties. If WHICH is
15447 `special' or `standard', only get that subclass. If WHICH
15448 is a string only get exactly this property. SPECIFIC can be a string, the
15449 specific property we are interested in. Specifying it can speed
15450 things up because then unnecessary parsing is avoided."
15451 (setq which (or which 'all))
15452 (org-with-wide-buffer
15453 (org-with-point-at pom
15454 (let ((clockstr (substring org-clock-string 0 -1))
15455 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15456 (case-fold-search nil)
15457 beg end range props sum-props key key1 value string clocksum clocksumt)
15458 (when (and (derived-mode-p 'org-mode)
15459 (ignore-errors (org-back-to-heading t)))
15460 (setq beg (point))
15461 (setq sum-props (get-text-property (point) 'org-summaries))
15462 (setq clocksum (get-text-property (point) :org-clock-minutes)
15463 clocksumt (get-text-property (point) :org-clock-minutes-today))
15464 (outline-next-heading)
15465 (setq end (point))
15466 (when (memq which '(all special))
15467 ;; Get the special properties, like TODO and tags
15468 (goto-char beg)
15469 (when (and (or (not specific) (string= specific "TODO"))
15470 (looking-at org-todo-line-regexp) (match-end 2))
15471 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15472 (when (and (or (not specific) (string= specific "PRIORITY"))
15473 (looking-at org-priority-regexp))
15474 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15475 (when (or (not specific) (string= specific "FILE"))
15476 (push (cons "FILE" buffer-file-name) props))
15477 (when (and (or (not specific) (string= specific "TAGS"))
15478 (setq value (org-get-tags-string))
15479 (string-match "\\S-" value))
15480 (push (cons "TAGS" value) props))
15481 (when (and (or (not specific) (string= specific "ALLTAGS"))
15482 (setq value (org-get-tags-at)))
15483 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15484 ":"))
15485 props))
15486 (when (or (not specific) (string= specific "BLOCKED"))
15487 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15488 (when (or (not specific)
15489 (member specific
15490 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15491 "TIMESTAMP" "TIMESTAMP_IA")))
15492 (catch 'match
15493 (while (and (re-search-forward org-maybe-keyword-time-regexp end t)
15494 (not (text-property-any 0 (length (match-string 0))
15495 'face 'font-lock-comment-face
15496 (match-string 0))))
15497 (setq key (if (match-end 1)
15498 (substring (org-match-string-no-properties 1)
15499 0 -1))
15500 string (if (equal key clockstr)
15501 (org-trim
15502 (buffer-substring-no-properties
15503 (match-beginning 3) (goto-char
15504 (point-at-eol))))
15505 (substring (org-match-string-no-properties 3)
15506 1 -1)))
15507 ;; Get the correct property name from the key. This is
15508 ;; necessary if the user has configured time keywords.
15509 (setq key1 (concat key ":"))
15510 (cond
15511 ((not key)
15512 (setq key
15513 (if (= (char-after (match-beginning 3)) ?\[)
15514 "TIMESTAMP_IA" "TIMESTAMP")))
15515 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15516 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15517 ((equal key1 org-closed-string) (setq key "CLOSED"))
15518 ((equal key1 org-clock-string) (setq key "CLOCK")))
15519 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15520 (progn
15521 (push (cons key string) props)
15522 ;; no need to search further if match is found
15523 (throw 'match t))
15524 (when (or (equal key "CLOCK") (not (assoc key props)))
15525 (push (cons key string) props)))))))
15527 (when (memq which '(all standard))
15528 ;; Get the standard properties, like :PROP: ...
15529 (setq range (org-get-property-block beg end))
15530 (when range
15531 (goto-char (car range))
15532 (while (re-search-forward org-property-re
15533 (cdr range) t)
15534 (setq key (org-match-string-no-properties 2)
15535 value (org-trim (or (org-match-string-no-properties 3) "")))
15536 (unless (member key excluded)
15537 (push (cons key (or value "")) props)))))
15538 (if clocksum
15539 (push (cons "CLOCKSUM"
15540 (org-columns-number-to-string (/ (float clocksum) 60.)
15541 'add_times))
15542 props))
15543 (if clocksumt
15544 (push (cons "CLOCKSUM_T"
15545 (org-columns-number-to-string (/ (float clocksumt) 60.)
15546 'add_times))
15547 props))
15548 (unless (assoc "CATEGORY" props)
15549 (push (cons "CATEGORY" (org-get-category)) props))
15550 (append sum-props (nreverse props)))))))
15552 (defun org-entry-get (pom property &optional inherit literal-nil)
15553 "Get value of PROPERTY for entry or content at point-or-marker POM.
15554 If INHERIT is non-nil and the entry does not have the property,
15555 then also check higher levels of the hierarchy.
15556 If INHERIT is the symbol `selective', use inheritance only if the setting
15557 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15558 If the property is present but empty, the return value is the empty string.
15559 If the property is not present at all, nil is returned.
15561 Return the value as a string.
15563 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15564 do not interpret it as the list atom nil. This is used for inheritance
15565 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15566 (org-with-point-at pom
15567 (if (and inherit (if (eq inherit 'selective)
15568 (org-property-inherit-p property)
15570 (org-entry-get-with-inheritance property literal-nil)
15571 (if (member property org-special-properties)
15572 ;; We need a special property. Use `org-entry-properties'
15573 ;; to retrieve it, but specify the wanted property
15574 (cdr (assoc property (org-entry-properties nil 'special property)))
15575 (org-with-wide-buffer
15576 (let ((range (org-get-property-block)))
15577 (when (and range (not (eq (car range) (cdr range)))
15578 (save-excursion
15579 (goto-char (car range))
15580 (re-search-forward
15581 (concat (org-re-property property) "\\|"
15582 (org-re-property (concat property "+")))
15583 (cdr range) t)))
15584 (let* ((props
15585 (list (or (assoc property org-file-properties)
15586 (assoc property org-global-properties)
15587 (assoc property org-global-properties-fixed))))
15588 (ap (lambda (key)
15589 (when (re-search-forward
15590 (org-re-property key) (cdr range) t)
15591 (setq props
15592 (org-update-property-plist
15594 (if (match-end 3)
15595 (org-match-string-no-properties 3) "")
15596 props)))))
15597 val)
15598 (goto-char (car range))
15599 (funcall ap property)
15600 (goto-char (car range))
15601 (while (funcall ap (concat property "+")))
15602 (setq val (cdr (assoc property props)))
15603 (when val (if literal-nil val (org-not-nil val)))))))))))
15605 (defun org-property-or-variable-value (var &optional inherit)
15606 "Check if there is a property fixing the value of VAR.
15607 If yes, return this value. If not, return the current value of the variable."
15608 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15609 (if (and prop (stringp prop) (string-match "\\S-" prop))
15610 (read prop)
15611 (symbol-value var))))
15613 (defun org-entry-delete (pom property)
15614 "Delete the property PROPERTY from entry at point-or-marker POM."
15615 (unless (member property org-special-properties)
15616 (org-with-point-at pom
15617 (let ((range (org-get-property-block)))
15618 (if (and range
15619 (goto-char (car range))
15620 (re-search-forward
15621 (org-re-property property)
15622 (cdr range) t))
15623 (progn
15624 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15625 (org-remove-empty-drawer-at (car range))
15627 nil)))))
15629 ;; Multi-values properties are properties that contain multiple values
15630 ;; These values are assumed to be single words, separated by whitespace.
15631 (defun org-entry-add-to-multivalued-property (pom property value)
15632 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15633 (let* ((old (org-entry-get pom property))
15634 (values (and old (org-split-string old "[ \t]"))))
15635 (setq value (org-entry-protect-space value))
15636 (unless (member value values)
15637 (setq values (append values (list value)))
15638 (org-entry-put pom property
15639 (mapconcat 'identity values " ")))))
15641 (defun org-entry-remove-from-multivalued-property (pom property value)
15642 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15643 (let* ((old (org-entry-get pom property))
15644 (values (and old (org-split-string old "[ \t]"))))
15645 (setq value (org-entry-protect-space value))
15646 (when (member value values)
15647 (setq values (delete value values))
15648 (org-entry-put pom property
15649 (mapconcat 'identity values " ")))))
15651 (defun org-entry-member-in-multivalued-property (pom property value)
15652 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15653 (let* ((old (org-entry-get pom property))
15654 (values (and old (org-split-string old "[ \t]"))))
15655 (setq value (org-entry-protect-space value))
15656 (member value values)))
15658 (defun org-entry-get-multivalued-property (pom property)
15659 "Return a list of values in a multivalued property."
15660 (let* ((value (org-entry-get pom property))
15661 (values (and value (org-split-string value "[ \t]"))))
15662 (mapcar 'org-entry-restore-space values)))
15664 (defun org-entry-put-multivalued-property (pom property &rest values)
15665 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15666 VALUES should be a list of strings. Spaces will be protected."
15667 (org-entry-put pom property
15668 (mapconcat 'org-entry-protect-space values " "))
15669 (let* ((value (org-entry-get pom property))
15670 (values (and value (org-split-string value "[ \t]"))))
15671 (mapcar 'org-entry-restore-space values)))
15673 (defun org-entry-protect-space (s)
15674 "Protect spaces and newline in string S."
15675 (while (string-match " " s)
15676 (setq s (replace-match "%20" t t s)))
15677 (while (string-match "\n" s)
15678 (setq s (replace-match "%0A" t t s)))
15681 (defun org-entry-restore-space (s)
15682 "Restore spaces and newline in string S."
15683 (while (string-match "%20" s)
15684 (setq s (replace-match " " t t s)))
15685 (while (string-match "%0A" s)
15686 (setq s (replace-match "\n" t t s)))
15689 (defvar org-entry-property-inherited-from (make-marker)
15690 "Marker pointing to the entry from where a property was inherited.
15691 Each call to `org-entry-get-with-inheritance' will set this marker to the
15692 location of the entry where the inheritance search matched. If there was
15693 no match, the marker will point nowhere.
15694 Note that also `org-entry-get' calls this function, if the INHERIT flag
15695 is set.")
15697 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15698 "Get PROPERTY of entry or content at point, search higher levels if needed.
15699 The search will stop at the first ancestor which has the property defined.
15700 If the value found is \"nil\", return nil to show that the property
15701 should be considered as undefined (this is the meaning of nil here).
15702 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15703 (move-marker org-entry-property-inherited-from nil)
15704 (let (tmp)
15705 (save-excursion
15706 (save-restriction
15707 (widen)
15708 (catch 'ex
15709 (while t
15710 (when (setq tmp (org-entry-get nil property nil literal-nil))
15711 (or (ignore-errors (org-back-to-heading t))
15712 (goto-char (point-min)))
15713 (move-marker org-entry-property-inherited-from (point))
15714 (throw 'ex tmp))
15715 (or (ignore-errors (org-up-heading-safe))
15716 (throw 'ex nil))))))
15717 (setq tmp (or tmp
15718 (cdr (assoc property org-file-properties))
15719 (cdr (assoc property org-global-properties))
15720 (cdr (assoc property org-global-properties-fixed))))
15721 (if literal-nil tmp (org-not-nil tmp))))
15723 (defvar org-property-changed-functions nil
15724 "Hook called when the value of a property has changed.
15725 Each hook function should accept two arguments, the name of the property
15726 and the new value.")
15728 (defun org-entry-put (pom property value)
15729 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15730 If the value is `nil', it is converted to the empty string.
15731 If it is not a string, an error is raised."
15732 (cond ((null value) (setq value ""))
15733 ((not (stringp value))
15734 (error "Properties values should be strings.")))
15735 (org-with-point-at pom
15736 (org-back-to-heading t)
15737 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15738 range)
15739 (cond
15740 ((equal property "TODO")
15741 (when (and (string-match "\\S-" value)
15742 (not (member value org-todo-keywords-1)))
15743 (user-error "\"%s\" is not a valid TODO state" value))
15744 (if (or (not value)
15745 (not (string-match "\\S-" value)))
15746 (setq value 'none))
15747 (org-todo value)
15748 (org-set-tags nil 'align))
15749 ((equal property "PRIORITY")
15750 (org-priority (if (and value (string-match "\\S-" value))
15751 (string-to-char value) ?\ ))
15752 (org-set-tags nil 'align))
15753 ((equal property "CLOCKSUM")
15754 (if (not (re-search-forward
15755 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15756 (error "Cannot find a clock log")
15757 (goto-char (- (match-end 1) 2))
15758 (cond
15759 ((eq value 'earlier) (org-timestamp-down))
15760 ((eq value 'later) (org-timestamp-up)))
15761 (org-clock-sum-current-item)))
15762 ((equal property "SCHEDULED")
15763 (if (re-search-forward org-scheduled-time-regexp end t)
15764 (cond
15765 ((eq value 'earlier) (org-timestamp-change -1 'day))
15766 ((eq value 'later) (org-timestamp-change 1 'day))
15767 (t (call-interactively 'org-schedule)))
15768 (call-interactively 'org-schedule)))
15769 ((equal property "DEADLINE")
15770 (if (re-search-forward org-deadline-time-regexp end t)
15771 (cond
15772 ((eq value 'earlier) (org-timestamp-change -1 'day))
15773 ((eq value 'later) (org-timestamp-change 1 'day))
15774 (t (call-interactively 'org-deadline)))
15775 (call-interactively 'org-deadline)))
15776 ((member property org-special-properties)
15777 (error "The %s property can not yet be set with `org-entry-put'"
15778 property))
15779 (t ; a non-special property
15780 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15781 (setq range (org-get-property-block beg end 'force))
15782 (goto-char (car range))
15783 (if (re-search-forward
15784 (org-re-property property nil t) (cdr range) t)
15785 (progn
15786 (delete-region (match-beginning 0) (match-end 0))
15787 (goto-char (match-beginning 0)))
15788 (goto-char (cdr range))
15789 (insert "\n")
15790 (backward-char 1)
15791 (org-indent-line))
15792 (insert ":" property ":")
15793 (and value (insert " " value))
15794 (org-indent-line)))))
15795 (run-hook-with-args 'org-property-changed-functions property value)))
15797 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15798 "Get all property keys in the current buffer.
15799 With INCLUDE-SPECIALS, also list the special properties that reflect things
15800 like tags and TODO state.
15801 With INCLUDE-DEFAULTS, also include properties that has special meaning
15802 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15803 and others.
15804 With INCLUDE-COLUMNS, also include property names given in COLUMN
15805 formats in the current buffer."
15806 (let (rtn range cfmt s p)
15807 (save-excursion
15808 (save-restriction
15809 (widen)
15810 (goto-char (point-min))
15811 (while (re-search-forward org-property-start-re nil t)
15812 (catch 'cont
15813 (setq range (or (org-get-property-block)
15814 (if (y-or-n-p
15815 (format "Malformed drawer at %d, repair?" (point)))
15816 (org-get-property-block nil nil t)
15817 (throw 'cont nil))))
15818 (goto-char (car range))
15819 (while (re-search-forward org-property-re
15820 (cdr range) t)
15821 (add-to-list 'rtn (org-match-string-no-properties 2)))
15822 (outline-next-heading)))))
15824 (when include-specials
15825 (setq rtn (append org-special-properties rtn)))
15827 (when include-defaults
15828 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15829 (add-to-list 'rtn org-effort-property))
15831 (when include-columns
15832 (save-excursion
15833 (save-restriction
15834 (widen)
15835 (goto-char (point-min))
15836 (while (re-search-forward
15837 "^[ \t]*\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15838 nil t)
15839 (setq cfmt (match-string 2) s 0)
15840 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15841 cfmt s)
15842 (setq s (match-end 0)
15843 p (match-string 1 cfmt))
15844 (unless (or (equal p "ITEM")
15845 (member p org-special-properties))
15846 (add-to-list 'rtn (match-string 1 cfmt))))))))
15848 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15850 (defun org-property-values (key)
15851 "Return a list of all values of property KEY in the current buffer."
15852 (save-excursion
15853 (save-restriction
15854 (widen)
15855 (goto-char (point-min))
15856 (let ((re (org-re-property key))
15857 values)
15858 (while (re-search-forward re nil t)
15859 (add-to-list 'values (org-trim (match-string 3))))
15860 (delete "" values)))))
15862 (defun org-insert-property-drawer ()
15863 "Insert a property drawer into the current entry."
15864 (org-back-to-heading t)
15865 (looking-at org-outline-regexp)
15866 (let ((indent (if org-adapt-indentation
15867 (- (match-end 0) (match-beginning 0))
15869 (beg (point))
15870 (re (concat "^[ \t]*" org-keyword-time-regexp))
15871 end hiddenp)
15872 (outline-next-heading)
15873 (setq end (point))
15874 (goto-char beg)
15875 (while (re-search-forward re end t))
15876 (setq hiddenp (outline-invisible-p))
15877 (end-of-line 1)
15878 (and (equal (char-after) ?\n) (forward-char 1))
15879 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15880 (if (member (match-string 1) '("CLOCK:" ":END:"))
15881 ;; just skip this line
15882 (beginning-of-line 2)
15883 ;; Drawer start, find the end
15884 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15885 (beginning-of-line 1)))
15886 (org-skip-over-state-notes)
15887 (skip-chars-backward " \t\n\r")
15888 (if (and (eq (char-before) ?*) (not (eq (char-after) ?\n)))
15889 (forward-char 1))
15890 (goto-char (point-at-eol))
15891 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15892 (beginning-of-line 0)
15893 (org-indent-to-column indent)
15894 (beginning-of-line 2)
15895 (org-indent-to-column indent)
15896 (beginning-of-line 0)
15897 (if hiddenp
15898 (save-excursion
15899 (org-back-to-heading t)
15900 (hide-entry))
15901 (org-flag-drawer t))))
15903 (defun org-insert-drawer (&optional arg drawer)
15904 "Insert a drawer at point.
15906 Optional argument DRAWER, when non-nil, is a string representing
15907 drawer's name. Otherwise, the user is prompted for a name.
15909 If a region is active, insert the drawer around that region
15910 instead.
15912 Point is left between drawer's boundaries."
15913 (interactive "P")
15914 (let* ((drawer (if arg "PROPERTIES"
15915 (or drawer (read-from-minibuffer "Drawer: ")))))
15916 (cond
15917 ;; With C-u, fall back on `org-insert-property-drawer'
15918 (arg (org-insert-property-drawer))
15920 ((not (org-string-match-p org-drawer-regexp (format ":%s:" drawer)))
15921 (user-error "Invalid drawer name"))
15922 ;; With an active region, insert a drawer at point.
15923 ((not (org-region-active-p))
15924 (progn
15925 (unless (bolp) (insert "\n"))
15926 (insert (format ":%s:\n\n:END:\n" drawer))
15927 (forward-line -2)))
15928 ;; Otherwise, insert the drawer at point
15930 (let ((rbeg (region-beginning))
15931 (rend (copy-marker (region-end))))
15932 (unwind-protect
15933 (progn
15934 (goto-char rbeg)
15935 (beginning-of-line)
15936 (when (save-excursion
15937 (re-search-forward org-outline-regexp-bol rend t))
15938 (user-error "Drawers cannot contain headlines"))
15939 ;; Position point at the beginning of the first
15940 ;; non-blank line in region. Insert drawer's opening
15941 ;; there, then indent it.
15942 (org-skip-whitespace)
15943 (beginning-of-line)
15944 (insert ":" drawer ":\n")
15945 (forward-line -1)
15946 (indent-for-tab-command)
15947 ;; Move point to the beginning of the first blank line
15948 ;; after the last non-blank line in region. Insert
15949 ;; drawer's closing, then indent it.
15950 (goto-char rend)
15951 (skip-chars-backward " \r\t\n")
15952 (insert "\n:END:")
15953 (deactivate-mark t)
15954 (indent-for-tab-command)
15955 (unless (eolp) (insert "\n")))
15956 ;; Clear marker, whatever the outcome of insertion is.
15957 (set-marker rend nil)))))))
15959 (defvar org-property-set-functions-alist nil
15960 "Property set function alist.
15961 Each entry should have the following format:
15963 (PROPERTY . READ-FUNCTION)
15965 The read function will be called with the same argument as
15966 `org-completing-read'.")
15968 (defun org-set-property-function (property)
15969 "Get the function that should be used to set PROPERTY.
15970 This is computed according to `org-property-set-functions-alist'."
15971 (or (cdr (assoc property org-property-set-functions-alist))
15972 'org-completing-read))
15974 (defun org-read-property-value (property)
15975 "Read PROPERTY value from user."
15976 (let* ((completion-ignore-case t)
15977 (allowed (org-property-get-allowed-values nil property 'table))
15978 (cur (org-entry-get nil property))
15979 (prompt (concat property " value"
15980 (if (and cur (string-match "\\S-" cur))
15981 (concat " [" cur "]") "") ": "))
15982 (set-function (org-set-property-function property))
15983 (val (if allowed
15984 (funcall set-function prompt allowed nil
15985 (not (get-text-property 0 'org-unrestricted
15986 (caar allowed))))
15987 (let (org-completion-use-ido org-completion-use-iswitchb)
15988 (funcall set-function prompt
15989 (mapcar 'list (org-property-values property))
15990 nil nil "" nil cur)))))
15991 (if (equal val "")
15993 val)))
15995 (defvar org-last-set-property nil)
15996 (defvar org-last-set-property-value nil)
15997 (defun org-read-property-name ()
15998 "Read a property name."
15999 (let* ((completion-ignore-case t)
16000 (keys (org-buffer-property-keys nil t t))
16001 (default-prop (or (save-excursion
16002 (save-match-data
16003 (beginning-of-line)
16004 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
16005 (null (string= (match-string 1) "END"))
16006 (match-string 1))))
16007 org-last-set-property))
16008 (property (org-icompleting-read
16009 (concat "Property"
16010 (if default-prop (concat " [" default-prop "]") "")
16011 ": ")
16012 (mapcar 'list keys)
16013 nil nil nil nil
16014 default-prop)))
16015 (if (member property keys)
16016 property
16017 (or (cdr (assoc (downcase property)
16018 (mapcar (lambda (x) (cons (downcase x) x))
16019 keys)))
16020 property))))
16022 (defun org-set-property-and-value (use-last)
16023 "Allow to set [PROPERTY]: [value] direction from prompt.
16024 When use-default, don't even ask, just use the last
16025 \"[PROPERTY]: [value]\" string from the history."
16026 (interactive "P")
16027 (let* ((completion-ignore-case t)
16028 (pv (or (and use-last org-last-set-property-value)
16029 (org-completing-read
16030 "Enter a \"[Property]: [value]\" pair: "
16031 nil nil nil nil nil
16032 org-last-set-property-value)))
16033 prop val)
16034 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16035 (setq prop (match-string 1 pv)
16036 val (match-string 2 pv))
16037 (org-set-property prop val))))
16039 (defun org-set-property (property value)
16040 "In the current entry, set PROPERTY to VALUE.
16041 When called interactively, this will prompt for a property name, offering
16042 completion on existing and default properties. And then it will prompt
16043 for a value, offering completion either on allowed values (via an inherited
16044 xxx_ALL property) or on existing values in other instances of this property
16045 in the current file."
16046 (interactive (list nil nil))
16047 (let* ((property (or property (org-read-property-name)))
16048 (value (or value (org-read-property-value property)))
16049 (fn (cdr (assoc property org-properties-postprocess-alist))))
16050 (setq org-last-set-property property)
16051 (setq org-last-set-property-value (concat property ": " value))
16052 ;; Possibly postprocess the inserted value:
16053 (when fn (setq value (funcall fn value)))
16054 (unless (equal (org-entry-get nil property) value)
16055 (org-entry-put nil property value))))
16057 (defun org-delete-property (property)
16058 "In the current entry, delete PROPERTY."
16059 (interactive
16060 (let* ((completion-ignore-case t)
16061 (cat (org-entry-get (point) "CATEGORY"))
16062 (props0 (org-entry-properties nil 'standard))
16063 (props (if cat props0
16064 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16065 (prop (if (< 1 (length props))
16066 (org-icompleting-read "Property: " props nil t)
16067 (caar props))))
16068 (list prop)))
16069 (if (org-entry-delete nil property)
16070 (message "Property %s deleted" property)))
16072 (defun org-delete-property-globally (property)
16073 "Remove PROPERTY globally, from all entries."
16074 (interactive
16075 (let* ((completion-ignore-case t)
16076 (prop (org-icompleting-read
16077 "Globally remove property: "
16078 (mapcar 'list (org-buffer-property-keys)))))
16079 (list prop)))
16080 (save-excursion
16081 (save-restriction
16082 (widen)
16083 (goto-char (point-min))
16084 (let ((cnt 0))
16085 (while (re-search-forward
16086 (org-re-property property)
16087 nil t)
16088 (setq cnt (1+ cnt))
16089 (delete-region (match-beginning 0) (1+ (point-at-eol))))
16090 (message "Property \"%s\" removed from %d entries" property cnt)))))
16092 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16094 (defun org-compute-property-at-point ()
16095 "Compute the property at point.
16096 This looks for an enclosing column format, extracts the operator and
16097 then applies it to the property in the column format's scope."
16098 (interactive)
16099 (unless (org-at-property-p)
16100 (user-error "Not at a property"))
16101 (let ((prop (org-match-string-no-properties 2)))
16102 (org-columns-get-format-and-top-level)
16103 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16104 (user-error "No operator defined for property %s" prop))
16105 (org-columns-compute prop)))
16107 (defvar org-property-allowed-value-functions nil
16108 "Hook for functions supplying allowed values for a specific property.
16109 The functions must take a single argument, the name of the property, and
16110 return a flat list of allowed values. If \":ETC\" is one of
16111 the values, this means that these values are intended as defaults for
16112 completion, but that other values should be allowed too.
16113 The functions must return nil if they are not responsible for this
16114 property.")
16116 (defun org-property-get-allowed-values (pom property &optional table)
16117 "Get allowed values for the property PROPERTY.
16118 When TABLE is non-nil, return an alist that can directly be used for
16119 completion."
16120 (let (vals)
16121 (cond
16122 ((equal property "TODO")
16123 (setq vals (org-with-point-at pom
16124 (append org-todo-keywords-1 '("")))))
16125 ((equal property "PRIORITY")
16126 (let ((n org-lowest-priority))
16127 (while (>= n org-highest-priority)
16128 (push (char-to-string n) vals)
16129 (setq n (1- n)))))
16130 ((member property org-special-properties))
16131 ((setq vals (run-hook-with-args-until-success
16132 'org-property-allowed-value-functions property)))
16134 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16135 (when (and vals (string-match "\\S-" vals))
16136 (setq vals (car (read-from-string (concat "(" vals ")"))))
16137 (setq vals (mapcar (lambda (x)
16138 (cond ((stringp x) x)
16139 ((numberp x) (number-to-string x))
16140 ((symbolp x) (symbol-name x))
16141 (t "???")))
16142 vals)))))
16143 (when (member ":ETC" vals)
16144 (setq vals (remove ":ETC" vals))
16145 (org-add-props (car vals) '(org-unrestricted t)))
16146 (if table (mapcar 'list vals) vals)))
16148 (defun org-property-previous-allowed-value (&optional previous)
16149 "Switch to the next allowed value for this property."
16150 (interactive)
16151 (org-property-next-allowed-value t))
16153 (defun org-property-next-allowed-value (&optional previous)
16154 "Switch to the next allowed value for this property."
16155 (interactive)
16156 (unless (org-at-property-p)
16157 (user-error "Not at a property"))
16158 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16159 (key (match-string 2))
16160 (value (match-string 3))
16161 (allowed (or (org-property-get-allowed-values (point) key)
16162 (and (member value '("[ ]" "[-]" "[X]"))
16163 '("[ ]" "[X]"))))
16164 (heading (save-match-data (nth 4 (org-heading-components))))
16165 nval)
16166 (unless allowed
16167 (user-error "Allowed values for this property have not been defined"))
16168 (if previous (setq allowed (reverse allowed)))
16169 (if (member value allowed)
16170 (setq nval (car (cdr (member value allowed)))))
16171 (setq nval (or nval (car allowed)))
16172 (if (equal nval value)
16173 (user-error "Only one allowed value for this property"))
16174 (org-at-property-p)
16175 (replace-match (concat " :" key ": " nval) t t)
16176 (org-indent-line)
16177 (beginning-of-line 1)
16178 (skip-chars-forward " \t")
16179 (when (equal prop org-effort-property)
16180 (org-refresh-property
16181 '((effort . identity)
16182 (effort-minutes . org-duration-string-to-minutes))
16183 nval)
16184 (when (string= org-clock-current-task heading)
16185 (setq org-clock-effort nval)
16186 (org-clock-update-mode-line)))
16187 (run-hook-with-args 'org-property-changed-functions key nval)))
16189 (defun org-find-olp (path &optional this-buffer)
16190 "Return a marker pointing to the entry at outline path OLP.
16191 If anything goes wrong, throw an error.
16192 You can wrap this call to catch the error like this:
16194 (condition-case msg
16195 (org-mobile-locate-entry (match-string 4))
16196 (error (nth 1 msg)))
16198 The return value will then be either a string with the error message,
16199 or a marker if everything is OK.
16201 If THIS-BUFFER is set, the outline path does not contain a file,
16202 only headings."
16203 (let* ((file (if this-buffer buffer-file-name (pop path)))
16204 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16205 (level 1)
16206 (lmin 1)
16207 (lmax 1)
16208 limit re end found pos heading cnt flevel)
16209 (unless buffer (error "File not found :%s" file))
16210 (with-current-buffer buffer
16211 (save-excursion
16212 (save-restriction
16213 (widen)
16214 (setq limit (point-max))
16215 (goto-char (point-min))
16216 (while (setq heading (pop path))
16217 (setq re (format org-complex-heading-regexp-format
16218 (regexp-quote heading)))
16219 (setq cnt 0 pos (point))
16220 (while (re-search-forward re end t)
16221 (setq level (- (match-end 1) (match-beginning 1)))
16222 (if (and (>= level lmin) (<= level lmax))
16223 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16224 (when (= cnt 0) (error "Heading not found on level %d: %s"
16225 lmax heading))
16226 (when (> cnt 1) (error "Heading not unique on level %d: %s"
16227 lmax heading))
16228 (goto-char found)
16229 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16230 (setq end (save-excursion (org-end-of-subtree t t))))
16231 (when (org-at-heading-p)
16232 (point-marker)))))))
16234 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16235 "Find node HEADING in BUFFER.
16236 Return a marker to the heading if it was found, or nil if not.
16237 If POS-ONLY is set, return just the position instead of a marker.
16239 The heading text must match exact, but it may have a TODO keyword,
16240 a priority cookie and tags in the standard locations."
16241 (with-current-buffer (or buffer (current-buffer))
16242 (save-excursion
16243 (save-restriction
16244 (widen)
16245 (goto-char (point-min))
16246 (let (case-fold-search)
16247 (if (re-search-forward
16248 (format org-complex-heading-regexp-format
16249 (regexp-quote heading)) nil t)
16250 (if pos-only
16251 (match-beginning 0)
16252 (move-marker (make-marker) (match-beginning 0)))))))))
16254 (defun org-find-exact-heading-in-directory (heading &optional dir)
16255 "Find Org node headline HEADING in all .org files in directory DIR.
16256 When the target headline is found, return a marker to this location."
16257 (let ((files (directory-files (or dir default-directory)
16258 t "\\`[^.#].*\\.org\\'"))
16259 file visiting m buffer)
16260 (catch 'found
16261 (while (setq file (pop files))
16262 (message "trying %s" file)
16263 (setq visiting (org-find-base-buffer-visiting file))
16264 (setq buffer (or visiting (find-file-noselect file)))
16265 (setq m (org-find-exact-headline-in-buffer
16266 heading buffer))
16267 (when (and (not m) (not visiting)) (kill-buffer buffer))
16268 (and m (throw 'found m))))))
16270 (defun org-find-entry-with-id (ident)
16271 "Locate the entry that contains the ID property with exact value IDENT.
16272 IDENT can be a string, a symbol or a number, this function will search for
16273 the string representation of it.
16274 Return the position where this entry starts, or nil if there is no such entry."
16275 (interactive "sID: ")
16276 (let ((id (cond
16277 ((stringp ident) ident)
16278 ((symbol-name ident) (symbol-name ident))
16279 ((numberp ident) (number-to-string ident))
16280 (t (error "IDENT %s must be a string, symbol or number" ident))))
16281 (case-fold-search nil))
16282 (save-excursion
16283 (save-restriction
16284 (widen)
16285 (goto-char (point-min))
16286 (when (re-search-forward
16287 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16288 nil t)
16289 (org-back-to-heading t)
16290 (point))))))
16292 ;;;; Timestamps
16294 (defvar org-last-changed-timestamp nil)
16295 (defvar org-last-inserted-timestamp nil
16296 "The last time stamp inserted with `org-insert-time-stamp'.")
16297 (defvar org-ts-what) ; dynamically scoped parameter
16299 (defun org-time-stamp (arg &optional inactive)
16300 "Prompt for a date/time and insert a time stamp.
16301 If the user specifies a time like HH:MM or if this command is
16302 called with at least one prefix argument, the time stamp contains
16303 the date and the time. Otherwise, only the date is be included.
16305 All parts of a date not specified by the user is filled in from
16306 the current date/time. So if you just press return without
16307 typing anything, the time stamp will represent the current
16308 date/time.
16310 If there is already a timestamp at the cursor, it will be
16311 modified.
16313 With two universal prefix arguments, insert an active timestamp
16314 with the current time without prompting the user.
16316 When called from lisp, the timestamp is inactive if INACTIVE is
16317 non-nil."
16318 (interactive "P")
16319 (let* ((ts nil)
16320 (default-time
16321 ;; Default time is either today, or, when entering a range,
16322 ;; the range start.
16323 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16324 (save-excursion
16325 (re-search-backward
16326 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16327 (- (point) 20) t)))
16328 (apply 'encode-time (org-parse-time-string (match-string 1)))
16329 (current-time)))
16330 (default-input (and ts (org-get-compact-tod ts)))
16331 (repeater (save-excursion
16332 (save-match-data
16333 (beginning-of-line)
16334 (when (re-search-forward
16335 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16336 (save-excursion (progn (end-of-line) (point))) t)
16337 (match-string 0)))))
16338 org-time-was-given org-end-time-was-given time)
16339 (cond
16340 ((and (org-at-timestamp-p t)
16341 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16342 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16343 (insert "--")
16344 (setq time (let ((this-command this-command))
16345 (org-read-date arg 'totime nil nil
16346 default-time default-input inactive)))
16347 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16348 ((org-at-timestamp-p t)
16349 (setq time (let ((this-command this-command))
16350 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16351 (when (org-at-timestamp-p t) ; just to get the match data
16352 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16353 (replace-match "")
16354 (setq org-last-changed-timestamp
16355 (org-insert-time-stamp
16356 time (or org-time-was-given arg)
16357 inactive nil nil (list org-end-time-was-given)))
16358 (when repeater (goto-char (1- (point))) (insert " " repeater)
16359 (setq org-last-changed-timestamp
16360 (concat (substring org-last-inserted-timestamp 0 -1)
16361 " " repeater ">"))))
16362 (message "Timestamp updated"))
16363 ((equal arg '(16))
16364 (org-insert-time-stamp (current-time) t inactive))
16366 (setq time (let ((this-command this-command))
16367 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16368 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16369 nil nil (list org-end-time-was-given))))))
16371 ;; FIXME: can we use this for something else, like computing time differences?
16372 (defun org-get-compact-tod (s)
16373 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16374 (let* ((t1 (match-string 1 s))
16375 (h1 (string-to-number (match-string 2 s)))
16376 (m1 (string-to-number (match-string 3 s)))
16377 (t2 (and (match-end 4) (match-string 5 s)))
16378 (h2 (and t2 (string-to-number (match-string 6 s))))
16379 (m2 (and t2 (string-to-number (match-string 7 s))))
16380 dh dm)
16381 (if (not t2)
16383 (setq dh (- h2 h1) dm (- m2 m1))
16384 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16385 (concat t1 "+" (number-to-string dh)
16386 (and (/= 0 dm) (format ":%02d" dm)))))))
16388 (defun org-time-stamp-inactive (&optional arg)
16389 "Insert an inactive time stamp.
16390 An inactive time stamp is enclosed in square brackets instead of angle
16391 brackets. It is inactive in the sense that it does not trigger agenda entries,
16392 does not link to the calendar and cannot be changed with the S-cursor keys.
16393 So these are more for recording a certain time/date."
16394 (interactive "P")
16395 (org-time-stamp arg 'inactive))
16397 (defvar org-date-ovl (make-overlay 1 1))
16398 (overlay-put org-date-ovl 'face 'org-date-selected)
16399 (org-detach-overlay org-date-ovl)
16401 (defvar org-ans1) ; dynamically scoped parameter
16402 (defvar org-ans2) ; dynamically scoped parameter
16404 (defvar org-plain-time-of-day-regexp) ; defined below
16406 (defvar org-overriding-default-time nil) ; dynamically scoped
16407 (defvar org-read-date-overlay nil)
16408 (defvar org-dcst nil) ; dynamically scoped
16409 (defvar org-read-date-history nil)
16410 (defvar org-read-date-final-answer nil)
16411 (defvar org-read-date-analyze-futurep nil)
16412 (defvar org-read-date-analyze-forced-year nil)
16413 (defvar org-read-date-inactive)
16415 (defvar org-read-date-minibuffer-local-map
16416 (let* ((org-replace-disputed-keys nil)
16417 (map (make-sparse-keymap)))
16418 (set-keymap-parent map minibuffer-local-map)
16419 (org-defkey map (kbd ".")
16420 (lambda () (interactive)
16421 ;; Are we at the beginning of the prompt?
16422 (if (looking-back "^[^:]+: ")
16423 (org-eval-in-calendar '(calendar-goto-today))
16424 (insert "."))))
16425 (org-defkey map (kbd "C-.")
16426 (lambda () (interactive)
16427 (org-eval-in-calendar '(calendar-goto-today))))
16428 (org-defkey map [(meta shift left)]
16429 (lambda () (interactive)
16430 (org-eval-in-calendar '(calendar-backward-month 1))))
16431 (org-defkey map [(meta shift right)]
16432 (lambda () (interactive)
16433 (org-eval-in-calendar '(calendar-forward-month 1))))
16434 (org-defkey map [(meta shift up)]
16435 (lambda () (interactive)
16436 (org-eval-in-calendar '(calendar-backward-year 1))))
16437 (org-defkey map [(meta shift down)]
16438 (lambda () (interactive)
16439 (org-eval-in-calendar '(calendar-forward-year 1))))
16440 (org-defkey map [?\e (shift left)]
16441 (lambda () (interactive)
16442 (org-eval-in-calendar '(calendar-backward-month 1))))
16443 (org-defkey map [?\e (shift right)]
16444 (lambda () (interactive)
16445 (org-eval-in-calendar '(calendar-forward-month 1))))
16446 (org-defkey map [?\e (shift up)]
16447 (lambda () (interactive)
16448 (org-eval-in-calendar '(calendar-backward-year 1))))
16449 (org-defkey map [?\e (shift down)]
16450 (lambda () (interactive)
16451 (org-eval-in-calendar '(calendar-forward-year 1))))
16452 (org-defkey map [(shift up)]
16453 (lambda () (interactive)
16454 (org-eval-in-calendar '(calendar-backward-week 1))))
16455 (org-defkey map [(shift down)]
16456 (lambda () (interactive)
16457 (org-eval-in-calendar '(calendar-forward-week 1))))
16458 (org-defkey map [(shift left)]
16459 (lambda () (interactive)
16460 (org-eval-in-calendar '(calendar-backward-day 1))))
16461 (org-defkey map [(shift right)]
16462 (lambda () (interactive)
16463 (org-eval-in-calendar '(calendar-forward-day 1))))
16464 (org-defkey map "!"
16465 (lambda () (interactive)
16466 (org-eval-in-calendar '(diary-view-entries))
16467 (message "")))
16468 (org-defkey map ">"
16469 (lambda () (interactive)
16470 (org-eval-in-calendar '(scroll-calendar-left 1))))
16471 (org-defkey map "<"
16472 (lambda () (interactive)
16473 (org-eval-in-calendar '(scroll-calendar-right 1))))
16474 (org-defkey map "\C-v"
16475 (lambda () (interactive)
16476 (org-eval-in-calendar
16477 '(calendar-scroll-left-three-months 1))))
16478 (org-defkey map "\M-v"
16479 (lambda () (interactive)
16480 (org-eval-in-calendar
16481 '(calendar-scroll-right-three-months 1))))
16482 map)
16483 "Keymap for minibuffer commands when using `org-read-date'.")
16485 (defvar org-def)
16486 (defvar org-defdecode)
16487 (defvar org-with-time)
16489 (defun org-read-date (&optional org-with-time to-time from-string prompt
16490 default-time default-input inactive)
16491 "Read a date, possibly a time, and make things smooth for the user.
16492 The prompt will suggest to enter an ISO date, but you can also enter anything
16493 which will at least partially be understood by `parse-time-string'.
16494 Unrecognized parts of the date will default to the current day, month, year,
16495 hour and minute. If this command is called to replace a timestamp at point,
16496 or to enter the second timestamp of a range, the default time is taken
16497 from the existing stamp. Furthermore, the command prefers the future,
16498 so if you are giving a date where the year is not given, and the day-month
16499 combination is already past in the current year, it will assume you
16500 mean next year. For details, see the manual. A few examples:
16502 3-2-5 --> 2003-02-05
16503 feb 15 --> currentyear-02-15
16504 2/15 --> currentyear-02-15
16505 sep 12 9 --> 2009-09-12
16506 12:45 --> today 12:45
16507 22 sept 0:34 --> currentyear-09-22 0:34
16508 12 --> currentyear-currentmonth-12
16509 Fri --> nearest Friday after today
16510 -Tue --> last Tuesday
16511 etc.
16513 Furthermore you can specify a relative date by giving, as the *first* thing
16514 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16515 change in days weeks, months, years.
16516 With a single plus or minus, the date is relative to today. With a double
16517 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16518 +4d --> four days from today
16519 +4 --> same as above
16520 +2w --> two weeks from today
16521 ++5 --> five days from default date
16523 The function understands only English month and weekday abbreviations.
16525 While prompting, a calendar is popped up - you can also select the
16526 date with the mouse (button 1). The calendar shows a period of three
16527 months. To scroll it to other months, use the keys `>' and `<'.
16528 If you don't like the calendar, turn it off with
16529 \(setq org-read-date-popup-calendar nil)
16531 With optional argument TO-TIME, the date will immediately be converted
16532 to an internal time.
16533 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16534 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16535 still enter a time, and this function will inform the calling routine
16536 about this change. The calling routine may then choose to change the
16537 format used to insert the time stamp into the buffer to include the time.
16538 With optional argument FROM-STRING, read from this string instead from
16539 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16540 the time/date that is used for everything that is not specified by the
16541 user."
16542 (require 'parse-time)
16543 (let* ((org-time-stamp-rounding-minutes
16544 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16545 (org-dcst org-display-custom-times)
16546 (ct (org-current-time))
16547 (org-def (or org-overriding-default-time default-time ct))
16548 (org-defdecode (decode-time org-def))
16549 (dummy (progn
16550 (when (< (nth 2 org-defdecode) org-extend-today-until)
16551 (setcar (nthcdr 2 org-defdecode) -1)
16552 (setcar (nthcdr 1 org-defdecode) 59)
16553 (setq org-def (apply 'encode-time org-defdecode)
16554 org-defdecode (decode-time org-def)))))
16555 (mouse-autoselect-window nil) ; Don't let the mouse jump
16556 (calendar-frame-setup nil)
16557 (calendar-setup nil)
16558 (calendar-move-hook nil)
16559 (calendar-view-diary-initially-flag nil)
16560 (calendar-view-holidays-initially-flag nil)
16561 (timestr (format-time-string
16562 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16563 (prompt (concat (if prompt (concat prompt " ") "")
16564 (format "Date+time [%s]: " timestr)))
16565 ans (org-ans0 "") org-ans1 org-ans2 final)
16567 (cond
16568 (from-string (setq ans from-string))
16569 (org-read-date-popup-calendar
16570 (save-excursion
16571 (save-window-excursion
16572 (calendar)
16573 (org-eval-in-calendar '(setq cursor-type nil) t)
16574 (unwind-protect
16575 (progn
16576 (calendar-forward-day (- (time-to-days org-def)
16577 (calendar-absolute-from-gregorian
16578 (calendar-current-date))))
16579 (org-eval-in-calendar nil t)
16580 (let* ((old-map (current-local-map))
16581 (map (copy-keymap calendar-mode-map))
16582 (minibuffer-local-map
16583 (copy-keymap org-read-date-minibuffer-local-map)))
16584 (org-defkey map (kbd "RET") 'org-calendar-select)
16585 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16586 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16587 (unwind-protect
16588 (progn
16589 (use-local-map map)
16590 (setq org-read-date-inactive inactive)
16591 (add-hook 'post-command-hook 'org-read-date-display)
16592 (setq org-ans0 (read-string prompt default-input
16593 'org-read-date-history nil))
16594 ;; org-ans0: from prompt
16595 ;; org-ans1: from mouse click
16596 ;; org-ans2: from calendar motion
16597 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16598 (remove-hook 'post-command-hook 'org-read-date-display)
16599 (use-local-map old-map)
16600 (when org-read-date-overlay
16601 (delete-overlay org-read-date-overlay)
16602 (setq org-read-date-overlay nil)))))
16603 (bury-buffer "*Calendar*")))))
16605 (t ; Naked prompt only
16606 (unwind-protect
16607 (setq ans (read-string prompt default-input
16608 'org-read-date-history timestr))
16609 (when org-read-date-overlay
16610 (delete-overlay org-read-date-overlay)
16611 (setq org-read-date-overlay nil)))))
16613 (setq final (org-read-date-analyze ans org-def org-defdecode))
16615 (when org-read-date-analyze-forced-year
16616 (message "Year was forced into %s"
16617 (if org-read-date-force-compatible-dates
16618 "compatible range (1970-2037)"
16619 "range representable on this machine"))
16620 (ding))
16622 ;; One round trip to get rid of 34th of August and stuff like that....
16623 (setq final (decode-time (apply 'encode-time final)))
16625 (setq org-read-date-final-answer ans)
16627 (if to-time
16628 (apply 'encode-time final)
16629 (if (and (boundp 'org-time-was-given) org-time-was-given)
16630 (format "%04d-%02d-%02d %02d:%02d"
16631 (nth 5 final) (nth 4 final) (nth 3 final)
16632 (nth 2 final) (nth 1 final))
16633 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16635 (defun org-read-date-display ()
16636 "Display the current date prompt interpretation in the minibuffer."
16637 (when org-read-date-display-live
16638 (when org-read-date-overlay
16639 (delete-overlay org-read-date-overlay))
16640 (when (minibufferp (current-buffer))
16641 (save-excursion
16642 (end-of-line 1)
16643 (while (not (equal (buffer-substring
16644 (max (point-min) (- (point) 4)) (point))
16645 " "))
16646 (insert " ")))
16647 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16648 " " (or org-ans1 org-ans2)))
16649 (org-end-time-was-given nil)
16650 (f (org-read-date-analyze ans org-def org-defdecode))
16651 (fmts (if org-dcst
16652 org-time-stamp-custom-formats
16653 org-time-stamp-formats))
16654 (fmt (if (or org-with-time
16655 (and (boundp 'org-time-was-given) org-time-was-given))
16656 (cdr fmts)
16657 (car fmts)))
16658 (txt (format-time-string fmt (apply 'encode-time f)))
16659 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16660 (txt (concat "=> " txt)))
16661 (when (and org-end-time-was-given
16662 (string-match org-plain-time-of-day-regexp txt))
16663 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16664 org-end-time-was-given
16665 (substring txt (match-end 0)))))
16666 (when org-read-date-analyze-futurep
16667 (setq txt (concat txt " (=>F)")))
16668 (setq org-read-date-overlay
16669 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16670 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16672 (defun org-read-date-analyze (ans org-def org-defdecode)
16673 "Analyze the combined answer of the date prompt."
16674 ;; FIXME: cleanup and comment
16675 (let ((nowdecode (decode-time (current-time)))
16676 delta deltan deltaw deltadef year month day
16677 hour minute second wday pm h2 m2 tl wday1
16678 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16679 (setq org-read-date-analyze-futurep nil
16680 org-read-date-analyze-forced-year nil)
16681 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16682 (setq ans "+0"))
16684 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16685 (setq ans (replace-match "" t t ans)
16686 deltan (car delta)
16687 deltaw (nth 1 delta)
16688 deltadef (nth 2 delta)))
16690 ;; Check if there is an iso week date in there. If yes, store the
16691 ;; info and postpone interpreting it until the rest of the parsing
16692 ;; is done.
16693 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16694 (setq iso-year (if (match-end 1)
16695 (org-small-year-to-year
16696 (string-to-number (match-string 1 ans))))
16697 iso-weekday (if (match-end 3)
16698 (string-to-number (match-string 3 ans)))
16699 iso-week (string-to-number (match-string 2 ans)))
16700 (setq ans (replace-match "" t t ans)))
16702 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16703 (when (string-match
16704 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16705 (setq year (if (match-end 2)
16706 (string-to-number (match-string 2 ans))
16707 (progn (setq kill-year t)
16708 (string-to-number (format-time-string "%Y"))))
16709 month (string-to-number (match-string 3 ans))
16710 day (string-to-number (match-string 4 ans)))
16711 (if (< year 100) (setq year (+ 2000 year)))
16712 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16713 t nil ans)))
16715 ;; Help matching dotted european dates
16716 (when (string-match
16717 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16718 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16719 (setq kill-year t)
16720 (string-to-number (format-time-string "%Y")))
16721 day (string-to-number (match-string 1 ans))
16722 month (string-to-number (match-string 2 ans))
16723 ans (replace-match (format "%04d-%02d-%02d" year month day)
16724 t nil ans)))
16726 ;; Help matching american dates, like 5/30 or 5/30/7
16727 (when (string-match
16728 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16729 (setq year (if (match-end 4)
16730 (string-to-number (match-string 4 ans))
16731 (progn (setq kill-year t)
16732 (string-to-number (format-time-string "%Y"))))
16733 month (string-to-number (match-string 1 ans))
16734 day (string-to-number (match-string 2 ans)))
16735 (if (< year 100) (setq year (+ 2000 year)))
16736 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16737 t nil ans)))
16738 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16739 ;; If there is a time with am/pm, and *no* time without it, we convert
16740 ;; so that matching will be successful.
16741 (loop for i from 1 to 2 do ; twice, for end time as well
16742 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16743 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16744 (setq hour (string-to-number (match-string 1 ans))
16745 minute (if (match-end 3)
16746 (string-to-number (match-string 3 ans))
16748 pm (equal ?p
16749 (string-to-char (downcase (match-string 4 ans)))))
16750 (if (and (= hour 12) (not pm))
16751 (setq hour 0)
16752 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16753 (setq ans (replace-match (format "%02d:%02d" hour minute)
16754 t t ans))))
16756 ;; Check if a time range is given as a duration
16757 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16758 (setq hour (string-to-number (match-string 1 ans))
16759 h2 (+ hour (string-to-number (match-string 3 ans)))
16760 minute (string-to-number (match-string 2 ans))
16761 m2 (+ minute (if (match-end 5) (string-to-number
16762 (match-string 5 ans))0)))
16763 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16764 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16765 t t ans)))
16767 ;; Check if there is a time range
16768 (when (boundp 'org-end-time-was-given)
16769 (setq org-time-was-given nil)
16770 (when (and (string-match org-plain-time-of-day-regexp ans)
16771 (match-end 8))
16772 (setq org-end-time-was-given (match-string 8 ans))
16773 (setq ans (concat (substring ans 0 (match-beginning 7))
16774 (substring ans (match-end 7))))))
16776 (setq tl (parse-time-string ans)
16777 day (or (nth 3 tl) (nth 3 org-defdecode))
16778 month (or (nth 4 tl)
16779 (if (and org-read-date-prefer-future
16780 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16781 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16782 (nth 4 org-defdecode)))
16783 year (or (and (not kill-year) (nth 5 tl))
16784 (if (and org-read-date-prefer-future
16785 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16786 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16787 (nth 5 org-defdecode)))
16788 hour (or (nth 2 tl) (nth 2 org-defdecode))
16789 minute (or (nth 1 tl) (nth 1 org-defdecode))
16790 second (or (nth 0 tl) 0)
16791 wday (nth 6 tl))
16793 (when (and (eq org-read-date-prefer-future 'time)
16794 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16795 (equal day (nth 3 nowdecode))
16796 (equal month (nth 4 nowdecode))
16797 (equal year (nth 5 nowdecode))
16798 (nth 2 tl)
16799 (or (< (nth 2 tl) (nth 2 nowdecode))
16800 (and (= (nth 2 tl) (nth 2 nowdecode))
16801 (nth 1 tl)
16802 (< (nth 1 tl) (nth 1 nowdecode)))))
16803 (setq day (1+ day)
16804 futurep t))
16806 ;; Special date definitions below
16807 (cond
16808 (iso-week
16809 ;; There was an iso week
16810 (require 'cal-iso)
16811 (setq futurep nil)
16812 (setq year (or iso-year year)
16813 day (or iso-weekday wday 1)
16814 wday nil ; to make sure that the trigger below does not match
16815 iso-date (calendar-gregorian-from-absolute
16816 (calendar-absolute-from-iso
16817 (list iso-week day year))))
16818 ; FIXME: Should we also push ISO weeks into the future?
16819 ; (when (and org-read-date-prefer-future
16820 ; (not iso-year)
16821 ; (< (calendar-absolute-from-gregorian iso-date)
16822 ; (time-to-days (current-time))))
16823 ; (setq year (1+ year)
16824 ; iso-date (calendar-gregorian-from-absolute
16825 ; (calendar-absolute-from-iso
16826 ; (list iso-week day year)))))
16827 (setq month (car iso-date)
16828 year (nth 2 iso-date)
16829 day (nth 1 iso-date)))
16830 (deltan
16831 (setq futurep nil)
16832 (unless deltadef
16833 (let ((now (decode-time (current-time))))
16834 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16835 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16836 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16837 ((equal deltaw "m") (setq month (+ month deltan)))
16838 ((equal deltaw "y") (setq year (+ year deltan)))))
16839 ((and wday (not (nth 3 tl)))
16840 ;; Weekday was given, but no day, so pick that day in the week
16841 ;; on or after the derived date.
16842 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16843 (unless (equal wday wday1)
16844 (setq day (+ day (% (- wday wday1 -7) 7))))))
16845 (if (and (boundp 'org-time-was-given)
16846 (nth 2 tl))
16847 (setq org-time-was-given t))
16848 (if (< year 100) (setq year (+ 2000 year)))
16849 ;; Check of the date is representable
16850 (if org-read-date-force-compatible-dates
16851 (progn
16852 (if (< year 1970)
16853 (setq year 1970 org-read-date-analyze-forced-year t))
16854 (if (> year 2037)
16855 (setq year 2037 org-read-date-analyze-forced-year t)))
16856 (condition-case nil
16857 (ignore (encode-time second minute hour day month year))
16858 (error
16859 (setq year (nth 5 org-defdecode))
16860 (setq org-read-date-analyze-forced-year t))))
16861 (setq org-read-date-analyze-futurep futurep)
16862 (list second minute hour day month year)))
16864 (defvar parse-time-weekdays)
16865 (defun org-read-date-get-relative (s today default)
16866 "Check string S for special relative date string.
16867 TODAY and DEFAULT are internal times, for today and for a default.
16868 Return shift list (N what def-flag)
16869 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16870 N is the number of WHATs to shift.
16871 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16872 the DEFAULT date rather than TODAY."
16873 (require 'parse-time)
16874 (when (and
16875 (string-match
16876 (concat
16877 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16878 "\\([0-9]+\\)?"
16879 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16880 "\\([ \t]\\|$\\)") s)
16881 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16882 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16883 (string-to-char (substring (match-string 1 s) -1))
16884 ?+))
16885 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16886 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16887 (what (if (match-end 3) (match-string 3 s) "d"))
16888 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16889 (date (if rel default today))
16890 (wday (nth 6 (decode-time date)))
16891 delta)
16892 (if wday1
16893 (progn
16894 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16895 (if (= delta 0) (setq delta 7))
16896 (if (= dir ?-)
16897 (progn
16898 (setq delta (- delta 7))
16899 (if (= delta 0) (setq delta -7))))
16900 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16901 (list delta "d" rel))
16902 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16904 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16905 "Turn a user-specified date into the internal representation.
16906 The internal representation needed by the calendar is (month day year).
16907 This is a wrapper to handle the brain-dead convention in calendar that
16908 user function argument order change dependent on argument order."
16909 (if (boundp 'calendar-date-style)
16910 (cond
16911 ((eq calendar-date-style 'american)
16912 (list arg1 arg2 arg3))
16913 ((eq calendar-date-style 'european)
16914 (list arg2 arg1 arg3))
16915 ((eq calendar-date-style 'iso)
16916 (list arg2 arg3 arg1)))
16917 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16918 (if (org-bound-and-true-p european-calendar-style)
16919 (list arg2 arg1 arg3)
16920 (list arg1 arg2 arg3)))))
16922 (defun org-eval-in-calendar (form &optional keepdate)
16923 "Eval FORM in the calendar window and return to current window.
16924 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16925 otherwise stick to the current value of `org-ans2'."
16926 (let ((sf (selected-frame))
16927 (sw (selected-window)))
16928 (select-window (get-buffer-window "*Calendar*" t))
16929 (eval form)
16930 (when (and (not keepdate) (calendar-cursor-to-date))
16931 (let* ((date (calendar-cursor-to-date))
16932 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16933 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16934 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16935 (select-window sw)
16936 (org-select-frame-set-input-focus sf)))
16938 (defun org-calendar-select ()
16939 "Return to `org-read-date' with the date currently selected.
16940 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16941 (interactive)
16942 (when (calendar-cursor-to-date)
16943 (let* ((date (calendar-cursor-to-date))
16944 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16945 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16946 (if (active-minibuffer-window) (exit-minibuffer))))
16948 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16949 "Insert a date stamp for the date given by the internal TIME.
16950 WITH-HM means use the stamp format that includes the time of the day.
16951 INACTIVE means use square brackets instead of angular ones, so that the
16952 stamp will not contribute to the agenda.
16953 PRE and POST are optional strings to be inserted before and after the
16954 stamp.
16955 The command returns the inserted time stamp."
16956 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16957 stamp)
16958 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16959 (insert-before-markers (or pre ""))
16960 (when (listp extra)
16961 (setq extra (car extra))
16962 (if (and (stringp extra)
16963 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16964 (setq extra (format "-%02d:%02d"
16965 (string-to-number (match-string 1 extra))
16966 (string-to-number (match-string 2 extra))))
16967 (setq extra nil)))
16968 (when extra
16969 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16970 (insert-before-markers (setq stamp (format-time-string fmt time)))
16971 (insert-before-markers (or post ""))
16972 (setq org-last-inserted-timestamp stamp)))
16974 (defun org-toggle-time-stamp-overlays ()
16975 "Toggle the use of custom time stamp formats."
16976 (interactive)
16977 (setq org-display-custom-times (not org-display-custom-times))
16978 (unless org-display-custom-times
16979 (let ((p (point-min)) (bmp (buffer-modified-p)))
16980 (while (setq p (next-single-property-change p 'display))
16981 (if (and (get-text-property p 'display)
16982 (eq (get-text-property p 'face) 'org-date))
16983 (remove-text-properties
16984 p (setq p (next-single-property-change p 'display))
16985 '(display t))))
16986 (set-buffer-modified-p bmp)))
16987 (if (featurep 'xemacs)
16988 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16989 (org-restart-font-lock)
16990 (setq org-table-may-need-update t)
16991 (if org-display-custom-times
16992 (message "Time stamps are overlaid with custom format")
16993 (message "Time stamp overlays removed")))
16995 (defun org-display-custom-time (beg end)
16996 "Overlay modified time stamp format over timestamp between BEG and END."
16997 (let* ((ts (buffer-substring beg end))
16998 t1 w1 with-hm tf time str w2 (off 0))
16999 (save-match-data
17000 (setq t1 (org-parse-time-string ts t))
17001 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17002 (setq off (- (match-end 0) (match-beginning 0)))))
17003 (setq end (- end off))
17004 (setq w1 (- end beg)
17005 with-hm (and (nth 1 t1) (nth 2 t1))
17006 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17007 time (org-fix-decoded-time t1)
17008 str (org-add-props
17009 (format-time-string
17010 (substring tf 1 -1) (apply 'encode-time time))
17011 nil 'mouse-face 'highlight)
17012 w2 (length str))
17013 (if (not (= w2 w1))
17014 (add-text-properties (1+ beg) (+ 2 beg)
17015 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17016 (if (featurep 'xemacs)
17017 (progn
17018 (put-text-property beg end 'invisible t)
17019 (put-text-property beg end 'end-glyph (make-glyph str)))
17020 (put-text-property beg end 'display str))))
17022 (defun org-translate-time (string)
17023 "Translate all timestamps in STRING to custom format.
17024 But do this only if the variable `org-display-custom-times' is set."
17025 (when org-display-custom-times
17026 (save-match-data
17027 (let* ((start 0)
17028 (re org-ts-regexp-both)
17029 t1 with-hm inactive tf time str beg end)
17030 (while (setq start (string-match re string start))
17031 (setq beg (match-beginning 0)
17032 end (match-end 0)
17033 t1 (save-match-data
17034 (org-parse-time-string (substring string beg end) t))
17035 with-hm (and (nth 1 t1) (nth 2 t1))
17036 inactive (equal (substring string beg (1+ beg)) "[")
17037 tf (funcall (if with-hm 'cdr 'car)
17038 org-time-stamp-custom-formats)
17039 time (org-fix-decoded-time t1)
17040 str (format-time-string
17041 (concat
17042 (if inactive "[" "<") (substring tf 1 -1)
17043 (if inactive "]" ">"))
17044 (apply 'encode-time time))
17045 string (replace-match str t t string)
17046 start (+ start (length str)))))))
17047 string)
17049 (defun org-fix-decoded-time (time)
17050 "Set 0 instead of nil for the first 6 elements of time.
17051 Don't touch the rest."
17052 (let ((n 0))
17053 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17055 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
17057 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17058 "Difference between TIMESTAMP-STRING and now in days.
17059 If SECONDS is non-nil, return the difference in seconds."
17060 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
17061 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17062 (funcall fdiff (current-time)))))
17064 (defun org-deadline-close (timestamp-string &optional ndays)
17065 "Is the time in TIMESTAMP-STRING close to the current date?"
17066 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17067 (and (< (org-time-stamp-to-now timestamp-string) ndays)
17068 (not (org-entry-is-done-p))))
17070 (defun org-get-wdays (ts &optional delay zero-delay)
17071 "Get the deadline lead time appropriate for timestring TS.
17072 When DELAY is non-nil, get the delay time for scheduled items
17073 instead of the deadline lead time. When ZERO-DELAY is non-nil
17074 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17075 don't try to find the delay cookie in the scheduled timestamp."
17076 (let ((tv (if delay org-scheduled-delay-days
17077 org-deadline-warning-days)))
17078 (cond
17079 ((or (and delay (< tv 0))
17080 (and delay zero-delay (<= tv 0))
17081 (and (not delay) (<= tv 0)))
17082 ;; Enforce this value no matter what
17083 (- tv))
17084 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17085 ;; lead time is specified.
17086 (floor (* (string-to-number (match-string 1 ts))
17087 (cdr (assoc (match-string 2 ts)
17088 '(("d" . 1) ("w" . 7)
17089 ("m" . 30.4) ("y" . 365.25)
17090 ("h" . 0.041667)))))))
17091 ;; go for the default.
17092 (t tv))))
17094 (defun org-calendar-select-mouse (ev)
17095 "Return to `org-read-date' with the date currently selected.
17096 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17097 (interactive "e")
17098 (mouse-set-point ev)
17099 (when (calendar-cursor-to-date)
17100 (let* ((date (calendar-cursor-to-date))
17101 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17102 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17103 (if (active-minibuffer-window) (exit-minibuffer))))
17105 (defun org-check-deadlines (ndays)
17106 "Check if there are any deadlines due or past due.
17107 A deadline is considered due if it happens within `org-deadline-warning-days'
17108 days from today's date. If the deadline appears in an entry marked DONE,
17109 it is not shown. The prefix arg NDAYS can be used to test that many
17110 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17111 (interactive "P")
17112 (let* ((org-warn-days
17113 (cond
17114 ((equal ndays '(4)) 100000)
17115 (ndays (prefix-numeric-value ndays))
17116 (t (abs org-deadline-warning-days))))
17117 (case-fold-search nil)
17118 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17119 (callback
17120 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
17122 (message "%d deadlines past-due or due within %d days"
17123 (org-occur regexp nil callback)
17124 org-warn-days)))
17126 (defsubst org-re-timestamp (type)
17127 "Return a regexp for timestamp TYPE.
17128 Allowed values for TYPE are:
17130 all: all timestamps
17131 active: only active timestamps (<...>)
17132 inactive: only inactive timestamps ([...])
17133 scheduled: only scheduled timestamps
17134 deadline: only deadline timestamps
17135 closed: only closed time-stamps
17137 When TYPE is nil, fall back on returning a regexp that matches
17138 both scheduled and deadline timestamps."
17139 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
17140 ((eq type 'active) org-ts-regexp)
17141 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
17142 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
17143 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17144 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
17145 ((eq type 'scheduled-or-deadline)
17146 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
17148 (defun org-check-before-date (date)
17149 "Check if there are deadlines or scheduled entries before DATE."
17150 (interactive (list (org-read-date)))
17151 (let ((case-fold-search nil)
17152 (regexp (org-re-timestamp org-ts-type))
17153 (callback
17154 (lambda () (time-less-p
17155 (org-time-string-to-time (match-string 1))
17156 (org-time-string-to-time date)))))
17157 (message "%d entries before %s"
17158 (org-occur regexp nil callback) date)))
17160 (defun org-check-after-date (date)
17161 "Check if there are deadlines or scheduled entries after DATE."
17162 (interactive (list (org-read-date)))
17163 (let ((case-fold-search nil)
17164 (regexp (org-re-timestamp org-ts-type))
17165 (callback
17166 (lambda () (not
17167 (time-less-p
17168 (org-time-string-to-time (match-string 1))
17169 (org-time-string-to-time date))))))
17170 (message "%d entries after %s"
17171 (org-occur regexp nil callback) date)))
17173 (defun org-check-dates-range (start-date end-date)
17174 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17175 (interactive (list (org-read-date nil nil nil "Range starts")
17176 (org-read-date nil nil nil "Range end")))
17177 (let ((case-fold-search nil)
17178 (regexp (org-re-timestamp org-ts-type))
17179 (callback
17180 (lambda ()
17181 (let ((match (match-string 1)))
17182 (and
17183 (not (time-less-p
17184 (org-time-string-to-time match)
17185 (org-time-string-to-time start-date)))
17186 (time-less-p
17187 (org-time-string-to-time match)
17188 (org-time-string-to-time end-date)))))))
17189 (message "%d entries between %s and %s"
17190 (org-occur regexp nil callback) start-date end-date)))
17192 (defun org-evaluate-time-range (&optional to-buffer)
17193 "Evaluate a time range by computing the difference between start and end.
17194 Normally the result is just printed in the echo area, but with prefix arg
17195 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17196 If the time range is actually in a table, the result is inserted into the
17197 next column.
17198 For time difference computation, a year is assumed to be exactly 365
17199 days in order to avoid rounding problems."
17200 (interactive "P")
17202 (org-clock-update-time-maybe)
17203 (save-excursion
17204 (unless (org-at-date-range-p t)
17205 (goto-char (point-at-bol))
17206 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17207 (if (not (org-at-date-range-p t))
17208 (user-error "Not at a time-stamp range, and none found in current line")))
17209 (let* ((ts1 (match-string 1))
17210 (ts2 (match-string 2))
17211 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17212 (match-end (match-end 0))
17213 (time1 (org-time-string-to-time ts1))
17214 (time2 (org-time-string-to-time ts2))
17215 (t1 (org-float-time time1))
17216 (t2 (org-float-time time2))
17217 (diff (abs (- t2 t1)))
17218 (negative (< (- t2 t1) 0))
17219 ;; (ys (floor (* 365 24 60 60)))
17220 (ds (* 24 60 60))
17221 (hs (* 60 60))
17222 (fy "%dy %dd %02d:%02d")
17223 (fy1 "%dy %dd")
17224 (fd "%dd %02d:%02d")
17225 (fd1 "%dd")
17226 (fh "%02d:%02d")
17227 y d h m align)
17228 (if havetime
17229 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17231 d (floor (/ diff ds)) diff (mod diff ds)
17232 h (floor (/ diff hs)) diff (mod diff hs)
17233 m (floor (/ diff 60)))
17234 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17236 d (floor (+ (/ diff ds) 0.5))
17237 h 0 m 0))
17238 (if (not to-buffer)
17239 (message "%s" (org-make-tdiff-string y d h m))
17240 (if (org-at-table-p)
17241 (progn
17242 (goto-char match-end)
17243 (setq align t)
17244 (and (looking-at " *|") (goto-char (match-end 0))))
17245 (goto-char match-end))
17246 (if (looking-at
17247 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17248 (replace-match ""))
17249 (if negative (insert " -"))
17250 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17251 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17252 (insert " " (format fh h m))))
17253 (if align (org-table-align))
17254 (message "Time difference inserted")))))
17256 (defun org-make-tdiff-string (y d h m)
17257 (let ((fmt "")
17258 (l nil))
17259 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
17260 l (push y l)))
17261 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
17262 l (push d l)))
17263 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
17264 l (push h l)))
17265 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
17266 l (push m l)))
17267 (apply 'format fmt (nreverse l))))
17269 (defun org-time-string-to-time (s &optional buffer pos)
17270 "Convert a timestamp string into internal time."
17271 (condition-case errdata
17272 (apply 'encode-time (org-parse-time-string s))
17273 (error (error "Bad timestamp `%s'%s\nError was: %s"
17274 s (if (not (and buffer pos))
17276 (format " at %d in buffer `%s'" pos buffer))
17277 (cdr errdata)))))
17279 (defun org-time-string-to-seconds (s)
17280 "Convert a timestamp string to a number of seconds."
17281 (org-float-time (org-time-string-to-time s)))
17283 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17284 "Convert a time stamp to an absolute day number.
17285 If there is a specifier for a cyclic time stamp, get the closest
17286 date to DAYNR.
17287 PREFER and SHOW-ALL are passed through to `org-closest-date'.
17288 The variable `date' is bound by the calendar when this is called."
17289 (cond
17290 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17291 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17292 daynr
17293 (+ daynr 1000)))
17294 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
17295 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17296 (time-to-days (current-time))) (match-string 0 s)
17297 prefer show-all))
17298 (t (time-to-days
17299 (condition-case errdata
17300 (apply 'encode-time (org-parse-time-string s))
17301 (error (error "Bad timestamp `%s'%s\nError was: %s"
17302 s (if (not (and buffer pos))
17304 (format " at %d in buffer `%s'" pos buffer))
17305 (cdr errdata))))))))
17307 (defun org-days-to-iso-week (days)
17308 "Return the iso week number."
17309 (require 'cal-iso)
17310 (car (calendar-iso-from-absolute days)))
17312 (defun org-small-year-to-year (year)
17313 "Convert 2-digit years into 4-digit years.
17314 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
17315 The year 2000 cannot be abbreviated. Any year larger than 99
17316 is returned unchanged."
17317 (if (< year 38)
17318 (setq year (+ 2000 year))
17319 (if (< year 100)
17320 (setq year (+ 1900 year))))
17321 year)
17323 (defun org-time-from-absolute (d)
17324 "Return the time corresponding to date D.
17325 D may be an absolute day number, or a calendar-type list (month day year)."
17326 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17327 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17329 (defun org-calendar-holiday ()
17330 "List of holidays, for Diary display in Org-mode."
17331 (require 'holidays)
17332 (let ((hl (funcall
17333 (if (fboundp 'calendar-check-holidays)
17334 'calendar-check-holidays 'check-calendar-holidays) date)))
17335 (if hl (mapconcat 'identity hl "; "))))
17337 (defun org-diary-sexp-entry (sexp entry date)
17338 "Process a SEXP diary ENTRY for DATE."
17339 (require 'diary-lib)
17340 (let ((result (if calendar-debug-sexp
17341 (let ((stack-trace-on-error t))
17342 (eval (car (read-from-string sexp))))
17343 (condition-case nil
17344 (eval (car (read-from-string sexp)))
17345 (error
17346 (beep)
17347 (message "Bad sexp at line %d in %s: %s"
17348 (org-current-line)
17349 (buffer-file-name) sexp)
17350 (sleep-for 2))))))
17351 (cond ((stringp result) (split-string result "; "))
17352 ((and (consp result)
17353 (not (consp (cdr result)))
17354 (stringp (cdr result))) (cdr result))
17355 ((and (consp result)
17356 (stringp (car result))) result)
17357 (result entry))))
17359 (defun org-diary-to-ical-string (frombuf)
17360 "Get iCalendar entries from diary entries in buffer FROMBUF.
17361 This uses the icalendar.el library."
17362 (let* ((tmpdir (if (featurep 'xemacs)
17363 (temp-directory)
17364 temporary-file-directory))
17365 (tmpfile (make-temp-name
17366 (expand-file-name "orgics" tmpdir)))
17367 buf rtn b e)
17368 (with-current-buffer frombuf
17369 (icalendar-export-region (point-min) (point-max) tmpfile)
17370 (setq buf (find-buffer-visiting tmpfile))
17371 (set-buffer buf)
17372 (goto-char (point-min))
17373 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17374 (setq b (match-beginning 0)))
17375 (goto-char (point-max))
17376 (if (re-search-backward "^END:VEVENT" nil t)
17377 (setq e (match-end 0)))
17378 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17379 (kill-buffer buf)
17380 (delete-file tmpfile)
17381 rtn))
17383 (defun org-closest-date (start current change prefer show-all)
17384 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17385 When PREFER is `past', return a date that is either CURRENT or past.
17386 When PREFER is `future', return a date that is either CURRENT or future.
17387 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17388 ;; Make the proper lists from the dates
17389 (catch 'exit
17390 (let ((a1 '(("h" . hour)
17391 ("d" . day)
17392 ("w" . week)
17393 ("m" . month)
17394 ("y" . year)))
17395 (shour (nth 2 (org-parse-time-string start)))
17396 dn dw sday cday n1 n2 n0
17397 d m y y1 y2 date1 date2 nmonths nm ny m2)
17399 (setq start (org-date-to-gregorian start)
17400 current (org-date-to-gregorian
17401 (if show-all
17402 current
17403 (time-to-days (current-time))))
17404 sday (calendar-absolute-from-gregorian start)
17405 cday (calendar-absolute-from-gregorian current))
17407 (if (<= cday sday) (throw 'exit sday))
17409 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17410 (setq dn (string-to-number (match-string 1 change))
17411 dw (cdr (assoc (match-string 2 change) a1)))
17412 (user-error "Invalid change specifier: %s" change))
17413 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17414 (cond
17415 ((eq dw 'hour)
17416 (let ((missing-hours
17417 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17418 dn)))
17419 (setq n1 (if (zerop missing-hours) cday
17420 (- cday (1+ (floor (/ missing-hours 24)))))
17421 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17422 ((eq dw 'day)
17423 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17424 n2 (+ n1 dn)))
17425 ((eq dw 'year)
17426 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17427 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17428 (setq date1 (list m d y1)
17429 n1 (calendar-absolute-from-gregorian date1)
17430 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17431 n2 (calendar-absolute-from-gregorian date2)))
17432 ((eq dw 'month)
17433 ;; approx number of month between the two dates
17434 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17435 ;; How often does dn fit in there?
17436 (setq d (nth 1 start) m (car start) y (nth 2 start)
17437 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17438 m (+ m nm)
17439 ny (floor (/ m 12))
17440 y (+ y ny)
17441 m (- m (* ny 12)))
17442 (while (> m 12) (setq m (- m 12) y (1+ y)))
17443 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17444 (setq m2 (+ m dn) y2 y)
17445 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17446 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17447 (while (<= n2 cday)
17448 (setq n1 n2 m m2 y y2)
17449 (setq m2 (+ m dn) y2 y)
17450 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17451 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17452 ;; Make sure n1 is the earlier date
17453 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17454 (if show-all
17455 (cond
17456 ((eq prefer 'past) (if (= cday n2) n2 n1))
17457 ((eq prefer 'future) (if (= cday n1) n1 n2))
17458 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17459 (cond
17460 ((eq prefer 'past) (if (= cday n2) n2 n1))
17461 ((eq prefer 'future) (if (= cday n1) n1 n2))
17462 (t (if (= cday n1) n1 n2)))))))
17464 (defun org-date-to-gregorian (date)
17465 "Turn any specification of DATE into a Gregorian date for the calendar."
17466 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17467 ((and (listp date) (= (length date) 3)) date)
17468 ((stringp date)
17469 (setq date (org-parse-time-string date))
17470 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17471 ((listp date)
17472 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17474 (defun org-parse-time-string (s &optional nodefault)
17475 "Parse the standard Org-mode time string.
17476 This should be a lot faster than the normal `parse-time-string'.
17477 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17478 hour and minute fields will be nil if not given."
17479 (cond ((string-match org-ts-regexp0 s)
17480 (list 0
17481 (if (or (match-beginning 8) (not nodefault))
17482 (string-to-number (or (match-string 8 s) "0")))
17483 (if (or (match-beginning 7) (not nodefault))
17484 (string-to-number (or (match-string 7 s) "0")))
17485 (string-to-number (match-string 4 s))
17486 (string-to-number (match-string 3 s))
17487 (string-to-number (match-string 2 s))
17488 nil nil nil))
17489 ((string-match "^<[^>]+>$" s)
17490 (decode-time (seconds-to-time (org-matcher-time s))))
17491 (t (error "Not a standard Org-mode time string: %s" s))))
17493 (defun org-timestamp-up (&optional arg)
17494 "Increase the date item at the cursor by one.
17495 If the cursor is on the year, change the year. If it is on the month,
17496 the day or the time, change that.
17497 With prefix ARG, change by that many units."
17498 (interactive "p")
17499 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17501 (defun org-timestamp-down (&optional arg)
17502 "Decrease the date item at the cursor by one.
17503 If the cursor is on the year, change the year. If it is on the month,
17504 the day or the time, change that.
17505 With prefix ARG, change by that many units."
17506 (interactive "p")
17507 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17509 (defun org-timestamp-up-day (&optional arg)
17510 "Increase the date in the time stamp by one day.
17511 With prefix ARG, change that many days."
17512 (interactive "p")
17513 (if (and (not (org-at-timestamp-p t))
17514 (org-at-heading-p))
17515 (org-todo 'up)
17516 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17518 (defun org-timestamp-down-day (&optional arg)
17519 "Decrease the date in the time stamp by one day.
17520 With prefix ARG, change that many days."
17521 (interactive "p")
17522 (if (and (not (org-at-timestamp-p t))
17523 (org-at-heading-p))
17524 (org-todo 'down)
17525 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17527 (defun org-at-timestamp-p (&optional inactive-ok)
17528 "Determine if the cursor is in or at a timestamp."
17529 (interactive)
17530 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17531 (pos (point))
17532 (ans (or (looking-at tsr)
17533 (save-excursion
17534 (skip-chars-backward "^[<\n\r\t")
17535 (if (> (point) (point-min)) (backward-char 1))
17536 (and (looking-at tsr)
17537 (> (- (match-end 0) pos) -1))))))
17538 (and ans
17539 (boundp 'org-ts-what)
17540 (setq org-ts-what
17541 (cond
17542 ((= pos (match-beginning 0)) 'bracket)
17543 ;; Point is considered to be "on the bracket" whether
17544 ;; it's really on it or right after it.
17545 ((= pos (1- (match-end 0))) 'bracket)
17546 ((= pos (match-end 0)) 'after)
17547 ((org-pos-in-match-range pos 2) 'year)
17548 ((org-pos-in-match-range pos 3) 'month)
17549 ((org-pos-in-match-range pos 7) 'hour)
17550 ((org-pos-in-match-range pos 8) 'minute)
17551 ((or (org-pos-in-match-range pos 4)
17552 (org-pos-in-match-range pos 5)) 'day)
17553 ((and (> pos (or (match-end 8) (match-end 5)))
17554 (< pos (match-end 0)))
17555 (- pos (or (match-end 8) (match-end 5))))
17556 (t 'day))))
17557 ans))
17559 (defun org-toggle-timestamp-type ()
17560 "Toggle the type (<active> or [inactive]) of a time stamp."
17561 (interactive)
17562 (when (org-at-timestamp-p t)
17563 (let ((beg (match-beginning 0)) (end (match-end 0))
17564 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17565 (save-excursion
17566 (goto-char beg)
17567 (while (re-search-forward "[][<>]" end t)
17568 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17569 t t)))
17570 (message "Timestamp is now %sactive"
17571 (if (equal (char-after beg) ?<) "" "in")))))
17573 (defun org-at-clock-log-p nil
17574 "Is the cursor on the clock log line?"
17575 (save-excursion
17576 (move-beginning-of-line 1)
17577 (looking-at "^[ \t]*CLOCK:")))
17579 (defvar org-clock-history) ; defined in org-clock.el
17580 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17581 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17582 "Change the date in the time stamp at point.
17583 The date will be changed by N times WHAT. WHAT can be `day', `month',
17584 `year', `minute', `second'. If WHAT is not given, the cursor position
17585 in the timestamp determines what will be changed.
17586 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17587 (let ((origin (point)) origin-cat
17588 with-hm inactive
17589 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17590 org-ts-what
17591 extra rem
17592 ts time time0 fixnext clrgx)
17593 (if (not (org-at-timestamp-p t))
17594 (user-error "Not at a timestamp"))
17595 (if (and (not what) (eq org-ts-what 'bracket))
17596 (org-toggle-timestamp-type)
17597 ;; Point isn't on brackets. Remember the part of the time-stamp
17598 ;; the point was in. Indeed, size of time-stamps may change,
17599 ;; but point must be kept in the same category nonetheless.
17600 (setq origin-cat org-ts-what)
17601 (if (and (not what) (not (eq org-ts-what 'day))
17602 org-display-custom-times
17603 (get-text-property (point) 'display)
17604 (not (get-text-property (1- (point)) 'display)))
17605 (setq org-ts-what 'day))
17606 (setq org-ts-what (or what org-ts-what)
17607 inactive (= (char-after (match-beginning 0)) ?\[)
17608 ts (match-string 0))
17609 (replace-match "")
17610 (when (string-match
17611 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17613 (setq extra (match-string 1 ts))
17614 (if suppress-tmp-delay
17615 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17616 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17617 (setq with-hm t))
17618 (setq time0 (org-parse-time-string ts))
17619 (when (and updown
17620 (eq org-ts-what 'minute)
17621 (not current-prefix-arg))
17622 ;; This looks like s-up and s-down. Change by one rounding step.
17623 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17624 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17625 (setcar (cdr time0) (+ (nth 1 time0)
17626 (if (> n 0) (- rem) (- dm rem))))))
17627 (setq time
17628 (encode-time (or (car time0) 0)
17629 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17630 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17631 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17632 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17633 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17634 (nthcdr 6 time0)))
17635 (when (and (member org-ts-what '(hour minute))
17636 extra
17637 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17638 (setq extra (org-modify-ts-extra
17639 extra
17640 (if (eq org-ts-what 'hour) 2 5)
17641 n dm)))
17642 (when (integerp org-ts-what)
17643 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17644 (if (eq what 'calendar)
17645 (let ((cal-date (org-get-date-from-calendar)))
17646 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17647 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17648 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17649 (setcar time0 (or (car time0) 0))
17650 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17651 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17652 (setq time (apply 'encode-time time0))))
17653 ;; Insert the new time-stamp, and ensure point stays in the same
17654 ;; category as before (i.e. not after the last position in that
17655 ;; category).
17656 (let ((pos (point)))
17657 ;; Stay before inserted string. `save-excursion' is of no use.
17658 (setq org-last-changed-timestamp
17659 (org-insert-time-stamp time with-hm inactive nil nil extra))
17660 (goto-char pos))
17661 (save-match-data
17662 (looking-at org-ts-regexp3)
17663 (goto-char (cond
17664 ;; `day' category ends before `hour' if any, or at
17665 ;; the end of the day name.
17666 ((eq origin-cat 'day)
17667 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17668 ((eq origin-cat 'hour) (min (match-end 7) origin))
17669 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17670 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17671 ;; `year' and `month' have both fixed size: point
17672 ;; couldn't have moved into another part.
17673 (t origin))))
17674 ;; Update clock if on a CLOCK line.
17675 (org-clock-update-time-maybe)
17676 ;; Maybe adjust the closest clock in `org-clock-history'
17677 (when org-clock-adjust-closest
17678 (if (not (and (org-at-clock-log-p)
17679 (< 1 (length (delq nil (mapcar 'marker-position
17680 org-clock-history))))))
17681 (message "No clock to adjust")
17682 (cond ((save-excursion ; fix previous clock?
17683 (re-search-backward org-ts-regexp0 nil t)
17684 (org-looking-back (concat org-clock-string " \\[")))
17685 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17686 ((save-excursion ; fix next clock?
17687 (re-search-backward org-ts-regexp0 nil t)
17688 (looking-at (concat org-ts-regexp0 "\\] =>")))
17689 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17690 (save-window-excursion
17691 ;; Find closest clock to point, adjust the previous/next one in history
17692 (let* ((p (save-excursion (org-back-to-heading t)))
17693 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17694 (clfixnth
17695 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
17696 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17697 (if (not clfixpos)
17698 (message "No clock to adjust")
17699 (save-excursion
17700 (org-goto-marker-or-bmk clfixpos)
17701 (org-show-subtree)
17702 (when (re-search-forward clrgx nil t)
17703 (goto-char (match-beginning 1))
17704 (let (org-clock-adjust-closest)
17705 (org-timestamp-change n org-ts-what updown))
17706 (message "Clock adjusted in %s for heading: %s"
17707 (file-name-nondirectory (buffer-file-name))
17708 (org-get-heading t t)))))))))
17709 ;; Try to recenter the calendar window, if any.
17710 (if (and org-calendar-follow-timestamp-change
17711 (get-buffer-window "*Calendar*" t)
17712 (memq org-ts-what '(day month year)))
17713 (org-recenter-calendar (time-to-days time))))))
17715 (defun org-modify-ts-extra (s pos n dm)
17716 "Change the different parts of the lead-time and repeat fields in timestamp."
17717 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17718 ng h m new rem)
17719 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17720 (cond
17721 ((or (org-pos-in-match-range pos 2)
17722 (org-pos-in-match-range pos 3))
17723 (setq m (string-to-number (match-string 3 s))
17724 h (string-to-number (match-string 2 s)))
17725 (if (org-pos-in-match-range pos 2)
17726 (setq h (+ h n))
17727 (setq n (* dm (org-no-warnings (signum n))))
17728 (when (not (= 0 (setq rem (% m dm))))
17729 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17730 (setq m (+ m n)))
17731 (if (< m 0) (setq m (+ m 60) h (1- h)))
17732 (if (> m 59) (setq m (- m 60) h (1+ h)))
17733 (setq h (min 24 (max 0 h)))
17734 (setq ng 1 new (format "-%02d:%02d" h m)))
17735 ((org-pos-in-match-range pos 6)
17736 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17737 ((org-pos-in-match-range pos 5)
17738 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17740 ((org-pos-in-match-range pos 9)
17741 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17742 ((org-pos-in-match-range pos 8)
17743 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17745 (when ng
17746 (setq s (concat
17747 (substring s 0 (match-beginning ng))
17749 (substring s (match-end ng))))))
17752 (defun org-recenter-calendar (date)
17753 "If the calendar is visible, recenter it to DATE."
17754 (let ((cwin (get-buffer-window "*Calendar*" t)))
17755 (when cwin
17756 (let ((calendar-move-hook nil))
17757 (with-selected-window cwin
17758 (calendar-goto-date (if (listp date) date
17759 (calendar-gregorian-from-absolute date))))))))
17761 (defun org-goto-calendar (&optional arg)
17762 "Go to the Emacs calendar at the current date.
17763 If there is a time stamp in the current line, go to that date.
17764 A prefix ARG can be used to force the current date."
17765 (interactive "P")
17766 (let ((tsr org-ts-regexp) diff
17767 (calendar-move-hook nil)
17768 (calendar-view-holidays-initially-flag nil)
17769 (calendar-view-diary-initially-flag nil))
17770 (if (or (org-at-timestamp-p)
17771 (save-excursion
17772 (beginning-of-line 1)
17773 (looking-at (concat ".*" tsr))))
17774 (let ((d1 (time-to-days (current-time)))
17775 (d2 (time-to-days
17776 (org-time-string-to-time (match-string 1)))))
17777 (setq diff (- d2 d1))))
17778 (calendar)
17779 (calendar-goto-today)
17780 (if (and diff (not arg)) (calendar-forward-day diff))))
17782 (defun org-get-date-from-calendar ()
17783 "Return a list (month day year) of date at point in calendar."
17784 (with-current-buffer "*Calendar*"
17785 (save-match-data
17786 (calendar-cursor-to-date))))
17788 (defun org-date-from-calendar ()
17789 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17790 If there is already a time stamp at the cursor position, update it."
17791 (interactive)
17792 (if (org-at-timestamp-p t)
17793 (org-timestamp-change 0 'calendar)
17794 (let ((cal-date (org-get-date-from-calendar)))
17795 (org-insert-time-stamp
17796 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17798 (defcustom org-effort-durations
17799 `(("h" . 60)
17800 ("d" . ,(* 60 8))
17801 ("w" . ,(* 60 8 5))
17802 ("m" . ,(* 60 8 5 4))
17803 ("y" . ,(* 60 8 5 40)))
17804 "Conversion factor to minutes for an effort modifier.
17806 Each entry has the form (MODIFIER . MINUTES).
17808 In an effort string, a number followed by MODIFIER is multiplied
17809 by the specified number of MINUTES to obtain an effort in
17810 minutes.
17812 For example, if the value of this variable is ((\"hours\" . 60)), then an
17813 effort string \"2hours\" is equivalent to 120 minutes."
17814 :group 'org-agenda
17815 :version "24.1"
17816 :type '(alist :key-type (string :tag "Modifier")
17817 :value-type (number :tag "Minutes")))
17819 (defun org-minutes-to-clocksum-string (m)
17820 "Format number of minutes as a clocksum string.
17821 The format is determined by `org-time-clocksum-format',
17822 `org-time-clocksum-use-fractional' and
17823 `org-time-clocksum-fractional-format' and
17824 `org-time-clocksum-use-effort-durations'."
17825 (let ((clocksum "")
17826 (m (round m)) ; Don't allow fractions of minutes
17827 h d w mo y fmt n)
17828 (setq h (if org-time-clocksum-use-effort-durations
17829 (cdr (assoc "h" org-effort-durations)) 60)
17830 d (if org-time-clocksum-use-effort-durations
17831 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17832 w (if org-time-clocksum-use-effort-durations
17833 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17834 mo (if org-time-clocksum-use-effort-durations
17835 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17836 y (if org-time-clocksum-use-effort-durations
17837 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17838 ;; fractional format
17839 (if org-time-clocksum-use-fractional
17840 (cond
17841 ;; single format string
17842 ((stringp org-time-clocksum-fractional-format)
17843 (format org-time-clocksum-fractional-format (/ m (float h))))
17844 ;; choice of fractional formats for different time units
17845 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17846 (> (/ (truncate m) (* y d h)) 0))
17847 (format fmt (/ m (* y d (float h)))))
17848 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17849 (> (/ (truncate m) (* mo d h)) 0))
17850 (format fmt (/ m (* mo d (float h)))))
17851 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17852 (> (/ (truncate m) (* w d h)) 0))
17853 (format fmt (/ m (* w d (float h)))))
17854 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17855 (> (/ (truncate m) (* d h)) 0))
17856 (format fmt (/ m (* d (float h)))))
17857 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17858 (> (/ (truncate m) h) 0))
17859 (format fmt (/ m (float h))))
17860 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17861 (format fmt m))
17862 ;; fall back to smallest time unit with a format
17863 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17864 (format fmt (/ m (float h))))
17865 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17866 (format fmt (/ m (* d (float h)))))
17867 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17868 (format fmt (/ m (* w d (float h)))))
17869 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17870 (format fmt (/ m (* mo d (float h)))))
17871 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17872 (format fmt (/ m (* y d (float h))))))
17873 ;; standard (non-fractional) format, with single format string
17874 (if (stringp org-time-clocksum-format)
17875 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17876 ;; separate formats components
17877 (and (setq fmt (plist-get org-time-clocksum-format :years))
17878 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17879 (plist-get org-time-clocksum-format :require-years))
17880 (setq clocksum (concat clocksum (format fmt n))
17881 m (- m (* n y d h))))
17882 (and (setq fmt (plist-get org-time-clocksum-format :months))
17883 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17884 (plist-get org-time-clocksum-format :require-months))
17885 (setq clocksum (concat clocksum (format fmt n))
17886 m (- m (* n mo d h))))
17887 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17888 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17889 (plist-get org-time-clocksum-format :require-weeks))
17890 (setq clocksum (concat clocksum (format fmt n))
17891 m (- m (* n w d h))))
17892 (and (setq fmt (plist-get org-time-clocksum-format :days))
17893 (or (> (setq n (/ (truncate m) (* d h))) 0)
17894 (plist-get org-time-clocksum-format :require-days))
17895 (setq clocksum (concat clocksum (format fmt n))
17896 m (- m (* n d h))))
17897 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17898 (or (> (setq n (/ (truncate m) h)) 0)
17899 (plist-get org-time-clocksum-format :require-hours))
17900 (setq clocksum (concat clocksum (format fmt n))
17901 m (- m (* n h))))
17902 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17903 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17904 (setq clocksum (concat clocksum (format fmt m))))
17905 ;; return formatted time duration
17906 clocksum))))
17908 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17909 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17910 "Org mode version 8.0")
17912 (defun org-hours-to-clocksum-string (n)
17913 (org-minutes-to-clocksum-string (* n 60)))
17915 (defun org-hh:mm-string-to-minutes (s)
17916 "Convert a string H:MM to a number of minutes.
17917 If the string is just a number, interpret it as minutes.
17918 In fact, the first hh:mm or number in the string will be taken,
17919 there can be extra stuff in the string.
17920 If no number is found, the return value is 0."
17921 (cond
17922 ((integerp s) s)
17923 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17924 (+ (* (string-to-number (match-string 1 s)) 60)
17925 (string-to-number (match-string 2 s))))
17926 ((string-match "\\([0-9]+\\)" s)
17927 (string-to-number (match-string 1 s)))
17928 (t 0)))
17930 (defcustom org-image-actual-width t
17931 "Should we use the actual width of images when inlining them?
17933 When set to `t', always use the image width.
17935 When set to a number, use imagemagick (when available) to set
17936 the image's width to this value.
17938 When set to a number in a list, try to get the width from any
17939 #+ATTR.* keyword if it matches a width specification like
17941 #+ATTR_HTML: :width 300px
17943 and fall back on that number if none is found.
17945 When set to nil, try to get the width from an #+ATTR.* keyword
17946 and fall back on the original width if none is found.
17948 This requires Emacs >= 24.1, build with imagemagick support."
17949 :group 'org-appearance
17950 :version "24.4"
17951 :package-version '(Org . "8.0")
17952 :type '(choice
17953 (const :tag "Use the image width" t)
17954 (integer :tag "Use a number of pixels")
17955 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17956 (const :tag "Use #+ATTR* or don't resize" nil)))
17958 (defcustom org-agenda-inhibit-startup nil
17959 "Inhibit startup when preparing agenda buffers.
17960 When this variable is `t' (the default), the initialization of
17961 the Org agenda buffers is inhibited: e.g. the visibility state
17962 is not set, the tables are not re-aligned, etc."
17963 :type 'boolean
17964 :version "24.3"
17965 :group 'org-agenda)
17967 (define-obsolete-variable-alias
17968 'org-agenda-ignore-drawer-properties
17969 'org-agenda-ignore-properties "24.5")
17971 (defcustom org-agenda-ignore-properties nil
17972 "Avoid updating text properties when building the agenda.
17973 Properties are used to prepare buffers for effort estimates,
17974 appointments, statistics and subtree-local categories.
17975 If you don't use these in the agenda, you can add them to this
17976 list and agenda building will be a bit faster.
17977 The value is a list, with zero or more of the symbols `effort', `appt',
17978 `stats' or `category'."
17979 :type '(set :greedy t
17980 (const effort)
17981 (const appt)
17982 (const stats)
17983 (const category))
17984 :version "24.5"
17985 :package-version '(Org . "8.3")
17986 :group 'org-agenda)
17988 (defun org-duration-string-to-minutes (s &optional output-to-string)
17989 "Convert a duration string S to minutes.
17991 A bare number is interpreted as minutes, modifiers can be set by
17992 customizing `org-effort-durations' (which see).
17994 Entries containing a colon are interpreted as H:MM by
17995 `org-hh:mm-string-to-minutes'."
17996 (let ((result 0)
17997 (re (concat "\\([0-9.]+\\) *\\("
17998 (regexp-opt (mapcar 'car org-effort-durations))
17999 "\\)")))
18000 (while (string-match re s)
18001 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
18002 (string-to-number (match-string 1 s))))
18003 (setq s (replace-match "" nil t s)))
18004 (setq result (floor result))
18005 (incf result (org-hh:mm-string-to-minutes s))
18006 (if output-to-string (number-to-string result) result)))
18008 ;;;; Files
18010 (defun org-save-all-org-buffers ()
18011 "Save all Org-mode buffers without user confirmation."
18012 (interactive)
18013 (message "Saving all Org-mode buffers...")
18014 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18015 (when (featurep 'org-id) (org-id-locations-save))
18016 (message "Saving all Org-mode buffers... done"))
18018 (defun org-revert-all-org-buffers ()
18019 "Revert all Org-mode buffers.
18020 Prompt for confirmation when there are unsaved changes.
18021 Be sure you know what you are doing before letting this function
18022 overwrite your changes.
18024 This function is useful in a setup where one tracks org files
18025 with a version control system, to revert on one machine after pulling
18026 changes from another. I believe the procedure must be like this:
18028 1. M-x org-save-all-org-buffers
18029 2. Pull changes from the other machine, resolve conflicts
18030 3. M-x org-revert-all-org-buffers"
18031 (interactive)
18032 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18033 (user-error "Abort"))
18034 (save-excursion
18035 (save-window-excursion
18036 (mapc
18037 (lambda (b)
18038 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18039 (with-current-buffer b buffer-file-name))
18040 (org-pop-to-buffer-same-window b)
18041 (revert-buffer t 'no-confirm)))
18042 (buffer-list))
18043 (when (and (featurep 'org-id) org-id-track-globally)
18044 (org-id-locations-load)))))
18046 ;;;; Agenda files
18048 ;;;###autoload
18049 (defun org-switchb (&optional arg)
18050 "Switch between Org buffers.
18051 With one prefix argument, restrict available buffers to files.
18052 With two prefix arguments, restrict available buffers to agenda files.
18054 Defaults to `iswitchb' for buffer name completion.
18055 Set `org-completion-use-ido' to make it use ido instead."
18056 (interactive "P")
18057 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
18058 ((equal arg '(16)) (org-buffer-list 'agenda))
18059 (t (org-buffer-list))))
18060 (org-completion-use-iswitchb org-completion-use-iswitchb)
18061 (org-completion-use-ido org-completion-use-ido))
18062 (unless (or org-completion-use-ido org-completion-use-iswitchb)
18063 (setq org-completion-use-iswitchb t))
18064 (org-pop-to-buffer-same-window
18065 (org-icompleting-read "Org buffer: "
18066 (mapcar 'list (mapcar 'buffer-name blist))
18067 nil t))))
18069 ;;; Define some older names previously used for this functionality
18070 ;;;###autoload
18071 (defalias 'org-ido-switchb 'org-switchb)
18072 ;;;###autoload
18073 (defalias 'org-iswitchb 'org-switchb)
18075 (defun org-buffer-list (&optional predicate exclude-tmp)
18076 "Return a list of Org buffers.
18077 PREDICATE can be `export', `files' or `agenda'.
18079 export restrict the list to Export buffers.
18080 files restrict the list to buffers visiting Org files.
18081 agenda restrict the list to buffers visiting agenda files.
18083 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18084 (let* ((bfn nil)
18085 (agenda-files (and (eq predicate 'agenda)
18086 (mapcar 'file-truename (org-agenda-files t))))
18087 (filter
18088 (cond
18089 ((eq predicate 'files)
18090 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18091 ((eq predicate 'export)
18092 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
18093 ((eq predicate 'agenda)
18094 (lambda (b)
18095 (with-current-buffer b
18096 (and (derived-mode-p 'org-mode)
18097 (setq bfn (buffer-file-name b))
18098 (member (file-truename bfn) agenda-files)))))
18099 (t (lambda (b) (with-current-buffer b
18100 (or (derived-mode-p 'org-mode)
18101 (string-match "\*Org .*Export"
18102 (buffer-name b)))))))))
18103 (delq nil
18104 (mapcar
18105 (lambda(b)
18106 (if (and (funcall filter b)
18107 (or (not exclude-tmp)
18108 (not (string-match "tmp" (buffer-name b)))))
18110 nil))
18111 (buffer-list)))))
18113 (defun org-agenda-files (&optional unrestricted archives)
18114 "Get the list of agenda files.
18115 Optional UNRESTRICTED means return the full list even if a restriction
18116 is currently in place.
18117 When ARCHIVES is t, include all archive files that are really being
18118 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18119 `org-agenda-archives-mode' is t."
18120 (let ((files
18121 (cond
18122 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18123 ((stringp org-agenda-files) (org-read-agenda-file-list))
18124 ((listp org-agenda-files) org-agenda-files)
18125 (t (error "Invalid value of `org-agenda-files'")))))
18126 (setq files (apply 'append
18127 (mapcar (lambda (f)
18128 (if (file-directory-p f)
18129 (directory-files
18130 f t org-agenda-file-regexp)
18131 (list f)))
18132 files)))
18133 (when org-agenda-skip-unavailable-files
18134 (setq files (delq nil
18135 (mapcar (function
18136 (lambda (file)
18137 (and (file-readable-p file) file)))
18138 files))))
18139 (when (or (eq archives t)
18140 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18141 (setq files (org-add-archive-files files)))
18142 files))
18144 (defun org-agenda-file-p (&optional file)
18145 "Return non-nil, if FILE is an agenda file.
18146 If FILE is omitted, use the file associated with the current
18147 buffer."
18148 (member (or file (buffer-file-name))
18149 (org-agenda-files t)))
18151 (defun org-edit-agenda-file-list ()
18152 "Edit the list of agenda files.
18153 Depending on setup, this either uses customize to edit the variable
18154 `org-agenda-files', or it visits the file that is holding the list. In the
18155 latter case, the buffer is set up in a way that saving it automatically kills
18156 the buffer and restores the previous window configuration."
18157 (interactive)
18158 (if (stringp org-agenda-files)
18159 (let ((cw (current-window-configuration)))
18160 (find-file org-agenda-files)
18161 (org-set-local 'org-window-configuration cw)
18162 (org-add-hook 'after-save-hook
18163 (lambda ()
18164 (set-window-configuration
18165 (prog1 org-window-configuration
18166 (kill-buffer (current-buffer))))
18167 (org-install-agenda-files-menu)
18168 (message "New agenda file list installed"))
18169 nil 'local)
18170 (message "%s" (substitute-command-keys
18171 "Edit list and finish with \\[save-buffer]")))
18172 (customize-variable 'org-agenda-files)))
18174 (defun org-store-new-agenda-file-list (list)
18175 "Set new value for the agenda file list and save it correctly."
18176 (if (stringp org-agenda-files)
18177 (let ((fe (org-read-agenda-file-list t)) b u)
18178 (while (setq b (find-buffer-visiting org-agenda-files))
18179 (kill-buffer b))
18180 (with-temp-file org-agenda-files
18181 (insert
18182 (mapconcat
18183 (lambda (f) ;; Keep un-expanded entries.
18184 (if (setq u (assoc f fe))
18185 (cdr u)
18187 list "\n")
18188 "\n")))
18189 (let ((org-mode-hook nil) (org-inhibit-startup t)
18190 (org-insert-mode-line-in-empty-file nil))
18191 (setq org-agenda-files list)
18192 (customize-save-variable 'org-agenda-files org-agenda-files))))
18194 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18195 "Read the list of agenda files from a file.
18196 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18197 filenames, used by `org-store-new-agenda-file-list' to write back
18198 un-expanded file names."
18199 (when (file-directory-p org-agenda-files)
18200 (error "`org-agenda-files' cannot be a single directory"))
18201 (when (stringp org-agenda-files)
18202 (with-temp-buffer
18203 (insert-file-contents org-agenda-files)
18204 (mapcar
18205 (lambda (f)
18206 (let ((e (expand-file-name (substitute-in-file-name f)
18207 org-directory)))
18208 (if pair-with-expansion
18209 (cons e f)
18210 e)))
18211 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18213 ;;;###autoload
18214 (defun org-cycle-agenda-files ()
18215 "Cycle through the files in `org-agenda-files'.
18216 If the current buffer visits an agenda file, find the next one in the list.
18217 If the current buffer does not, find the first agenda file."
18218 (interactive)
18219 (let* ((fs (org-agenda-files t))
18220 (files (append fs (list (car fs))))
18221 (tcf (if buffer-file-name (file-truename buffer-file-name)))
18222 file)
18223 (unless files (user-error "No agenda files"))
18224 (catch 'exit
18225 (while (setq file (pop files))
18226 (if (equal (file-truename file) tcf)
18227 (when (car files)
18228 (find-file (car files))
18229 (throw 'exit t))))
18230 (find-file (car fs)))
18231 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
18233 (defun org-agenda-file-to-front (&optional to-end)
18234 "Move/add the current file to the top of the agenda file list.
18235 If the file is not present in the list, it is added to the front. If it is
18236 present, it is moved there. With optional argument TO-END, add/move to the
18237 end of the list."
18238 (interactive "P")
18239 (let ((org-agenda-skip-unavailable-files nil)
18240 (file-alist (mapcar (lambda (x)
18241 (cons (file-truename x) x))
18242 (org-agenda-files t)))
18243 (ctf (file-truename
18244 (or buffer-file-name
18245 (user-error "Please save the current buffer to a file"))))
18246 x had)
18247 (setq x (assoc ctf file-alist) had x)
18249 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18250 (if to-end
18251 (setq file-alist (append (delq x file-alist) (list x)))
18252 (setq file-alist (cons x (delq x file-alist))))
18253 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18254 (org-install-agenda-files-menu)
18255 (message "File %s to %s of agenda file list"
18256 (if had "moved" "added") (if to-end "end" "front"))))
18258 (defun org-remove-file (&optional file)
18259 "Remove current file from the list of files in variable `org-agenda-files'.
18260 These are the files which are being checked for agenda entries.
18261 Optional argument FILE means use this file instead of the current."
18262 (interactive)
18263 (let* ((org-agenda-skip-unavailable-files nil)
18264 (file (or file buffer-file-name
18265 (user-error "Current buffer does not visit a file")))
18266 (true-file (file-truename file))
18267 (afile (abbreviate-file-name file))
18268 (files (delq nil (mapcar
18269 (lambda (x)
18270 (if (equal true-file
18271 (file-truename x))
18272 nil x))
18273 (org-agenda-files t)))))
18274 (if (not (= (length files) (length (org-agenda-files t))))
18275 (progn
18276 (org-store-new-agenda-file-list files)
18277 (org-install-agenda-files-menu)
18278 (message "Removed file: %s" afile))
18279 (message "File was not in list: %s (not removed)" afile))))
18281 (defun org-file-menu-entry (file)
18282 (vector file (list 'find-file file) t))
18284 (defun org-check-agenda-file (file)
18285 "Make sure FILE exists. If not, ask user what to do."
18286 (when (not (file-exists-p file))
18287 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18288 (abbreviate-file-name file))
18289 (let ((r (downcase (read-char-exclusive))))
18290 (cond
18291 ((equal r ?r)
18292 (org-remove-file file)
18293 (throw 'nextfile t))
18294 (t (user-error "Abort"))))))
18296 (defun org-get-agenda-file-buffer (file)
18297 "Get an agenda buffer visiting FILE.
18298 If the buffer needs to be created, add it to the list of buffers
18299 which might be released later."
18300 (let ((buf (org-find-base-buffer-visiting file)))
18301 (if buf
18302 buf ; just return it
18303 ;; Make a new buffer and remember it
18304 (setq buf (find-file-noselect file))
18305 (if buf (push buf org-agenda-new-buffers))
18306 buf)))
18308 (defun org-release-buffers (blist)
18309 "Release all buffers in list, asking the user for confirmation when needed.
18310 When a buffer is unmodified, it is just killed. When modified, it is saved
18311 \(if the user agrees) and then killed."
18312 (let (buf file)
18313 (while (setq buf (pop blist))
18314 (setq file (buffer-file-name buf))
18315 (when (and (buffer-modified-p buf)
18316 file
18317 (y-or-n-p (format "Save file %s? " file)))
18318 (with-current-buffer buf (save-buffer)))
18319 (kill-buffer buf))))
18321 (defun org-agenda-prepare-buffers (files)
18322 "Create buffers for all agenda files, protect archived trees and comments."
18323 (interactive)
18324 (let ((pa '(:org-archived t))
18325 (pc '(:org-comment t))
18326 (pall '(:org-archived t :org-comment t))
18327 (inhibit-read-only t)
18328 (org-inhibit-startup org-agenda-inhibit-startup)
18329 (rea (concat ":" org-archive-tag ":"))
18330 file re pos)
18331 (setq org-tag-alist-for-agenda nil
18332 org-tag-groups-alist-for-agenda nil)
18333 (save-excursion
18334 (save-restriction
18335 (while (setq file (pop files))
18336 (catch 'nextfile
18337 (if (bufferp file)
18338 (set-buffer file)
18339 (org-check-agenda-file file)
18340 (set-buffer (org-get-agenda-file-buffer file)))
18341 (widen)
18342 (org-set-regexps-and-options-for-tags)
18343 (setq pos (point))
18344 (goto-char (point-min))
18345 (let ((case-fold-search t))
18346 (when (search-forward "#+setupfile" nil t)
18347 ;; Don't set all regexps and options systematically as
18348 ;; this is only run for setting agenda tags from setup
18349 ;; file
18350 (org-set-regexps-and-options)))
18351 (or (memq 'category org-agenda-ignore-properties)
18352 (org-refresh-category-properties))
18353 (or (memq 'stats org-agenda-ignore-properties)
18354 (org-refresh-stats-properties))
18355 (or (memq 'effort org-agenda-ignore-properties)
18356 (org-refresh-effort-properties))
18357 (or (memq 'appt org-agenda-ignore-properties)
18358 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18359 (setq org-todo-keywords-for-agenda
18360 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18361 (setq org-done-keywords-for-agenda
18362 (append org-done-keywords-for-agenda org-done-keywords))
18363 (setq org-todo-keyword-alist-for-agenda
18364 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18365 (setq org-tag-alist-for-agenda
18366 (org-uniquify
18367 (append org-tag-alist-for-agenda
18368 org-tag-alist
18369 org-tag-persistent-alist)))
18370 (if org-group-tags
18371 (setq org-tag-groups-alist-for-agenda
18372 (org-uniquify-alist
18373 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18374 (org-with-silent-modifications
18375 (save-excursion
18376 (remove-text-properties (point-min) (point-max) pall)
18377 (when org-agenda-skip-archived-trees
18378 (goto-char (point-min))
18379 (while (re-search-forward rea nil t)
18380 (if (org-at-heading-p t)
18381 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18382 (goto-char (point-min))
18383 (setq re (format "^\\* .*\\<%s\\>" org-comment-string))
18384 (while (re-search-forward re nil t)
18385 (when (save-match-data (org-in-commented-heading-p t))
18386 (add-text-properties
18387 (match-beginning 0) (org-end-of-subtree t) pc)))))
18388 (goto-char pos)))))
18389 (setq org-todo-keywords-for-agenda
18390 (org-uniquify org-todo-keywords-for-agenda))
18391 (setq org-todo-keyword-alist-for-agenda
18392 (org-uniquify org-todo-keyword-alist-for-agenda))))
18395 ;;;; CDLaTeX minor mode
18397 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18398 "Keymap for the minor `org-cdlatex-mode'.")
18400 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18401 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18402 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18403 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18404 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
18406 (defvar org-cdlatex-texmathp-advice-is-done nil
18407 "Flag remembering if we have applied the advice to texmathp already.")
18409 (define-minor-mode org-cdlatex-mode
18410 "Toggle the minor `org-cdlatex-mode'.
18411 This mode supports entering LaTeX environment and math in LaTeX fragments
18412 in Org-mode.
18413 \\{org-cdlatex-mode-map}"
18414 nil " OCDL" nil
18415 (when org-cdlatex-mode
18416 (require 'cdlatex)
18417 (run-hooks 'cdlatex-mode-hook)
18418 (cdlatex-compute-tables))
18419 (unless org-cdlatex-texmathp-advice-is-done
18420 (setq org-cdlatex-texmathp-advice-is-done t)
18421 (defadvice texmathp (around org-math-always-on activate)
18422 "Always return t in org-mode buffers.
18423 This is because we want to insert math symbols without dollars even outside
18424 the LaTeX math segments. If Orgmode thinks that point is actually inside
18425 an embedded LaTeX fragment, let texmathp do its job.
18426 \\[org-cdlatex-mode-map]"
18427 (interactive)
18428 (let (p)
18429 (cond
18430 ((not (derived-mode-p 'org-mode)) ad-do-it)
18431 ((eq this-command 'cdlatex-math-symbol)
18432 (setq ad-return-value t
18433 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18435 (let ((p (org-inside-LaTeX-fragment-p)))
18436 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18437 (setq ad-return-value t
18438 texmathp-why '("Org-mode embedded math" . 0))
18439 (if p ad-do-it)))))))))
18441 (defun turn-on-org-cdlatex ()
18442 "Unconditionally turn on `org-cdlatex-mode'."
18443 (org-cdlatex-mode 1))
18445 (defun org-try-cdlatex-tab ()
18446 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18447 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18448 - inside a LaTeX fragment, or
18449 - after the first word in a line, where an abbreviation expansion could
18450 insert a LaTeX environment."
18451 (when org-cdlatex-mode
18452 (cond
18453 ;; Before any word on the line: No expansion possible.
18454 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18455 ;; Just after first word on the line: Expand it. Make sure it
18456 ;; cannot happen on headlines, though.
18457 ((save-excursion
18458 (skip-chars-backward "a-zA-Z0-9*")
18459 (skip-chars-backward " \t")
18460 (and (bolp) (not (org-at-heading-p))))
18461 (cdlatex-tab) t)
18462 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18464 (defun org-cdlatex-underscore-caret (&optional arg)
18465 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18466 Revert to the normal definition outside of these fragments."
18467 (interactive "P")
18468 (if (org-inside-LaTeX-fragment-p)
18469 (call-interactively 'cdlatex-sub-superscript)
18470 (let (org-cdlatex-mode)
18471 (call-interactively (key-binding (vector last-input-event))))))
18473 (defun org-cdlatex-math-modify (&optional arg)
18474 "Execute `cdlatex-math-modify' in LaTeX fragments.
18475 Revert to the normal definition outside of these fragments."
18476 (interactive "P")
18477 (if (org-inside-LaTeX-fragment-p)
18478 (call-interactively 'cdlatex-math-modify)
18479 (let (org-cdlatex-mode)
18480 (call-interactively (key-binding (vector last-input-event))))))
18484 ;;;; LaTeX fragments
18486 (defun org-inside-LaTeX-fragment-p ()
18487 "Test if point is inside a LaTeX fragment.
18488 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18489 sequence appearing also before point.
18490 Even though the matchers for math are configurable, this function assumes
18491 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18492 delimiters are skipped when they have been removed by customization.
18493 The return value is nil, or a cons cell with the delimiter and the
18494 position of this delimiter.
18496 This function does a reasonably good job, but can locally be fooled by
18497 for example currency specifications. For example it will assume being in
18498 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18499 fragments that are properly closed, but during editing, we have to live
18500 with the uncertainty caused by missing closing delimiters. This function
18501 looks only before point, not after."
18502 (catch 'exit
18503 (let ((pos (point))
18504 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18505 (lim (progn
18506 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18507 (point)))
18508 dd-on str (start 0) m re)
18509 (goto-char pos)
18510 (when dodollar
18511 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18512 re (nth 1 (assoc "$" org-latex-regexps)))
18513 (while (string-match re str start)
18514 (cond
18515 ((= (match-end 0) (length str))
18516 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18517 ((= (match-end 0) (- (length str) 5))
18518 (throw 'exit nil))
18519 (t (setq start (match-end 0))))))
18520 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18521 (goto-char pos)
18522 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18523 (and (match-beginning 2) (throw 'exit nil))
18524 ;; count $$
18525 (while (re-search-backward "\\$\\$" lim t)
18526 (setq dd-on (not dd-on)))
18527 (goto-char pos)
18528 (if dd-on (cons "$$" m))))))
18530 (defun org-inside-latex-macro-p ()
18531 "Is point inside a LaTeX macro or its arguments?"
18532 (save-match-data
18533 (org-in-regexp
18534 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18536 (defvar org-latex-fragment-image-overlays nil
18537 "List of overlays carrying the images of latex fragments.")
18538 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18540 (defun org-remove-latex-fragment-image-overlays ()
18541 "Remove all overlays with LaTeX fragment images in current buffer."
18542 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18543 (setq org-latex-fragment-image-overlays nil))
18545 (defun org-preview-latex-fragment (&optional subtree)
18546 "Preview the LaTeX fragment at point, or all locally or globally.
18547 If the cursor is in a LaTeX fragment, create the image and overlay
18548 it over the source code. If there is no fragment at point, display
18549 all fragments in the current text, from one headline to the next. With
18550 prefix SUBTREE, display all fragments in the current subtree. With a
18551 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18552 the cursor is before the first headline,
18553 display all fragments in the buffer.
18554 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18555 (interactive "P")
18556 (unless buffer-file-name
18557 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18558 (when (display-graphic-p)
18559 (org-remove-latex-fragment-image-overlays)
18560 (save-excursion
18561 (save-restriction
18562 (let (beg end at msg)
18563 (cond
18564 ((or (equal subtree '(16))
18565 (not (save-excursion
18566 (re-search-backward org-outline-regexp-bol nil t))))
18567 (setq beg (point-min) end (point-max)
18568 msg "Creating images for buffer...%s"))
18569 ((equal subtree '(4))
18570 (org-back-to-heading)
18571 (setq beg (point) end (org-end-of-subtree t)
18572 msg "Creating images for subtree...%s"))
18574 (if (setq at (org-inside-LaTeX-fragment-p))
18575 (goto-char (max (point-min) (- (cdr at) 2)))
18576 (org-back-to-heading))
18577 (setq beg (point) end (progn (outline-next-heading) (point))
18578 msg (if at "Creating image...%s"
18579 "Creating images for entry...%s"))))
18580 (message msg "")
18581 (narrow-to-region beg end)
18582 (goto-char beg)
18583 (org-format-latex
18584 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18585 (file-name-nondirectory
18586 buffer-file-name)))
18587 default-directory 'overlays msg at 'forbuffer
18588 org-latex-create-formula-image-program)
18589 (message msg "done. Use `C-c C-c' to remove images."))))))
18591 (defun org-format-latex (prefix &optional dir overlays msg at
18592 forbuffer processing-type)
18593 "Replace LaTeX fragments with links to an image, and produce images.
18594 Some of the options can be changed using the variable
18595 `org-format-latex-options'."
18596 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18597 (let* ((prefixnodir (file-name-nondirectory prefix))
18598 (absprefix (expand-file-name prefix dir))
18599 (todir (file-name-directory absprefix))
18600 (opt org-format-latex-options)
18601 (optnew org-format-latex-options)
18602 (matchers (plist-get opt :matchers))
18603 (re-list org-latex-regexps)
18604 (cnt 0) txt hash link beg end re e checkdir
18605 string
18606 m n block-type block linkfile movefile ov)
18607 ;; Check the different regular expressions
18608 (while (setq e (pop re-list))
18609 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18610 block (if block-type "\n\n" ""))
18611 (when (member m matchers)
18612 (goto-char (point-min))
18613 (while (re-search-forward re nil t)
18614 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18615 (or (not overlays)
18616 (not (eq (get-char-property (match-beginning n)
18617 'org-overlay-type)
18618 'org-latex-overlay))))
18619 (cond
18620 ((eq processing-type 'verbatim))
18621 ((eq processing-type 'mathjax)
18622 ;; Prepare for MathJax processing.
18623 (setq string (match-string n))
18624 (when (member m '("$" "$1"))
18625 (save-excursion
18626 (delete-region (match-beginning n) (match-end n))
18627 (goto-char (match-beginning n))
18628 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18629 ((or (eq processing-type 'dvipng)
18630 (eq processing-type 'imagemagick))
18631 ;; Process to an image.
18632 (setq txt (match-string n)
18633 beg (match-beginning n) end (match-end n)
18634 cnt (1+ cnt))
18635 (let ((face (face-at-point))
18636 (fg (plist-get opt :foreground))
18637 (bg (plist-get opt :background))
18638 ;; Ensure full list is printed.
18639 print-length print-level)
18640 (when forbuffer
18641 ;; Get the colors from the face at point.
18642 (goto-char beg)
18643 (when (eq fg 'auto)
18644 (setq fg (face-attribute face :foreground nil 'default)))
18645 (when (eq bg 'auto)
18646 (setq bg (face-attribute face :background nil 'default)))
18647 (setq optnew (copy-sequence opt))
18648 (plist-put optnew :foreground fg)
18649 (plist-put optnew :background bg))
18650 (setq hash (sha1 (prin1-to-string
18651 (list org-format-latex-header
18652 org-latex-default-packages-alist
18653 org-latex-packages-alist
18654 org-format-latex-options
18655 forbuffer txt fg bg)))
18656 linkfile (format "%s_%s.png" prefix hash)
18657 movefile (format "%s_%s.png" absprefix hash)))
18658 (setq link (concat block "[[file:" linkfile "]]" block))
18659 (if msg (message msg cnt))
18660 (goto-char beg)
18661 (unless checkdir ; Ensure the directory exists.
18662 (setq checkdir t)
18663 (or (file-directory-p todir) (make-directory todir t)))
18664 (unless (file-exists-p movefile)
18665 (org-create-formula-image
18666 txt movefile optnew forbuffer processing-type))
18667 (if overlays
18668 (progn
18669 (mapc (lambda (o)
18670 (if (eq (overlay-get o 'org-overlay-type)
18671 'org-latex-overlay)
18672 (delete-overlay o)))
18673 (overlays-in beg end))
18674 (setq ov (make-overlay beg end))
18675 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18676 (if (featurep 'xemacs)
18677 (progn
18678 (overlay-put ov 'invisible t)
18679 (overlay-put
18680 ov 'end-glyph
18681 (make-glyph (vector 'png :file movefile))))
18682 (overlay-put
18683 ov 'display
18684 (list 'image :type 'png :file movefile :ascent 'center)))
18685 (push ov org-latex-fragment-image-overlays)
18686 (goto-char end))
18687 (delete-region beg end)
18688 (insert (org-add-props link
18689 (list 'org-latex-src
18690 (replace-regexp-in-string
18691 "\"" "" txt)
18692 'org-latex-src-embed-type
18693 (if block-type 'paragraph 'character))))))
18694 ((eq processing-type 'mathml)
18695 ;; Process to MathML
18696 (unless (save-match-data (org-format-latex-mathml-available-p))
18697 (user-error "LaTeX to MathML converter not configured"))
18698 (setq txt (match-string n)
18699 beg (match-beginning n) end (match-end n)
18700 cnt (1+ cnt))
18701 (if msg (message msg cnt))
18702 (goto-char beg)
18703 (delete-region beg end)
18704 (insert (org-format-latex-as-mathml
18705 txt block-type prefix dir)))
18707 (error "Unknown conversion type %s for LaTeX fragments"
18708 processing-type)))))))))
18710 (defun org-create-math-formula (latex-frag &optional mathml-file)
18711 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18712 Use `org-latex-to-mathml-convert-command'. If the conversion is
18713 sucessful, return the portion between \"<math...> </math>\"
18714 elements otherwise return nil. When MATHML-FILE is specified,
18715 write the results in to that file. When invoked as an
18716 interactive command, prompt for LATEX-FRAG, with initial value
18717 set to the current active region and echo the results for user
18718 inspection."
18719 (interactive (list (let ((frag (when (org-region-active-p)
18720 (buffer-substring-no-properties
18721 (region-beginning) (region-end)))))
18722 (read-string "LaTeX Fragment: " frag nil frag))))
18723 (unless latex-frag (user-error "Invalid LaTeX fragment"))
18724 (let* ((tmp-in-file (file-relative-name
18725 (make-temp-name (expand-file-name "ltxmathml-in"))))
18726 (ignore (write-region latex-frag nil tmp-in-file))
18727 (tmp-out-file (file-relative-name
18728 (make-temp-name (expand-file-name "ltxmathml-out"))))
18729 (cmd (format-spec
18730 org-latex-to-mathml-convert-command
18731 `((?j . ,(shell-quote-argument
18732 (expand-file-name org-latex-to-mathml-jar-file)))
18733 (?I . ,(shell-quote-argument tmp-in-file))
18734 (?o . ,(shell-quote-argument tmp-out-file)))))
18735 mathml shell-command-output)
18736 (when (org-called-interactively-p 'any)
18737 (unless (org-format-latex-mathml-available-p)
18738 (user-error "LaTeX to MathML converter not configured")))
18739 (message "Running %s" cmd)
18740 (setq shell-command-output (shell-command-to-string cmd))
18741 (setq mathml
18742 (when (file-readable-p tmp-out-file)
18743 (with-current-buffer (find-file-noselect tmp-out-file t)
18744 (goto-char (point-min))
18745 (when (re-search-forward
18746 (concat
18747 (regexp-quote
18748 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18749 "\\(.\\|\n\\)*"
18750 (regexp-quote "</math>")) nil t)
18751 (prog1 (match-string 0) (kill-buffer))))))
18752 (cond
18753 (mathml
18754 (setq mathml
18755 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18756 (when mathml-file
18757 (write-region mathml nil mathml-file))
18758 (when (org-called-interactively-p 'any)
18759 (message mathml)))
18760 ((message "LaTeX to MathML conversion failed")
18761 (message shell-command-output)))
18762 (delete-file tmp-in-file)
18763 (when (file-exists-p tmp-out-file)
18764 (delete-file tmp-out-file))
18765 mathml))
18767 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18768 prefix &optional dir)
18769 "Use `org-create-math-formula' but check local cache first."
18770 (let* ((absprefix (expand-file-name prefix dir))
18771 (print-length nil) (print-level nil)
18772 (formula-id (concat
18773 "formula-"
18774 (sha1
18775 (prin1-to-string
18776 (list latex-frag
18777 org-latex-to-mathml-convert-command)))))
18778 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18779 (formula-cache-dir (file-name-directory formula-cache)))
18781 (unless (file-directory-p formula-cache-dir)
18782 (make-directory formula-cache-dir t))
18784 (unless (file-exists-p formula-cache)
18785 (org-create-math-formula latex-frag formula-cache))
18787 (if (file-exists-p formula-cache)
18788 ;; Successful conversion. Return the link to MathML file.
18789 (org-add-props
18790 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18791 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18792 'org-latex-src-embed-type (if latex-frag-type
18793 'paragraph 'character)))
18794 ;; Failed conversion. Return the LaTeX fragment verbatim
18795 latex-frag)))
18797 (defun org-create-formula-image (string tofile options buffer &optional type)
18798 "Create an image from LaTeX source using dvipng or convert.
18799 This function calls either `org-create-formula-image-with-dvipng'
18800 or `org-create-formula-image-with-imagemagick' depending on the
18801 value of `org-latex-create-formula-image-program' or on the value
18802 of the optional TYPE variable.
18804 Note: ultimately these two function should be combined as they
18805 share a good deal of logic."
18806 (org-check-external-command
18807 "latex" "needed to convert LaTeX fragments to images")
18808 (funcall
18809 (case (or type org-latex-create-formula-image-program)
18810 ('dvipng
18811 (org-check-external-command
18812 "dvipng" "needed to convert LaTeX fragments to images")
18813 'org-create-formula-image-with-dvipng)
18814 ('imagemagick
18815 (org-check-external-command
18816 "convert" "you need to install imagemagick")
18817 'org-create-formula-image-with-imagemagick)
18818 (t (error
18819 "Invalid value of `org-latex-create-formula-image-program'")))
18820 string tofile options buffer))
18822 (declare-function org-export-get-backend "ox" (name))
18823 (declare-function org-export--get-global-options "ox" (&optional backend))
18824 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18825 (declare-function org-latex-guess-inputenc "ox-latex" (header))
18826 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
18827 (defun org-create-formula--latex-header ()
18828 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18829 (let ((info (org-combine-plists (org-export--get-global-options
18830 (org-export-get-backend 'latex))
18831 (org-export--get-inbuffer-options
18832 (org-export-get-backend 'latex)))))
18833 (org-latex-guess-babel-language
18834 (org-latex-guess-inputenc
18835 (org-splice-latex-header
18836 org-format-latex-header
18837 org-latex-default-packages-alist
18838 org-latex-packages-alist t
18839 (plist-get info :latex-header)))
18840 info)))
18842 ;; This function borrows from Ganesh Swami's latex2png.el
18843 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18844 "This calls dvipng."
18845 (require 'ox-latex)
18846 (let* ((tmpdir (if (featurep 'xemacs)
18847 (temp-directory)
18848 temporary-file-directory))
18849 (texfilebase (make-temp-name
18850 (expand-file-name "orgtex" tmpdir)))
18851 (texfile (concat texfilebase ".tex"))
18852 (dvifile (concat texfilebase ".dvi"))
18853 (pngfile (concat texfilebase ".png"))
18854 (fnh (if (featurep 'xemacs)
18855 (font-height (face-font 'default))
18856 (face-attribute 'default :height nil)))
18857 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18858 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18859 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18860 "Black"))
18861 (bg (or (plist-get options (if buffer :background :html-background))
18862 "Transparent")))
18863 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18864 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18865 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18866 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18867 (let ((latex-header (org-create-formula--latex-header)))
18868 (with-temp-file texfile
18869 (insert latex-header)
18870 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18871 (let ((dir default-directory))
18872 (ignore-errors
18873 (cd tmpdir)
18874 (call-process "latex" nil nil nil texfile))
18875 (cd dir))
18876 (if (not (file-exists-p dvifile))
18877 (progn (message "Failed to create dvi file from %s" texfile) nil)
18878 (ignore-errors
18879 (if (featurep 'xemacs)
18880 (call-process "dvipng" nil nil nil
18881 "-fg" fg "-bg" bg
18882 "-T" "tight"
18883 "-o" pngfile
18884 dvifile)
18885 (call-process "dvipng" nil nil nil
18886 "-fg" fg "-bg" bg
18887 "-D" dpi
18888 ;;"-x" scale "-y" scale
18889 "-T" "tight"
18890 "-o" pngfile
18891 dvifile)))
18892 (if (not (file-exists-p pngfile))
18893 (if org-format-latex-signal-error
18894 (error "Failed to create png file from %s" texfile)
18895 (message "Failed to create png file from %s" texfile)
18896 nil)
18897 ;; Use the requested file name and clean up
18898 (copy-file pngfile tofile 'replace)
18899 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18900 (if (file-exists-p (concat texfilebase e))
18901 (delete-file (concat texfilebase e))))
18902 pngfile))))
18904 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18905 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18906 "This calls convert, which is included into imagemagick."
18907 (require 'ox-latex)
18908 (let* ((tmpdir (if (featurep 'xemacs)
18909 (temp-directory)
18910 temporary-file-directory))
18911 (texfilebase (make-temp-name
18912 (expand-file-name "orgtex" tmpdir)))
18913 (texfile (concat texfilebase ".tex"))
18914 (pdffile (concat texfilebase ".pdf"))
18915 (pngfile (concat texfilebase ".png"))
18916 (fnh (if (featurep 'xemacs)
18917 (font-height (face-font 'default))
18918 (face-attribute 'default :height nil)))
18919 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18920 (dpi (number-to-string (* scale (floor (if buffer fnh 120.)))))
18921 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18922 "black"))
18923 (bg (or (plist-get options (if buffer :background :html-background))
18924 "white")))
18925 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18926 (setq fg (org-latex-color-format fg)))
18927 (if (eq bg 'default) (setq bg (org-latex-color :background))
18928 (setq bg (org-latex-color-format
18929 (if (string= bg "Transparent") "white" bg))))
18930 (let ((latex-header (org-create-formula--latex-header)))
18931 (with-temp-file texfile
18932 (insert latex-header)
18933 (insert "\n\\begin{document}\n"
18934 "\\definecolor{fg}{rgb}{" fg "}\n"
18935 "\\definecolor{bg}{rgb}{" bg "}\n"
18936 "\n\\pagecolor{bg}\n"
18937 "\n{\\color{fg}\n"
18938 string
18939 "\n}\n"
18940 "\n\\end{document}\n")))
18941 (org-latex-compile texfile t)
18942 (if (not (file-exists-p pdffile))
18943 (progn (message "Failed to create pdf file from %s" texfile) nil)
18944 (ignore-errors
18945 (if (featurep 'xemacs)
18946 (call-process "convert" nil nil nil
18947 "-density" "96"
18948 "-trim"
18949 "-antialias"
18950 pdffile
18951 "-quality" "100"
18952 ;; "-sharpen" "0x1.0"
18953 pngfile)
18954 (call-process "convert" nil nil nil
18955 "-density" dpi
18956 "-trim"
18957 "-antialias"
18958 pdffile
18959 "-quality" "100"
18960 ;; "-sharpen" "0x1.0"
18961 pngfile)))
18962 (if (not (file-exists-p pngfile))
18963 (if org-format-latex-signal-error
18964 (error "Failed to create png file from %s" texfile)
18965 (message "Failed to create png file from %s" texfile)
18966 nil)
18967 ;; Use the requested file name and clean up
18968 (copy-file pngfile tofile 'replace)
18969 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18970 (if (file-exists-p (concat texfilebase e))
18971 (delete-file (concat texfilebase e))))
18972 pngfile))))
18974 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18975 "Fill a LaTeX header template TPL.
18976 In the template, the following place holders will be recognized:
18978 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18979 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18980 [PACKAGES] \\usepackage statements for PKG
18981 [NO-PACKAGES] do not include PKG
18982 [EXTRA] the string EXTRA
18983 [NO-EXTRA] do not include EXTRA
18985 For backward compatibility, if both the positive and the negative place
18986 holder is missing, the positive one (without the \"NO-\") will be
18987 assumed to be present at the end of the template.
18988 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18989 EXTRA is a string.
18990 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18991 (let (rpl (end ""))
18992 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18993 (setq rpl (if (or (match-end 1) (not def-pkg))
18994 "" (org-latex-packages-to-string def-pkg snippets-p t))
18995 tpl (replace-match rpl t t tpl))
18996 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18998 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18999 (setq rpl (if (or (match-end 1) (not pkg))
19000 "" (org-latex-packages-to-string pkg snippets-p t))
19001 tpl (replace-match rpl t t tpl))
19002 (if pkg (setq end
19003 (concat end "\n"
19004 (org-latex-packages-to-string pkg snippets-p)))))
19006 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19007 (setq rpl (if (or (match-end 1) (not extra))
19008 "" (concat extra "\n"))
19009 tpl (replace-match rpl t t tpl))
19010 (if (and extra (string-match "\\S-" extra))
19011 (setq end (concat end "\n" extra))))
19013 (if (string-match "\\S-" end)
19014 (concat tpl "\n" end)
19015 tpl)))
19017 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19018 "Turn an alist of packages into a string with the \\usepackage macros."
19019 (setq pkg (mapconcat (lambda(p)
19020 (cond
19021 ((stringp p) p)
19022 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19023 (format "%% Package %s omitted" (cadr p)))
19024 ((equal "" (car p))
19025 (format "\\usepackage{%s}" (cadr p)))
19027 (format "\\usepackage[%s]{%s}"
19028 (car p) (cadr p)))))
19030 "\n"))
19031 (if newline (concat pkg "\n") pkg))
19033 (defun org-dvipng-color (attr)
19034 "Return a RGB color specification for dvipng."
19035 (apply 'format "rgb %s %s %s"
19036 (mapcar 'org-normalize-color
19037 (if (featurep 'xemacs)
19038 (color-rgb-components
19039 (face-property 'default
19040 (cond ((eq attr :foreground) 'foreground)
19041 ((eq attr :background) 'background))))
19042 (color-values (face-attribute 'default attr nil))))))
19044 (defun org-dvipng-color-format (color-name)
19045 "Convert COLOR-NAME to a RGB color value for dvipng."
19046 (apply 'format "rgb %s %s %s"
19047 (mapcar 'org-normalize-color
19048 (color-values color-name))))
19050 (defun org-latex-color (attr)
19051 "Return a RGB color for the LaTeX color package."
19052 (apply 'format "%s,%s,%s"
19053 (mapcar 'org-normalize-color
19054 (if (featurep 'xemacs)
19055 (color-rgb-components
19056 (face-property 'default
19057 (cond ((eq attr :foreground) 'foreground)
19058 ((eq attr :background) 'background))))
19059 (color-values (face-attribute 'default attr nil))))))
19061 (defun org-latex-color-format (color-name)
19062 "Convert COLOR-NAME to a RGB color value."
19063 (apply 'format "%s,%s,%s"
19064 (mapcar 'org-normalize-color
19065 (color-values color-name))))
19067 (defun org-normalize-color (value)
19068 "Return string to be used as color value for an RGB component."
19069 (format "%g" (/ value 65535.0)))
19073 ;; Image display
19075 (defvar org-inline-image-overlays nil)
19076 (make-variable-buffer-local 'org-inline-image-overlays)
19078 (defun org-toggle-inline-images (&optional include-linked)
19079 "Toggle the display of inline images.
19080 INCLUDE-LINKED is passed to `org-display-inline-images'."
19081 (interactive "P")
19082 (if org-inline-image-overlays
19083 (progn
19084 (org-remove-inline-images)
19085 (message "Inline image display turned off"))
19086 (org-display-inline-images include-linked)
19087 (if (and (org-called-interactively-p)
19088 org-inline-image-overlays)
19089 (message "%d images displayed inline"
19090 (length org-inline-image-overlays))
19091 (message "No images to display inline"))))
19093 (defun org-redisplay-inline-images ()
19094 "Refresh the display of inline images."
19095 (interactive)
19096 (if (not org-inline-image-overlays)
19097 (org-toggle-inline-images)
19098 (org-toggle-inline-images)
19099 (org-toggle-inline-images)))
19101 (defun org-display-inline-images (&optional include-linked refresh beg end)
19102 "Display inline images.
19104 An inline image is a link which follows either of these
19105 conventions:
19107 1. Its path is a file with an extension matching return value
19108 from `image-file-name-regexp' and it has no contents.
19110 2. Its description consists in a single link of the previous
19111 type.
19113 When optional argument INCLUDE-LINKED is non-nil, also links with
19114 a text description part will be inlined. This can be nice for
19115 a quick look at those images, but it does not reflect what
19116 exported files will look like.
19118 When optional argument REFRESH is non-nil, refresh existing
19119 images between BEG and END. This will create new image displays
19120 only if necessary. BEG and END default to the buffer
19121 boundaries."
19122 (interactive "P")
19123 (when (display-graphic-p)
19124 (unless refresh
19125 (org-remove-inline-images)
19126 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19127 (org-with-wide-buffer
19128 (goto-char (or beg (point-min)))
19129 (let ((case-fold-search t)
19130 (file-extension-re (org-image-file-name-regexp)))
19131 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19132 (let ((link (save-match-data (org-element-context))))
19133 ;; Check if we're at an inline image.
19134 (when (and (equal (org-element-property :type link) "file")
19135 (or include-linked
19136 (not (org-element-property :contents-begin link)))
19137 (let ((parent (org-element-property :parent link)))
19138 (or (not (eq (org-element-type parent) 'link))
19139 (not (cdr (org-element-contents parent)))))
19140 (org-string-match-p file-extension-re
19141 (org-element-property :path link)))
19142 (let ((file (expand-file-name (org-element-property :path link))))
19143 (when (file-exists-p file)
19144 (let ((width
19145 ;; Apply `org-image-actual-width' specifications.
19146 (cond
19147 ((not (image-type-available-p 'imagemagick)) nil)
19148 ((eq org-image-actual-width t) nil)
19149 ((listp org-image-actual-width)
19151 ;; First try to find a width among
19152 ;; attributes associated to the paragraph
19153 ;; containing link.
19154 (let ((paragraph
19155 (let ((e link))
19156 (while (and (setq e (org-element-property
19157 :parent e))
19158 (not (eq (org-element-type e)
19159 'paragraph))))
19160 e)))
19161 (when paragraph
19162 (save-excursion
19163 (goto-char (org-element-property :begin paragraph))
19164 (when (save-match-data
19165 (re-search-forward
19166 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19167 (org-element-property
19168 :post-affiliated paragraph)
19170 (string-to-number (match-string 1))))))
19171 ;; Otherwise, fall-back to provided number.
19172 (car org-image-actual-width)))
19173 ((numberp org-image-actual-width)
19174 org-image-actual-width)))
19175 (old (get-char-property-and-overlay
19176 (org-element-property :begin link)
19177 'org-image-overlay)))
19178 (if (and (car-safe old) refresh)
19179 (image-refresh (overlay-get (cdr old) 'display))
19180 (let ((image (save-match-data
19181 (create-image file
19182 (and width 'imagemagick)
19184 :width width))))
19185 (when image
19186 (let* ((link
19187 ;; If inline image is the description
19188 ;; of another link, be sure to
19189 ;; consider the latter as the one to
19190 ;; apply the overlay on.
19191 (let ((parent
19192 (org-element-property :parent link)))
19193 (if (eq (org-element-type parent) 'link)
19194 parent
19195 link)))
19196 (ov (make-overlay
19197 (org-element-property :begin link)
19198 (progn
19199 (goto-char
19200 (org-element-property :end link))
19201 (skip-chars-backward " \t")
19202 (point)))))
19203 (overlay-put ov 'display image)
19204 (overlay-put ov 'face 'default)
19205 (overlay-put ov 'org-image-overlay t)
19206 (overlay-put
19207 ov 'modification-hooks
19208 (list 'org-display-inline-remove-overlay))
19209 (push ov org-inline-image-overlays)))))))))))))))
19211 (define-obsolete-function-alias
19212 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
19214 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
19215 "Remove inline-display overlay if a corresponding region is modified."
19216 (let ((inhibit-modification-hooks t))
19217 (when (and ov after)
19218 (delete ov org-inline-image-overlays)
19219 (delete-overlay ov))))
19221 (defun org-remove-inline-images ()
19222 "Remove inline display of images."
19223 (interactive)
19224 (mapc 'delete-overlay org-inline-image-overlays)
19225 (setq org-inline-image-overlays nil))
19227 ;;;; Key bindings
19229 ;; Outline functions from `outline-mode-prefix-map'
19230 ;; that can be remapped in Org:
19231 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19232 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
19233 (define-key org-mode-map [remap outline-forward-same-level]
19234 'org-forward-heading-same-level)
19235 (define-key org-mode-map [remap outline-backward-same-level]
19236 'org-backward-heading-same-level)
19237 (define-key org-mode-map [remap show-branches]
19238 'org-kill-note-or-show-branches)
19239 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19240 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19241 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19243 ;; Outline functions from `outline-mode-prefix-map' that can not
19244 ;; be remapped in Org:
19246 ;; - the column "key binding" shows whether the Outline function is still
19247 ;; available in Org mode on the same key that it has been bound to in
19248 ;; Outline mode:
19249 ;; - "overridden": key used for a different functionality in Org mode
19250 ;; - else: key still bound to the same Outline function in Org mode
19252 ;; | Outline function | key binding | Org replacement |
19253 ;; |------------------------------------+-------------+-----------------------|
19254 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
19255 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
19256 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19257 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19258 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19259 ;; | `show-entry' | overridden | no replacement |
19260 ;; | `show-children' | `C-c C-i' | visibility cycling |
19261 ;; | `show-branches' | `C-c C-k' | still same function |
19262 ;; | `show-subtree' | overridden | visibility cycling |
19263 ;; | `show-all' | overridden | no replacement |
19264 ;; | `hide-subtree' | overridden | visibility cycling |
19265 ;; | `hide-body' | overridden | no replacement |
19266 ;; | `hide-entry' | overridden | visibility cycling |
19267 ;; | `hide-leaves' | overridden | no replacement |
19268 ;; | `hide-sublevels' | overridden | no replacement |
19269 ;; | `hide-other' | overridden | no replacement |
19271 ;; Make `C-c C-x' a prefix key
19272 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19274 ;; TAB key with modifiers
19275 (org-defkey org-mode-map "\C-i" 'org-cycle)
19276 (org-defkey org-mode-map [(tab)] 'org-cycle)
19277 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19278 (org-defkey org-mode-map "\M-\t" 'pcomplete)
19279 ;; The following line is necessary under Suse GNU/Linux
19280 (unless (featurep 'xemacs)
19281 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
19282 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19283 (define-key org-mode-map [backtab] 'org-shifttab)
19285 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19286 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19287 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19289 ;; Cursor keys with modifiers
19290 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19291 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19292 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19293 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19295 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19296 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19297 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19298 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19299 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19300 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19302 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19303 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19304 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19305 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19307 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19308 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19309 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19310 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19312 ;; Babel keys
19313 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19314 (mapc (lambda (pair)
19315 (define-key org-babel-map (car pair) (cdr pair)))
19316 org-babel-key-bindings)
19318 ;;; Extra keys for tty access.
19319 ;; We only set them when really needed because otherwise the
19320 ;; menus don't show the simple keys
19322 (when (or org-use-extra-keys
19323 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19324 (not window-system))
19325 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19326 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19327 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19328 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19329 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19330 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19331 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19332 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19333 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19334 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19335 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19336 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19337 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19338 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19339 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19340 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19341 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19342 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19343 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19344 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19345 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19346 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19347 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
19348 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19349 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19350 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19351 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19352 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19354 ;; All the other keys
19356 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
19357 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19358 (if (boundp 'narrow-map)
19359 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19360 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19361 (if (boundp 'narrow-map)
19362 (org-defkey narrow-map "b" 'org-narrow-to-block)
19363 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19364 (if (boundp 'narrow-map)
19365 (org-defkey narrow-map "e" 'org-narrow-to-element)
19366 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19367 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19368 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19369 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19370 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19371 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19372 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19373 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19374 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19375 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19376 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19377 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
19378 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19379 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19380 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19381 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19382 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19383 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19384 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19385 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19386 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19387 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19388 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19389 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19390 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19391 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19392 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19393 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19394 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19395 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19396 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19397 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19398 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19399 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19400 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19401 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19402 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19403 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19404 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19405 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19406 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19407 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19408 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19409 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19410 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19411 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19412 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19413 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19414 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19415 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19416 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19417 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19418 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19419 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19420 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19421 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19422 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19423 (org-defkey org-mode-map "\C-c^" 'org-sort)
19424 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19425 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19426 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19427 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19428 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19429 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19430 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19431 (org-defkey org-mode-map "\C-m" 'org-return)
19432 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19433 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19434 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19435 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19436 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19437 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19438 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19439 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19440 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19441 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19442 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19443 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19444 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19445 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19446 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19447 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19448 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19449 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19450 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19451 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19452 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19453 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19454 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19456 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19457 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19458 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19460 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19461 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19462 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19463 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19464 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19465 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19466 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19467 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19468 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19469 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19470 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
19471 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19472 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19473 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19474 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19475 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19476 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19477 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19478 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19479 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19480 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19481 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19482 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19484 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19485 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19486 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19487 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19488 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19490 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19492 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19494 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19495 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19497 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19500 (when (featurep 'xemacs)
19501 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19504 (defconst org-speed-commands-default
19506 ("Outline Navigation")
19507 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19508 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19509 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19510 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19511 ("F" . org-next-block)
19512 ("B" . org-previous-block)
19513 ("u" . (org-speed-move-safe 'outline-up-heading))
19514 ("j" . org-goto)
19515 ("g" . (org-refile t))
19516 ("Outline Visibility")
19517 ("c" . org-cycle)
19518 ("C" . org-shifttab)
19519 (" " . org-display-outline-path)
19520 ("s" . org-narrow-to-subtree)
19521 ("=" . org-columns)
19522 ("Outline Structure Editing")
19523 ("U" . org-shiftmetaup)
19524 ("D" . org-shiftmetadown)
19525 ("r" . org-metaright)
19526 ("l" . org-metaleft)
19527 ("R" . org-shiftmetaright)
19528 ("L" . org-shiftmetaleft)
19529 ("i" . (progn (forward-char 1) (call-interactively
19530 'org-insert-heading-respect-content)))
19531 ("^" . org-sort)
19532 ("w" . org-refile)
19533 ("a" . org-archive-subtree-default-with-confirmation)
19534 ("@" . org-mark-subtree)
19535 ("#" . org-toggle-comment)
19536 ("Clock Commands")
19537 ("I" . org-clock-in)
19538 ("O" . org-clock-out)
19539 ("Meta Data Editing")
19540 ("t" . org-todo)
19541 ("," . (org-priority))
19542 ("0" . (org-priority ?\ ))
19543 ("1" . (org-priority ?A))
19544 ("2" . (org-priority ?B))
19545 ("3" . (org-priority ?C))
19546 (":" . org-set-tags-command)
19547 ("e" . org-set-effort)
19548 ("E" . org-inc-effort)
19549 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19550 (org-entry-put (point) "APPT_WARNTIME" m)))
19551 ("Agenda Views etc")
19552 ("v" . org-agenda)
19553 ("/" . org-sparse-tree)
19554 ("Misc")
19555 ("o" . org-open-at-point)
19556 ("?" . org-speed-command-help)
19557 ("<" . (org-agenda-set-restriction-lock 'subtree))
19558 (">" . (org-agenda-remove-restriction-lock))
19560 "The default speed commands.")
19562 (defun org-print-speed-command (e)
19563 (if (> (length (car e)) 1)
19564 (progn
19565 (princ "\n")
19566 (princ (car e))
19567 (princ "\n")
19568 (princ (make-string (length (car e)) ?-))
19569 (princ "\n"))
19570 (princ (car e))
19571 (princ " ")
19572 (if (symbolp (cdr e))
19573 (princ (symbol-name (cdr e)))
19574 (prin1 (cdr e)))
19575 (princ "\n")))
19577 (defun org-speed-command-help ()
19578 "Show the available speed commands."
19579 (interactive)
19580 (if (not org-use-speed-commands)
19581 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19582 (with-output-to-temp-buffer "*Help*"
19583 (princ "User-defined Speed commands\n===========================\n")
19584 (mapc 'org-print-speed-command org-speed-commands-user)
19585 (princ "\n")
19586 (princ "Built-in Speed commands\n=======================\n")
19587 (mapc 'org-print-speed-command org-speed-commands-default))
19588 (with-current-buffer "*Help*"
19589 (setq truncate-lines t))))
19591 (defun org-speed-move-safe (cmd)
19592 "Execute CMD, but make sure that the cursor always ends up in a headline.
19593 If not, return to the original position and throw an error."
19594 (interactive)
19595 (let ((pos (point)))
19596 (call-interactively cmd)
19597 (unless (and (bolp) (org-at-heading-p))
19598 (goto-char pos)
19599 (error "Boundary reached while executing %s" cmd))))
19601 (defvar org-self-insert-command-undo-counter 0)
19603 (defvar org-table-auto-blank-field) ; defined in org-table.el
19604 (defvar org-speed-command nil)
19606 (define-obsolete-function-alias
19607 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19609 (defun org-speed-command-activate (keys)
19610 "Hook for activating single-letter speed commands.
19611 `org-speed-commands-default' specifies a minimal command set.
19612 Use `org-speed-commands-user' for further customization."
19613 (when (or (and (bolp) (looking-at org-outline-regexp))
19614 (and (functionp org-use-speed-commands)
19615 (funcall org-use-speed-commands)))
19616 (cdr (assoc keys (append org-speed-commands-user
19617 org-speed-commands-default)))))
19619 (define-obsolete-function-alias
19620 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19622 (defun org-babel-speed-command-activate (keys)
19623 "Hook for activating single-letter code block commands."
19624 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19625 (cdr (assoc keys org-babel-key-bindings))))
19627 (defcustom org-speed-command-hook
19628 '(org-speed-command-default-hook org-babel-speed-command-hook)
19629 "Hook for activating speed commands at strategic locations.
19630 Hook functions are called in sequence until a valid handler is
19631 found.
19633 Each hook takes a single argument, a user-pressed command key
19634 which is also a `self-insert-command' from the global map.
19636 Within the hook, examine the cursor position and the command key
19637 and return nil or a valid handler as appropriate. Handler could
19638 be one of an interactive command, a function, or a form.
19640 Set `org-use-speed-commands' to non-nil value to enable this
19641 hook. The default setting is `org-speed-command-activate'."
19642 :group 'org-structure
19643 :version "24.1"
19644 :type 'hook)
19646 (defun org-self-insert-command (N)
19647 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19648 If the cursor is in a table looking at whitespace, the whitespace is
19649 overwritten, and the table is not marked as requiring realignment."
19650 (interactive "p")
19651 (org-check-before-invisible-edit 'insert)
19652 (cond
19653 ((and org-use-speed-commands
19654 (setq org-speed-command
19655 (run-hook-with-args-until-success
19656 'org-speed-command-hook (this-command-keys))))
19657 (cond
19658 ((commandp org-speed-command)
19659 (setq this-command org-speed-command)
19660 (call-interactively org-speed-command))
19661 ((functionp org-speed-command)
19662 (funcall org-speed-command))
19663 ((and org-speed-command (listp org-speed-command))
19664 (eval org-speed-command))
19665 (t (let (org-use-speed-commands)
19666 (call-interactively 'org-self-insert-command)))))
19667 ((and
19668 (org-table-p)
19669 (progn
19670 ;; check if we blank the field, and if that triggers align
19671 (and (featurep 'org-table) org-table-auto-blank-field
19672 (member last-command
19673 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19674 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19675 ;; got extra space, this field does not determine column width
19676 (let (org-table-may-need-update) (org-table-blank-field))
19677 ;; no extra space, this field may determine column width
19678 (org-table-blank-field)))
19680 (eq N 1)
19681 (looking-at "[^|\n]* |"))
19682 (let (org-table-may-need-update)
19683 (goto-char (1- (match-end 0)))
19684 (backward-delete-char 1)
19685 (goto-char (match-beginning 0))
19686 (self-insert-command N)))
19688 (setq org-table-may-need-update t)
19689 (self-insert-command N)
19690 (org-fix-tags-on-the-fly)
19691 (if org-self-insert-cluster-for-undo
19692 (if (not (eq last-command 'org-self-insert-command))
19693 (setq org-self-insert-command-undo-counter 1)
19694 (if (>= org-self-insert-command-undo-counter 20)
19695 (setq org-self-insert-command-undo-counter 1)
19696 (and (> org-self-insert-command-undo-counter 0)
19697 buffer-undo-list (listp buffer-undo-list)
19698 (not (cadr buffer-undo-list)) ; remove nil entry
19699 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19700 (setq org-self-insert-command-undo-counter
19701 (1+ org-self-insert-command-undo-counter))))))))
19703 (defun org-check-before-invisible-edit (kind)
19704 "Check is editing if kind KIND would be dangerous with invisible text around.
19705 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19706 ;; First, try to get out of here as quickly as possible, to reduce overhead
19707 (if (and org-catch-invisible-edits
19708 (or (not (boundp 'visible-mode)) (not visible-mode))
19709 (or (get-char-property (point) 'invisible)
19710 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19711 ;; OK, we need to take a closer look
19712 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19713 (invisible-before-point (if (bobp) nil (get-char-property
19714 (1- (point)) 'invisible)))
19715 (border-and-ok-direction
19717 ;; Check if we are acting predictably before invisible text
19718 (and invisible-at-point (not invisible-before-point)
19719 (memq kind '(insert delete-backward)))
19720 ;; Check if we are acting predictably after invisible text
19721 ;; This works not well, and I have turned it off. It seems
19722 ;; better to always show and stop after invisible text.
19723 ;; (and (not invisible-at-point) invisible-before-point
19724 ;; (memq kind '(insert delete)))
19726 (when (or (memq invisible-at-point '(outline org-hide-block t))
19727 (memq invisible-before-point '(outline org-hide-block t)))
19728 (if (eq org-catch-invisible-edits 'error)
19729 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19730 (if (and org-custom-properties-overlays
19731 (y-or-n-p "Display invisible properties in this buffer? "))
19732 (org-toggle-custom-properties-visibility)
19733 ;; Make the area visible
19734 (save-excursion
19735 (if invisible-before-point
19736 (goto-char (previous-single-char-property-change
19737 (point) 'invisible)))
19738 (show-subtree))
19739 (cond
19740 ((eq org-catch-invisible-edits 'show)
19741 ;; That's it, we do the edit after showing
19742 (message
19743 "Unfolding invisible region around point before editing")
19744 (sit-for 1))
19745 ((and (eq org-catch-invisible-edits 'smart)
19746 border-and-ok-direction)
19747 (message "Unfolding invisible region around point before editing"))
19749 ;; Don't do the edit, make the user repeat it in full visibility
19750 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19752 (defun org-fix-tags-on-the-fly ()
19753 (when (and (equal (char-after (point-at-bol)) ?*)
19754 (org-at-heading-p))
19755 (org-align-tags-here org-tags-column)))
19757 (defun org-delete-backward-char (N)
19758 "Like `delete-backward-char', insert whitespace at field end in tables.
19759 When deleting backwards, in tables this function will insert whitespace in
19760 front of the next \"|\" separator, to keep the table aligned. The table will
19761 still be marked for re-alignment if the field did fill the entire column,
19762 because, in this case the deletion might narrow the column."
19763 (interactive "p")
19764 (save-match-data
19765 (org-check-before-invisible-edit 'delete-backward)
19766 (if (and (org-table-p)
19767 (eq N 1)
19768 (string-match "|" (buffer-substring (point-at-bol) (point)))
19769 (looking-at ".*?|"))
19770 (let ((pos (point))
19771 (noalign (looking-at "[^|\n\r]* |"))
19772 (c org-table-may-need-update))
19773 (backward-delete-char N)
19774 (if (not overwrite-mode)
19775 (progn
19776 (skip-chars-forward "^|")
19777 (insert " ")
19778 (goto-char (1- pos))))
19779 ;; noalign: if there were two spaces at the end, this field
19780 ;; does not determine the width of the column.
19781 (if noalign (setq org-table-may-need-update c)))
19782 (backward-delete-char N)
19783 (org-fix-tags-on-the-fly))))
19785 (defun org-delete-char (N)
19786 "Like `delete-char', but insert whitespace at field end in tables.
19787 When deleting characters, in tables this function will insert whitespace in
19788 front of the next \"|\" separator, to keep the table aligned. The table will
19789 still be marked for re-alignment if the field did fill the entire column,
19790 because, in this case the deletion might narrow the column."
19791 (interactive "p")
19792 (save-match-data
19793 (org-check-before-invisible-edit 'delete)
19794 (if (and (org-table-p)
19795 (not (bolp))
19796 (not (= (char-after) ?|))
19797 (eq N 1))
19798 (if (looking-at ".*?|")
19799 (let ((pos (point))
19800 (noalign (looking-at "[^|\n\r]* |"))
19801 (c org-table-may-need-update))
19802 (replace-match
19803 (concat (substring (match-string 0) 1 -1) " |") nil t)
19804 (goto-char pos)
19805 ;; noalign: if there were two spaces at the end, this field
19806 ;; does not determine the width of the column.
19807 (if noalign (setq org-table-may-need-update c)))
19808 (delete-char N))
19809 (delete-char N)
19810 (org-fix-tags-on-the-fly))))
19812 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19813 (put 'org-self-insert-command 'delete-selection
19814 (lambda ()
19815 (not (run-hook-with-args-until-success
19816 'self-insert-uses-region-functions))))
19817 (put 'orgtbl-self-insert-command 'delete-selection
19818 (lambda ()
19819 (not (run-hook-with-args-until-success
19820 'self-insert-uses-region-functions))))
19821 (put 'org-delete-char 'delete-selection 'supersede)
19822 (put 'org-delete-backward-char 'delete-selection 'supersede)
19823 (put 'org-yank 'delete-selection 'yank)
19825 ;; Make `flyspell-mode' delay after some commands
19826 (put 'org-self-insert-command 'flyspell-delayed t)
19827 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19828 (put 'org-delete-char 'flyspell-delayed t)
19829 (put 'org-delete-backward-char 'flyspell-delayed t)
19831 ;; Make pabbrev-mode expand after org-mode commands
19832 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19833 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19835 (defun org-remap (map &rest commands)
19836 "In MAP, remap the functions given in COMMANDS.
19837 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19838 (let (new old)
19839 (while commands
19840 (setq old (pop commands) new (pop commands))
19841 (if (fboundp 'command-remapping)
19842 (org-defkey map (vector 'remap old) new)
19843 (substitute-key-definition old new map global-map)))))
19845 (defun org-transpose-words ()
19846 "Transpose words for Org.
19847 This uses the `org-mode-transpose-word-syntax-table' syntax
19848 table, which interprets characters in `org-emphasis-alist' as
19849 word constituents."
19850 (interactive)
19851 (with-syntax-table org-mode-transpose-word-syntax-table
19852 (call-interactively 'transpose-words)))
19853 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19855 (when (eq org-enable-table-editor 'optimized)
19856 ;; If the user wants maximum table support, we need to hijack
19857 ;; some standard editing functions
19858 (org-remap org-mode-map
19859 'self-insert-command 'org-self-insert-command
19860 'delete-char 'org-delete-char
19861 'delete-backward-char 'org-delete-backward-char)
19862 (org-defkey org-mode-map "|" 'org-force-self-insert))
19864 (defvar org-ctrl-c-ctrl-c-hook nil
19865 "Hook for functions attaching themselves to `C-c C-c'.
19867 This can be used to add additional functionality to the C-c C-c
19868 key which executes context-dependent commands. This hook is run
19869 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19870 run after the last test.
19872 Each function will be called with no arguments. The function
19873 must check if the context is appropriate for it to act. If yes,
19874 it should do its thing and then return a non-nil value. If the
19875 context is wrong, just do nothing and return nil.")
19877 (defvar org-ctrl-c-ctrl-c-final-hook nil
19878 "Hook for functions attaching themselves to `C-c C-c'.
19880 This can be used to add additional functionality to the C-c C-c
19881 key which executes context-dependent commands. This hook is run
19882 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19883 before the first test.
19885 Each function will be called with no arguments. The function
19886 must check if the context is appropriate for it to act. If yes,
19887 it should do its thing and then return a non-nil value. If the
19888 context is wrong, just do nothing and return nil.")
19890 (defvar org-tab-first-hook nil
19891 "Hook for functions to attach themselves to TAB.
19892 See `org-ctrl-c-ctrl-c-hook' for more information.
19893 This hook runs as the first action when TAB is pressed, even before
19894 `org-cycle' messes around with the `outline-regexp' to cater for
19895 inline tasks and plain list item folding.
19896 If any function in this hook returns t, any other actions that
19897 would have been caused by TAB (such as table field motion or visibility
19898 cycling) will not occur.")
19900 (defvar org-tab-after-check-for-table-hook nil
19901 "Hook for functions to attach themselves to TAB.
19902 See `org-ctrl-c-ctrl-c-hook' for more information.
19903 This hook runs after it has been established that the cursor is not in a
19904 table, but before checking if the cursor is in a headline or if global cycling
19905 should be done.
19906 If any function in this hook returns t, not other actions like visibility
19907 cycling will be done.")
19909 (defvar org-tab-after-check-for-cycling-hook nil
19910 "Hook for functions to attach themselves to TAB.
19911 See `org-ctrl-c-ctrl-c-hook' for more information.
19912 This hook runs after it has been established that not table field motion and
19913 not visibility should be done because of current context. This is probably
19914 the place where a package like yasnippets can hook in.")
19916 (defvar org-tab-before-tab-emulation-hook nil
19917 "Hook for functions to attach themselves to TAB.
19918 See `org-ctrl-c-ctrl-c-hook' for more information.
19919 This hook runs after every other options for TAB have been exhausted, but
19920 before indentation and \t insertion takes place.")
19922 (defvar org-metaleft-hook nil
19923 "Hook for functions attaching themselves to `M-left'.
19924 See `org-ctrl-c-ctrl-c-hook' for more information.")
19925 (defvar org-metaright-hook nil
19926 "Hook for functions attaching themselves to `M-right'.
19927 See `org-ctrl-c-ctrl-c-hook' for more information.")
19928 (defvar org-metaup-hook nil
19929 "Hook for functions attaching themselves to `M-up'.
19930 See `org-ctrl-c-ctrl-c-hook' for more information.")
19931 (defvar org-metadown-hook nil
19932 "Hook for functions attaching themselves to `M-down'.
19933 See `org-ctrl-c-ctrl-c-hook' for more information.")
19934 (defvar org-shiftmetaleft-hook nil
19935 "Hook for functions attaching themselves to `M-S-left'.
19936 See `org-ctrl-c-ctrl-c-hook' for more information.")
19937 (defvar org-shiftmetaright-hook nil
19938 "Hook for functions attaching themselves to `M-S-right'.
19939 See `org-ctrl-c-ctrl-c-hook' for more information.")
19940 (defvar org-shiftmetaup-hook nil
19941 "Hook for functions attaching themselves to `M-S-up'.
19942 See `org-ctrl-c-ctrl-c-hook' for more information.")
19943 (defvar org-shiftmetadown-hook nil
19944 "Hook for functions attaching themselves to `M-S-down'.
19945 See `org-ctrl-c-ctrl-c-hook' for more information.")
19946 (defvar org-metareturn-hook nil
19947 "Hook for functions attaching themselves to `M-RET'.
19948 See `org-ctrl-c-ctrl-c-hook' for more information.")
19949 (defvar org-shiftup-hook nil
19950 "Hook for functions attaching themselves to `S-up'.
19951 See `org-ctrl-c-ctrl-c-hook' for more information.")
19952 (defvar org-shiftup-final-hook nil
19953 "Hook for functions attaching themselves to `S-up'.
19954 This one runs after all other options except shift-select have been excluded.
19955 See `org-ctrl-c-ctrl-c-hook' for more information.")
19956 (defvar org-shiftdown-hook nil
19957 "Hook for functions attaching themselves to `S-down'.
19958 See `org-ctrl-c-ctrl-c-hook' for more information.")
19959 (defvar org-shiftdown-final-hook nil
19960 "Hook for functions attaching themselves to `S-down'.
19961 This one runs after all other options except shift-select have been excluded.
19962 See `org-ctrl-c-ctrl-c-hook' for more information.")
19963 (defvar org-shiftleft-hook nil
19964 "Hook for functions attaching themselves to `S-left'.
19965 See `org-ctrl-c-ctrl-c-hook' for more information.")
19966 (defvar org-shiftleft-final-hook nil
19967 "Hook for functions attaching themselves to `S-left'.
19968 This one runs after all other options except shift-select have been excluded.
19969 See `org-ctrl-c-ctrl-c-hook' for more information.")
19970 (defvar org-shiftright-hook nil
19971 "Hook for functions attaching themselves to `S-right'.
19972 See `org-ctrl-c-ctrl-c-hook' for more information.")
19973 (defvar org-shiftright-final-hook nil
19974 "Hook for functions attaching themselves to `S-right'.
19975 This one runs after all other options except shift-select have been excluded.
19976 See `org-ctrl-c-ctrl-c-hook' for more information.")
19978 (defun org-modifier-cursor-error ()
19979 "Throw an error, a modified cursor command was applied in wrong context."
19980 (user-error "This command is active in special context like tables, headlines or items"))
19982 (defun org-shiftselect-error ()
19983 "Throw an error because Shift-Cursor command was applied in wrong context."
19984 (if (and (boundp 'shift-select-mode) shift-select-mode)
19985 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19986 (user-error "This command works only in special context like headlines or timestamps")))
19988 (defun org-call-for-shift-select (cmd)
19989 (let ((this-command-keys-shift-translated t))
19990 (call-interactively cmd)))
19992 (defun org-shifttab (&optional arg)
19993 "Global visibility cycling or move to previous table field.
19994 Call `org-table-previous-field' within a table.
19995 When ARG is nil, cycle globally through visibility states.
19996 When ARG is a numeric prefix, show contents of this level."
19997 (interactive "P")
19998 (cond
19999 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20000 ((integerp arg)
20001 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20002 (message "Content view to level: %d" arg)
20003 (org-content (prefix-numeric-value arg2))
20004 (org-cycle-show-empty-lines t)
20005 (setq org-cycle-global-status 'overview)))
20006 (t (call-interactively 'org-global-cycle))))
20008 (defun org-shiftmetaleft ()
20009 "Promote subtree or delete table column.
20010 Calls `org-promote-subtree', `org-outdent-item-tree', or
20011 `org-table-delete-column', depending on context. See the
20012 individual commands for more information."
20013 (interactive)
20014 (cond
20015 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20016 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20017 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20018 ((if (not (org-region-active-p)) (org-at-item-p)
20019 (save-excursion (goto-char (region-beginning))
20020 (org-at-item-p)))
20021 (call-interactively 'org-outdent-item-tree))
20022 (t (org-modifier-cursor-error))))
20024 (defun org-shiftmetaright ()
20025 "Demote subtree or insert table column.
20026 Calls `org-demote-subtree', `org-indent-item-tree', or
20027 `org-table-insert-column', depending on context. See the
20028 individual commands for more information."
20029 (interactive)
20030 (cond
20031 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20032 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20033 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20034 ((if (not (org-region-active-p)) (org-at-item-p)
20035 (save-excursion (goto-char (region-beginning))
20036 (org-at-item-p)))
20037 (call-interactively 'org-indent-item-tree))
20038 (t (org-modifier-cursor-error))))
20040 (defun org-shiftmetaup (&optional arg)
20041 "Drag the line at point up.
20042 In a table, kill the current row.
20043 On a clock timestamp, update the value of the timestamp like `S-<up>'
20044 but also adjust the previous clocked item in the clock history.
20045 Everywhere else, drag the line at point up."
20046 (interactive "P")
20047 (cond
20048 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20049 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20050 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20051 (call-interactively 'org-timestamp-up)))
20052 (t (call-interactively 'org-drag-line-backward))))
20054 (defun org-shiftmetadown (&optional arg)
20055 "Drag the line at point down.
20056 In a table, insert an empty row at the current line.
20057 On a clock timestamp, update the value of the timestamp like `S-<down>'
20058 but also adjust the previous clocked item in the clock history.
20059 Everywhere else, drag the line at point down."
20060 (interactive "P")
20061 (cond
20062 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20063 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20064 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20065 (call-interactively 'org-timestamp-down)))
20066 (t (call-interactively 'org-drag-line-forward))))
20068 (defsubst org-hidden-tree-error ()
20069 (user-error
20070 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20072 (defun org-metaleft (&optional arg)
20073 "Promote heading or move table column to left.
20074 Calls `org-do-promote' or `org-table-move-column', depending on context.
20075 With no specific context, calls the Emacs default `backward-word'.
20076 See the individual commands for more information."
20077 (interactive "P")
20078 (cond
20079 ((run-hook-with-args-until-success 'org-metaleft-hook))
20080 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20081 ((org-with-limited-levels
20082 (or (org-at-heading-p)
20083 (and (org-region-active-p)
20084 (save-excursion
20085 (goto-char (region-beginning))
20086 (org-at-heading-p)))))
20087 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20088 (call-interactively 'org-do-promote))
20089 ;; At an inline task.
20090 ((org-at-heading-p)
20091 (call-interactively 'org-inlinetask-promote))
20092 ((or (org-at-item-p)
20093 (and (org-region-active-p)
20094 (save-excursion
20095 (goto-char (region-beginning))
20096 (org-at-item-p))))
20097 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20098 (call-interactively 'org-outdent-item))
20099 (t (call-interactively 'backward-word))))
20101 (defun org-metaright (&optional arg)
20102 "Demote a subtree, a list item or move table column to right.
20103 In front of a drawer or a block keyword, indent it correctly.
20104 With no specific context, calls the Emacs default `forward-word'.
20105 See the individual commands for more information."
20106 (interactive "P")
20107 (cond
20108 ((run-hook-with-args-until-success 'org-metaright-hook))
20109 ((org-at-table-p) (call-interactively 'org-table-move-column))
20110 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20111 ((org-at-block-p) (call-interactively 'org-indent-block))
20112 ((org-with-limited-levels
20113 (or (org-at-heading-p)
20114 (and (org-region-active-p)
20115 (save-excursion
20116 (goto-char (region-beginning))
20117 (org-at-heading-p)))))
20118 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20119 (call-interactively 'org-do-demote))
20120 ;; At an inline task.
20121 ((org-at-heading-p)
20122 (call-interactively 'org-inlinetask-demote))
20123 ((or (org-at-item-p)
20124 (and (org-region-active-p)
20125 (save-excursion
20126 (goto-char (region-beginning))
20127 (org-at-item-p))))
20128 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20129 (call-interactively 'org-indent-item))
20130 (t (call-interactively 'forward-word))))
20132 (defun org-check-for-hidden (what)
20133 "Check if there are hidden headlines/items in the current visual line.
20134 WHAT can be either `headlines' or `items'. If the current line is
20135 an outline or item heading and it has a folded subtree below it,
20136 this function returns t, nil otherwise."
20137 (let ((re (cond
20138 ((eq what 'headlines) org-outline-regexp-bol)
20139 ((eq what 'items) (org-item-beginning-re))
20140 (t (error "This should not happen"))))
20141 beg end)
20142 (save-excursion
20143 (catch 'exit
20144 (unless (org-region-active-p)
20145 (setq beg (point-at-bol))
20146 (beginning-of-line 2)
20147 (while (and (not (eobp)) ;; this is like `next-line'
20148 (get-char-property (1- (point)) 'invisible))
20149 (beginning-of-line 2))
20150 (setq end (point))
20151 (goto-char beg)
20152 (goto-char (point-at-eol))
20153 (setq end (max end (point)))
20154 (while (re-search-forward re end t)
20155 (if (get-char-property (match-beginning 0) 'invisible)
20156 (throw 'exit t))))
20157 nil))))
20159 (defun org-metaup (&optional arg)
20160 "Move subtree up or move table row up.
20161 Calls `org-move-subtree-up' or `org-table-move-row' or
20162 `org-move-item-up', depending on context. See the individual commands
20163 for more information."
20164 (interactive "P")
20165 (cond
20166 ((run-hook-with-args-until-success 'org-metaup-hook))
20167 ((org-region-active-p)
20168 (let* ((a (min (region-beginning) (region-end)))
20169 (b (1- (max (region-beginning) (region-end))))
20170 (c (save-excursion (goto-char a)
20171 (move-beginning-of-line 0)))
20172 (d (save-excursion (goto-char a)
20173 (move-end-of-line 0) (point))))
20174 (transpose-regions a b c d)
20175 (goto-char c)))
20176 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20177 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20178 ((org-at-item-p) (call-interactively 'org-move-item-up))
20179 (t (org-drag-element-backward))))
20181 (defun org-metadown (&optional arg)
20182 "Move subtree down or move table row down.
20183 Calls `org-move-subtree-down' or `org-table-move-row' or
20184 `org-move-item-down', depending on context. See the individual
20185 commands for more information."
20186 (interactive "P")
20187 (cond
20188 ((run-hook-with-args-until-success 'org-metadown-hook))
20189 ((org-region-active-p)
20190 (let* ((a (min (region-beginning) (region-end)))
20191 (b (max (region-beginning) (region-end)))
20192 (c (save-excursion (goto-char b)
20193 (move-beginning-of-line 1)))
20194 (d (save-excursion (goto-char b)
20195 (move-end-of-line 1) (1+ (point)))))
20196 (transpose-regions a b c d)
20197 (goto-char d)))
20198 ((org-at-table-p) (call-interactively 'org-table-move-row))
20199 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20200 ((org-at-item-p) (call-interactively 'org-move-item-down))
20201 (t (org-drag-element-forward))))
20203 (defun org-shiftup (&optional arg)
20204 "Increase item in timestamp or increase priority of current headline.
20205 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20206 depending on context. See the individual commands for more information."
20207 (interactive "P")
20208 (cond
20209 ((run-hook-with-args-until-success 'org-shiftup-hook))
20210 ((and org-support-shift-select (org-region-active-p))
20211 (org-call-for-shift-select 'previous-line))
20212 ((org-at-timestamp-p t)
20213 (call-interactively (if org-edit-timestamp-down-means-later
20214 'org-timestamp-down 'org-timestamp-up)))
20215 ((and (not (eq org-support-shift-select 'always))
20216 org-enable-priority-commands
20217 (org-at-heading-p))
20218 (call-interactively 'org-priority-up))
20219 ((and (not org-support-shift-select) (org-at-item-p))
20220 (call-interactively 'org-previous-item))
20221 ((org-clocktable-try-shift 'up arg))
20222 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20223 (org-support-shift-select
20224 (org-call-for-shift-select 'previous-line))
20225 (t (org-shiftselect-error))))
20227 (defun org-shiftdown (&optional arg)
20228 "Decrease item in timestamp or decrease priority of current headline.
20229 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20230 depending on context. See the individual commands for more information."
20231 (interactive "P")
20232 (cond
20233 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20234 ((and org-support-shift-select (org-region-active-p))
20235 (org-call-for-shift-select 'next-line))
20236 ((org-at-timestamp-p t)
20237 (call-interactively (if org-edit-timestamp-down-means-later
20238 'org-timestamp-up 'org-timestamp-down)))
20239 ((and (not (eq org-support-shift-select 'always))
20240 org-enable-priority-commands
20241 (org-at-heading-p))
20242 (call-interactively 'org-priority-down))
20243 ((and (not org-support-shift-select) (org-at-item-p))
20244 (call-interactively 'org-next-item))
20245 ((org-clocktable-try-shift 'down arg))
20246 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20247 (org-support-shift-select
20248 (org-call-for-shift-select 'next-line))
20249 (t (org-shiftselect-error))))
20251 (defun org-shiftright (&optional arg)
20252 "Cycle the thing at point or in the current line, depending on context.
20253 Depending on context, this does one of the following:
20255 - switch a timestamp at point one day into the future
20256 - on a headline, switch to the next TODO keyword.
20257 - on an item, switch entire list to the next bullet type
20258 - on a property line, switch to the next allowed value
20259 - on a clocktable definition line, move time block into the future"
20260 (interactive "P")
20261 (cond
20262 ((run-hook-with-args-until-success 'org-shiftright-hook))
20263 ((and org-support-shift-select (org-region-active-p))
20264 (org-call-for-shift-select 'forward-char))
20265 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20266 ((and (not (eq org-support-shift-select 'always))
20267 (org-at-heading-p))
20268 (let ((org-inhibit-logging
20269 (not org-treat-S-cursor-todo-selection-as-state-change))
20270 (org-inhibit-blocking
20271 (not org-treat-S-cursor-todo-selection-as-state-change)))
20272 (org-call-with-arg 'org-todo 'right)))
20273 ((or (and org-support-shift-select
20274 (not (eq org-support-shift-select 'always))
20275 (org-at-item-bullet-p))
20276 (and (not org-support-shift-select) (org-at-item-p)))
20277 (org-call-with-arg 'org-cycle-list-bullet nil))
20278 ((and (not (eq org-support-shift-select 'always))
20279 (org-at-property-p))
20280 (call-interactively 'org-property-next-allowed-value))
20281 ((org-clocktable-try-shift 'right arg))
20282 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20283 (org-support-shift-select
20284 (org-call-for-shift-select 'forward-char))
20285 (t (org-shiftselect-error))))
20287 (defun org-shiftleft (&optional arg)
20288 "Cycle the thing at point or in the current line, depending on context.
20289 Depending on context, this does one of the following:
20291 - switch a timestamp at point one day into the past
20292 - on a headline, switch to the previous TODO keyword.
20293 - on an item, switch entire list to the previous bullet type
20294 - on a property line, switch to the previous allowed value
20295 - on a clocktable definition line, move time block into the past"
20296 (interactive "P")
20297 (cond
20298 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20299 ((and org-support-shift-select (org-region-active-p))
20300 (org-call-for-shift-select 'backward-char))
20301 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20302 ((and (not (eq org-support-shift-select 'always))
20303 (org-at-heading-p))
20304 (let ((org-inhibit-logging
20305 (not org-treat-S-cursor-todo-selection-as-state-change))
20306 (org-inhibit-blocking
20307 (not org-treat-S-cursor-todo-selection-as-state-change)))
20308 (org-call-with-arg 'org-todo 'left)))
20309 ((or (and org-support-shift-select
20310 (not (eq org-support-shift-select 'always))
20311 (org-at-item-bullet-p))
20312 (and (not org-support-shift-select) (org-at-item-p)))
20313 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20314 ((and (not (eq org-support-shift-select 'always))
20315 (org-at-property-p))
20316 (call-interactively 'org-property-previous-allowed-value))
20317 ((org-clocktable-try-shift 'left arg))
20318 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20319 (org-support-shift-select
20320 (org-call-for-shift-select 'backward-char))
20321 (t (org-shiftselect-error))))
20323 (defun org-shiftcontrolright ()
20324 "Switch to next TODO set."
20325 (interactive)
20326 (cond
20327 ((and org-support-shift-select (org-region-active-p))
20328 (org-call-for-shift-select 'forward-word))
20329 ((and (not (eq org-support-shift-select 'always))
20330 (org-at-heading-p))
20331 (org-call-with-arg 'org-todo 'nextset))
20332 (org-support-shift-select
20333 (org-call-for-shift-select 'forward-word))
20334 (t (org-shiftselect-error))))
20336 (defun org-shiftcontrolleft ()
20337 "Switch to previous TODO set."
20338 (interactive)
20339 (cond
20340 ((and org-support-shift-select (org-region-active-p))
20341 (org-call-for-shift-select 'backward-word))
20342 ((and (not (eq org-support-shift-select 'always))
20343 (org-at-heading-p))
20344 (org-call-with-arg 'org-todo 'previousset))
20345 (org-support-shift-select
20346 (org-call-for-shift-select 'backward-word))
20347 (t (org-shiftselect-error))))
20349 (defun org-shiftcontrolup (&optional n)
20350 "Change timestamps synchronously up in CLOCK log lines.
20351 Optional argument N tells to change by that many units."
20352 (interactive "P")
20353 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20354 (let (org-support-shift-select)
20355 (org-clock-timestamps-up n))
20356 (user-error "Not at a clock log")))
20358 (defun org-shiftcontroldown (&optional n)
20359 "Change timestamps synchronously down in CLOCK log lines.
20360 Optional argument N tells to change by that many units."
20361 (interactive "P")
20362 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20363 (let (org-support-shift-select)
20364 (org-clock-timestamps-down n))
20365 (user-error "Not at a clock log")))
20367 (defun org-increase-number-at-point (&optional inc)
20368 "Increment the number at point.
20369 With an optional prefix numeric argument INC, increment using
20370 this numeric value."
20371 (interactive "p")
20372 (if (not (number-at-point))
20373 (user-error "Not on a number")
20374 (unless inc (setq inc 1))
20375 (let ((pos (point))
20376 (beg (skip-chars-backward "-+^/*0-9eE."))
20377 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20378 (setq nap (buffer-substring-no-properties
20379 (+ pos beg) (+ pos beg end)))
20380 (delete-region (+ pos beg) (+ pos beg end))
20381 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20382 (when (org-at-table-p)
20383 (org-table-align)
20384 (org-table-end-of-field 1))))
20386 (defun org-decrease-number-at-point (&optional inc)
20387 "Decrement the number at point.
20388 With an optional prefix numeric argument INC, decrement using
20389 this numeric value."
20390 (interactive "p")
20391 (org-increase-number-at-point (- inc)))
20393 (defun org-ctrl-c-ret ()
20394 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20395 (interactive)
20396 (cond
20397 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20398 (t (call-interactively 'org-insert-heading))))
20400 (defun org-find-visible ()
20401 (let ((s (point)))
20402 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20403 (get-char-property s 'invisible)))
20405 (defun org-find-invisible ()
20406 (let ((s (point)))
20407 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20408 (not (get-char-property s 'invisible))))
20411 (defun org-copy-visible (beg end)
20412 "Copy the visible parts of the region."
20413 (interactive "r")
20414 (let (snippets s)
20415 (save-excursion
20416 (save-restriction
20417 (narrow-to-region beg end)
20418 (setq s (goto-char (point-min)))
20419 (while (not (= (point) (point-max)))
20420 (goto-char (org-find-invisible))
20421 (push (buffer-substring s (point)) snippets)
20422 (setq s (goto-char (org-find-visible))))))
20423 (kill-new (apply 'concat (nreverse snippets)))))
20425 (defun org-copy-special ()
20426 "Copy region in table or copy current subtree.
20427 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20428 See the individual commands for more information."
20429 (interactive)
20430 (call-interactively
20431 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20433 (defun org-cut-special ()
20434 "Cut region in table or cut current subtree.
20435 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20436 See the individual commands for more information."
20437 (interactive)
20438 (call-interactively
20439 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20441 (defun org-paste-special (arg)
20442 "Paste rectangular region into table, or past subtree relative to level.
20443 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20444 See the individual commands for more information."
20445 (interactive "P")
20446 (if (org-at-table-p)
20447 (org-table-paste-rectangle)
20448 (org-paste-subtree arg)))
20450 (defsubst org-in-fixed-width-region-p ()
20451 "Is point in a fixed-width region?"
20452 (save-match-data
20453 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20455 (defun org-edit-special (&optional arg)
20456 "Call a special editor for the element at point.
20457 When at a table, call the formula editor with `org-table-edit-formulas'.
20458 When in a source code block, call `org-edit-src-code'.
20459 When in a fixed-width region, call `org-edit-fixed-width-region'.
20460 When at an #+INCLUDE keyword, visit the included file.
20461 On a link, call `ffap' to visit the link at point.
20462 Otherwise, return a user error."
20463 (interactive "P")
20464 (let ((element (org-element-at-point)))
20465 (assert (not buffer-read-only) nil
20466 "Buffer is read-only: %s" (buffer-name))
20467 (case (org-element-type element)
20468 (src-block
20469 (if (not arg) (org-edit-src-code)
20470 (let* ((info (org-babel-get-src-block-info))
20471 (lang (nth 0 info))
20472 (params (nth 2 info))
20473 (session (cdr (assq :session params))))
20474 (if (not session) (org-edit-src-code)
20475 ;; At a src-block with a session and function called with
20476 ;; an ARG: switch to the buffer related to the inferior
20477 ;; process.
20478 (switch-to-buffer
20479 (funcall (intern (concat "org-babel-prep-session:" lang))
20480 session params))))))
20481 (keyword
20482 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20483 (find-file-other-window
20484 (org-remove-double-quotes
20485 (car (org-split-string (org-element-property :value element)))))
20486 (user-error "No special environment to edit here")))
20487 (table
20488 (if (eq (org-element-property :type element) 'table.el)
20489 (org-edit-src-code)
20490 (call-interactively 'org-table-edit-formulas)))
20491 ;; Only Org tables contain `table-row' type elements.
20492 (table-row (call-interactively 'org-table-edit-formulas))
20493 ((example-block export-block) (org-edit-src-code))
20494 (fixed-width (org-edit-fixed-width-region))
20495 (otherwise
20496 ;; No notable element at point. Though, we may be at a link,
20497 ;; which is an object. Thus, scan deeper.
20498 (if (eq (org-element-type (org-element-context element)) 'link)
20499 (call-interactively 'ffap)
20500 (user-error "No special environment to edit here"))))))
20502 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20503 (defun org-ctrl-c-ctrl-c (&optional arg)
20504 "Set tags in headline, or update according to changed information at point.
20506 This command does many different things, depending on context:
20508 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20509 this is what we do.
20511 - If the cursor is on a statistics cookie, update it.
20513 - If the cursor is in a headline, prompt for tags and insert them
20514 into the current line, aligned to `org-tags-column'. When called
20515 with prefix arg, realign all tags in the current buffer.
20517 - If the cursor is in one of the special #+KEYWORD lines, this
20518 triggers scanning the buffer for these lines and updating the
20519 information.
20521 - If the cursor is inside a table, realign the table. This command
20522 works even if the automatic table editor has been turned off.
20524 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20525 the entire table.
20527 - If the cursor is at a footnote reference or definition, jump to
20528 the corresponding definition or references, respectively.
20530 - If the cursor is a the beginning of a dynamic block, update it.
20532 - If the current buffer is a capture buffer, close note and file it.
20534 - If the cursor is on a <<<target>>>, update radio targets and
20535 corresponding links in this buffer.
20537 - If the cursor is on a numbered item in a plain list, renumber the
20538 ordered list.
20540 - If the cursor is on a checkbox, toggle it.
20542 - If the cursor is on a code block, evaluate it. The variable
20543 `org-confirm-babel-evaluate' can be used to control prompting
20544 before code block evaluation, by default every code block
20545 evaluation requires confirmation. Code block evaluation can be
20546 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20547 (interactive "P")
20548 (cond
20549 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20550 org-occur-highlights
20551 org-latex-fragment-image-overlays)
20552 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20553 (org-remove-occur-highlights)
20554 (org-remove-latex-fragment-image-overlays)
20555 (message "Temporary highlights/overlays removed from current buffer"))
20556 ((and (local-variable-p 'org-finish-function (current-buffer))
20557 (fboundp org-finish-function))
20558 (funcall org-finish-function))
20559 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20561 (let* ((context (org-element-context)) (type (org-element-type context)))
20562 ;; Test if point is within a blank line.
20563 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20564 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20565 (user-error "C-c C-c can do nothing useful at this location"))
20566 (case type
20567 ;; When at a link, act according to the parent instead.
20568 (link (setq context (org-element-property :parent context))
20569 (setq type (org-element-type context)))
20570 ;; Unsupported object types: refer to the first supported
20571 ;; element or object containing it.
20572 ((bold code entity export-snippet inline-babel-call inline-src-block
20573 italic latex-fragment line-break macro strike-through subscript
20574 superscript underline verbatim)
20575 (while (and (setq context (org-element-property :parent context))
20576 (not (memq (setq type (org-element-type context))
20577 '(radio-target paragraph verse-block
20578 table-cell)))))))
20579 ;; For convenience: at the first line of a paragraph on the
20580 ;; same line as an item, apply function on that item instead.
20581 (when (eq type 'paragraph)
20582 (let ((parent (org-element-property :parent context)))
20583 (when (and (eq (org-element-type parent) 'item)
20584 (= (point-at-bol) (org-element-property :begin parent)))
20585 (setq context parent type 'item))))
20586 ;; Act according to type of element or object at point.
20587 (case type
20588 (clock (org-clock-update-time-maybe))
20589 (dynamic-block
20590 (save-excursion
20591 (goto-char (org-element-property :post-affiliated context))
20592 (org-update-dblock)))
20593 (footnote-definition
20594 (goto-char (org-element-property :post-affiliated context))
20595 (call-interactively 'org-footnote-action))
20596 (footnote-reference (call-interactively 'org-footnote-action))
20597 ((headline inlinetask)
20598 (save-excursion (goto-char (org-element-property :begin context))
20599 (call-interactively 'org-set-tags)))
20600 (item
20601 ;; At an item: a double C-u set checkbox to "[-]"
20602 ;; unconditionally, whereas a single one will toggle its
20603 ;; presence. Without an universal argument, if the item
20604 ;; has a checkbox, toggle it. Otherwise repair the list.
20605 (let* ((box (org-element-property :checkbox context))
20606 (struct (org-element-property :structure context))
20607 (old-struct (copy-tree struct))
20608 (parents (org-list-parents-alist struct))
20609 (prevs (org-list-prevs-alist struct))
20610 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20611 (org-list-set-checkbox
20612 (org-element-property :begin context) struct
20613 (cond ((equal arg '(16)) "[-]")
20614 ((and (not box) (equal arg '(4))) "[ ]")
20615 ((or (not box) (equal arg '(4))) nil)
20616 ((eq box 'on) "[ ]")
20617 (t "[X]")))
20618 ;; Mimic `org-list-write-struct' but with grabbing
20619 ;; a return value from `org-list-struct-fix-box'.
20620 (org-list-struct-fix-ind struct parents 2)
20621 (org-list-struct-fix-item-end struct)
20622 (org-list-struct-fix-bul struct prevs)
20623 (org-list-struct-fix-ind struct parents)
20624 (let ((block-item
20625 (org-list-struct-fix-box struct parents prevs orderedp)))
20626 (if (and box (equal struct old-struct))
20627 (if (equal arg '(16))
20628 (message "Checkboxes already reset")
20629 (user-error "Cannot toggle this checkbox: %s"
20630 (if (eq box 'on)
20631 "all subitems checked"
20632 "unchecked subitems")))
20633 (org-list-struct-apply-struct struct old-struct)
20634 (org-update-checkbox-count-maybe))
20635 (when block-item
20636 (message "Checkboxes were removed due to empty box at line %d"
20637 (org-current-line block-item))))))
20638 (keyword
20639 (let ((org-inhibit-startup-visibility-stuff t)
20640 (org-startup-align-all-tables nil))
20641 (when (boundp 'org-table-coordinate-overlays)
20642 (mapc 'delete-overlay org-table-coordinate-overlays)
20643 (setq org-table-coordinate-overlays nil))
20644 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20645 (message "Local setup has been refreshed"))
20646 (plain-list
20647 ;; At a plain list, with a double C-u argument, set
20648 ;; checkboxes of each item to "[-]", whereas a single one
20649 ;; will toggle their presence according to the state of the
20650 ;; first item in the list. Without an argument, repair the
20651 ;; list.
20652 (let* ((begin (org-element-property :contents-begin context))
20653 (beginm (move-marker (make-marker) begin))
20654 (struct (org-element-property :structure context))
20655 (old-struct (copy-tree struct))
20656 (first-box (save-excursion
20657 (goto-char begin)
20658 (looking-at org-list-full-item-re)
20659 (match-string-no-properties 3)))
20660 (new-box (cond ((equal arg '(16)) "[-]")
20661 ((equal arg '(4)) (unless first-box "[ ]"))
20662 ((equal first-box "[X]") "[ ]")
20663 (t "[X]"))))
20664 (cond
20665 (arg
20666 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20667 (org-list-get-all-items
20668 begin struct (org-list-prevs-alist struct))))
20669 ((and first-box (eq (point) begin))
20670 ;; For convenience, when point is at bol on the first
20671 ;; item of the list and no argument is provided, simply
20672 ;; toggle checkbox of that item, if any.
20673 (org-list-set-checkbox begin struct new-box)))
20674 (org-list-write-struct
20675 struct (org-list-parents-alist struct) old-struct)
20676 (org-update-checkbox-count-maybe)
20677 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20678 ((property-drawer node-property)
20679 (call-interactively 'org-property-action))
20680 ((radio-target target)
20681 (call-interactively 'org-update-radio-target-regexp))
20682 (statistics-cookie
20683 (call-interactively 'org-update-statistics-cookies))
20684 ((table table-cell table-row)
20685 ;; At a table, recalculate every field and align it. Also
20686 ;; send the table if necessary. If the table has
20687 ;; a `table.el' type, just give up. At a table row or
20688 ;; cell, maybe recalculate line but always align table.
20689 (if (eq (org-element-property :type context) 'table.el)
20690 (message "Use C-c ' to edit table.el tables")
20691 (let ((org-enable-table-editor t))
20692 (if (or (eq type 'table)
20693 ;; Check if point is at a TBLFM line.
20694 (and (eq type 'table-row)
20695 (= (point) (org-element-property :end context))))
20696 (save-excursion
20697 (if (org-at-TBLFM-p)
20698 (progn (require 'org-table)
20699 (org-table-calc-current-TBLFM))
20700 (goto-char (org-element-property :contents-begin context))
20701 (org-call-with-arg 'org-table-recalculate (or arg t))
20702 (orgtbl-send-table 'maybe)))
20703 (org-table-maybe-eval-formula)
20704 (cond (arg (call-interactively 'org-table-recalculate))
20705 ((org-table-maybe-recalculate-line))
20706 (t (org-table-align)))))))
20707 (timestamp (org-timestamp-change 0 'day))
20708 (otherwise
20709 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20710 (user-error
20711 "C-c C-c can do nothing useful at this location")))))))))
20713 (defun org-mode-restart ()
20714 (interactive)
20715 (let ((indent-status (org-bound-and-true-p org-indent-mode)))
20716 (funcall major-mode)
20717 (hack-local-variables)
20718 (when (and indent-status (not (org-bound-and-true-p org-indent-mode)))
20719 (org-indent-mode -1)))
20720 (message "%s restarted" major-mode))
20722 (defun org-kill-note-or-show-branches ()
20723 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20724 (interactive)
20725 (if (not org-finish-function)
20726 (progn
20727 (hide-subtree)
20728 (call-interactively 'show-branches))
20729 (let ((org-note-abort t))
20730 (funcall org-finish-function))))
20732 (defun org-open-line (n)
20733 "Insert a new row in tables, call `open-line' elsewhere.
20734 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
20735 (interactive "*p")
20736 (cond
20737 ((not org-special-ctrl-o)
20738 (open-line n))
20739 ((org-at-table-p)
20740 (org-table-insert-row))
20742 (open-line n))))
20744 (defun org-return (&optional indent)
20745 "Goto next table row or insert a newline.
20746 Calls `org-table-next-row' or `newline', depending on context.
20747 See the individual commands for more information."
20748 (interactive)
20749 (let (org-ts-what)
20750 (cond
20751 ((or (bobp) (org-in-src-block-p))
20752 (if indent (newline-and-indent) (newline)))
20753 ((org-at-table-p)
20754 (org-table-justify-field-maybe)
20755 (call-interactively 'org-table-next-row))
20756 ;; when `newline-and-indent' is called within a list, make sure
20757 ;; text moved stays inside the item.
20758 ((and (org-in-item-p) indent)
20759 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20760 (progn
20761 (save-match-data (newline))
20762 (org-indent-line-to (length (match-string 0))))
20763 (let ((ind (org-get-indentation)))
20764 (newline)
20765 (if (org-looking-back org-list-end-re)
20766 (org-indent-line)
20767 (org-indent-line-to ind)))))
20768 ((and org-return-follows-link
20769 (org-at-timestamp-p t)
20770 (not (eq org-ts-what 'after)))
20771 (org-follow-timestamp-link))
20772 ((and org-return-follows-link
20773 (let ((tprop (get-text-property (point) 'face)))
20774 (or (eq tprop 'org-link)
20775 (and (listp tprop) (memq 'org-link tprop)))))
20776 (call-interactively 'org-open-at-point))
20777 ((and (org-at-heading-p)
20778 (looking-at
20779 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20780 (org-show-entry)
20781 (end-of-line 1)
20782 (newline))
20783 (t (if indent (newline-and-indent) (newline))))))
20785 (defun org-return-indent ()
20786 "Goto next table row or insert a newline and indent.
20787 Calls `org-table-next-row' or `newline-and-indent', depending on
20788 context. See the individual commands for more information."
20789 (interactive)
20790 (org-return t))
20792 (defun org-ctrl-c-star ()
20793 "Compute table, or change heading status of lines.
20794 Calls `org-table-recalculate' or `org-toggle-heading',
20795 depending on context."
20796 (interactive)
20797 (cond
20798 ((org-at-table-p)
20799 (call-interactively 'org-table-recalculate))
20801 ;; Convert all lines in region to list items
20802 (call-interactively 'org-toggle-heading))))
20804 (defun org-ctrl-c-minus ()
20805 "Insert separator line in table or modify bullet status of line.
20806 Also turns a plain line or a region of lines into list items.
20807 Calls `org-table-insert-hline', `org-toggle-item', or
20808 `org-cycle-list-bullet', depending on context."
20809 (interactive)
20810 (cond
20811 ((org-at-table-p)
20812 (call-interactively 'org-table-insert-hline))
20813 ((org-region-active-p)
20814 (call-interactively 'org-toggle-item))
20815 ((org-in-item-p)
20816 (call-interactively 'org-cycle-list-bullet))
20818 (call-interactively 'org-toggle-item))))
20820 (defun org-toggle-item (arg)
20821 "Convert headings or normal lines to items, items to normal lines.
20822 If there is no active region, only the current line is considered.
20824 If the first non blank line in the region is a headline, convert
20825 all headlines to items, shifting text accordingly.
20827 If it is an item, convert all items to normal lines.
20829 If it is normal text, change region into a list of items.
20830 With a prefix argument ARG, change the region in a single item."
20831 (interactive "P")
20832 (let ((shift-text
20833 (function
20834 ;; Shift text in current section to IND, from point to END.
20835 ;; The function leaves point to END line.
20836 (lambda (ind end)
20837 (let ((min-i 1000) (end (copy-marker end)))
20838 ;; First determine the minimum indentation (MIN-I) of
20839 ;; the text.
20840 (save-excursion
20841 (catch 'exit
20842 (while (< (point) end)
20843 (let ((i (org-get-indentation)))
20844 (cond
20845 ;; Skip blank lines and inline tasks.
20846 ((looking-at "^[ \t]*$"))
20847 ((looking-at org-outline-regexp-bol))
20848 ;; We can't find less than 0 indentation.
20849 ((zerop i) (throw 'exit (setq min-i 0)))
20850 ((< i min-i) (setq min-i i))))
20851 (forward-line))))
20852 ;; Then indent each line so that a line indented to
20853 ;; MIN-I becomes indented to IND. Ignore blank lines
20854 ;; and inline tasks in the process.
20855 (let ((delta (- ind min-i)))
20856 (while (< (point) end)
20857 (unless (or (looking-at "^[ \t]*$")
20858 (looking-at org-outline-regexp-bol))
20859 (org-indent-line-to (+ (org-get-indentation) delta)))
20860 (forward-line)))))))
20861 (skip-blanks
20862 (function
20863 ;; Return beginning of first non-blank line, starting from
20864 ;; line at POS.
20865 (lambda (pos)
20866 (save-excursion
20867 (goto-char pos)
20868 (skip-chars-forward " \r\t\n")
20869 (point-at-bol)))))
20870 beg end)
20871 ;; Determine boundaries of changes.
20872 (if (org-region-active-p)
20873 (setq beg (funcall skip-blanks (region-beginning))
20874 end (copy-marker (region-end)))
20875 (setq beg (funcall skip-blanks (point-at-bol))
20876 end (copy-marker (point-at-eol))))
20877 ;; Depending on the starting line, choose an action on the text
20878 ;; between BEG and END.
20879 (org-with-limited-levels
20880 (save-excursion
20881 (goto-char beg)
20882 (cond
20883 ;; Case 1. Start at an item: de-itemize. Note that it only
20884 ;; happens when a region is active: `org-ctrl-c-minus'
20885 ;; would call `org-cycle-list-bullet' otherwise.
20886 ((org-at-item-p)
20887 (while (< (point) end)
20888 (when (org-at-item-p)
20889 (skip-chars-forward " \t")
20890 (delete-region (point) (match-end 0)))
20891 (forward-line)))
20892 ;; Case 2. Start at an heading: convert to items.
20893 ((org-at-heading-p)
20894 (let* ((bul (org-list-bullet-string "-"))
20895 (bul-len (length bul))
20896 (done (org-entry-is-done-p))
20897 (todo (org-entry-is-todo-p))
20898 ;; Indentation of the first heading. It should be
20899 ;; relative to the indentation of its parent, if any.
20900 (start-ind (save-excursion
20901 (cond
20902 ((not org-adapt-indentation) 0)
20903 ((not (outline-previous-heading)) 0)
20904 (t (length (match-string 0))))))
20905 ;; Level of first heading. Further headings will be
20906 ;; compared to it to determine hierarchy in the list.
20907 (ref-level (org-reduced-level (org-outline-level))))
20908 (when (or done todo) (org-todo ""))
20909 (while (< (point) end)
20910 (let* ((level (org-reduced-level (org-outline-level)))
20911 (delta (max 0 (- level ref-level))))
20912 ;; If current headline is less indented than the first
20913 ;; one, set it as reference, in order to preserve
20914 ;; subtrees.
20915 (when (< level ref-level) (setq ref-level level))
20916 (replace-match bul t t)
20917 (org-indent-line-to (+ start-ind (* delta bul-len)))
20918 (when (or done todo)
20919 (let* ((struct (org-list-struct))
20920 (old (copy-tree struct)))
20921 (org-list-set-checkbox (line-beginning-position)
20922 struct
20923 (if done "[X]" "[ ]"))
20924 (org-list-write-struct struct
20925 (org-list-parents-alist struct)
20926 old)))
20927 ;; Ensure all text down to END (or SECTION-END) belongs
20928 ;; to the newly created item.
20929 (let ((section-end (save-excursion
20930 (or (outline-next-heading) (point)))))
20931 (forward-line)
20932 (funcall shift-text
20933 (+ start-ind (* (1+ delta) bul-len))
20934 (min end section-end)))))))
20935 ;; Case 3. Normal line with ARG: make the first line of region
20936 ;; an item, and shift indentation of others lines to
20937 ;; set them as item's body.
20938 (arg (let* ((bul (org-list-bullet-string "-"))
20939 (bul-len (length bul))
20940 (ref-ind (org-get-indentation)))
20941 (skip-chars-forward " \t")
20942 (insert bul)
20943 (forward-line)
20944 (while (< (point) end)
20945 ;; Ensure that lines less indented than first one
20946 ;; still get included in item body.
20947 (funcall shift-text
20948 (+ ref-ind bul-len)
20949 (min end (save-excursion (or (outline-next-heading)
20950 (point)))))
20951 (forward-line))))
20952 ;; Case 4. Normal line without ARG: turn each non-item line
20953 ;; into an item.
20955 (while (< (point) end)
20956 (unless (or (org-at-heading-p) (org-at-item-p))
20957 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20958 (replace-match
20959 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20960 (forward-line))))))))
20962 (defun org-toggle-heading (&optional nstars)
20963 "Convert headings to normal text, or items or text to headings.
20964 If there is no active region, only convert the current line.
20966 With a \\[universal-argument] prefix, convert the whole list at
20967 point into heading.
20969 In a region:
20971 - If the first non blank line is a headline, remove the stars
20972 from all headlines in the region.
20974 - If it is a normal line, turn each and every normal line (i.e.,
20975 not an heading or an item) in the region into headings. If you
20976 want to convert only the first line of this region, use one
20977 universal prefix argument.
20979 - If it is a plain list item, turn all plain list items into headings.
20981 When converting a line into a heading, the number of stars is chosen
20982 such that the lines become children of the current entry. However,
20983 when a numeric prefix argument is given, its value determines the
20984 number of stars to add."
20985 (interactive "P")
20986 (let ((skip-blanks
20987 (function
20988 ;; Return beginning of first non-blank line, starting from
20989 ;; line at POS.
20990 (lambda (pos)
20991 (save-excursion
20992 (goto-char pos)
20993 (while (org-at-comment-p) (forward-line))
20994 (skip-chars-forward " \r\t\n")
20995 (point-at-bol)))))
20996 beg end toggled)
20997 ;; Determine boundaries of changes. If a universal prefix has
20998 ;; been given, put the list in a region. If region ends at a bol,
20999 ;; do not consider the last line to be in the region.
21001 (when (and current-prefix-arg (org-at-item-p))
21002 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
21003 (org-mark-element))
21005 (if (org-region-active-p)
21006 (setq beg (funcall skip-blanks (region-beginning))
21007 end (copy-marker (save-excursion
21008 (goto-char (region-end))
21009 (if (bolp) (point) (point-at-eol)))))
21010 (setq beg (funcall skip-blanks (point-at-bol))
21011 end (copy-marker (point-at-eol))))
21012 ;; Ensure inline tasks don't count as headings.
21013 (org-with-limited-levels
21014 (save-excursion
21015 (goto-char beg)
21016 (cond
21017 ;; Case 1. Started at an heading: de-star headings.
21018 ((org-at-heading-p)
21019 (while (< (point) end)
21020 (when (org-at-heading-p t)
21021 (looking-at org-outline-regexp) (replace-match "")
21022 (setq toggled t))
21023 (forward-line)))
21024 ;; Case 2. Started at an item: change items into headlines.
21025 ;; One star will be added by `org-list-to-subtree'.
21026 ((org-at-item-p)
21027 (let* ((stars (make-string
21028 ;; subtract the star that will be added again by
21029 ;; `org-list-to-subtree'
21030 (if (numberp nstars) (1- nstars)
21031 (or (org-current-level) 0))
21032 ?*))
21033 (add-stars
21034 (cond (nstars "") ; stars from prefix only
21035 ((equal stars "") "") ; before first heading
21036 (org-odd-levels-only "*") ; inside heading, odd
21037 (t "")))) ; inside heading, oddeven
21038 (while (< (point) end)
21039 (when (org-at-item-p)
21040 ;; Pay attention to cases when region ends before list.
21041 (let* ((struct (org-list-struct))
21042 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
21043 (save-restriction
21044 (narrow-to-region (point) list-end)
21045 (insert
21046 (org-list-to-subtree
21047 (org-list-parse-list t)
21048 '(:istart (concat stars add-stars (funcall get-stars depth))
21049 :icount (concat stars add-stars (funcall get-stars depth)))))))
21050 (setq toggled t))
21051 (forward-line))))
21052 ;; Case 3. Started at normal text: make every line an heading,
21053 ;; skipping headlines and items.
21054 (t (let* ((stars
21055 (make-string
21056 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21057 (add-stars
21058 (cond (nstars "") ; stars from prefix only
21059 ((equal stars "") "*") ; before first heading
21060 (org-odd-levels-only "**") ; inside heading, odd
21061 (t "*"))) ; inside heading, oddeven
21062 (rpl (concat stars add-stars " "))
21063 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
21064 (while (< (point) (if (equal nstars '(4)) lend end))
21065 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21066 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21067 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21068 (forward-line)))))))
21069 (unless toggled (message "Cannot toggle heading from here"))))
21071 (defun org-meta-return (&optional arg)
21072 "Insert a new heading or wrap a region in a table.
21073 Calls `org-insert-heading' or `org-table-wrap-region', depending
21074 on context. See the individual commands for more information."
21075 (interactive "P")
21076 (org-check-before-invisible-edit 'insert)
21077 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21078 (let* ((element (org-element-at-point))
21079 (type (org-element-type element)))
21080 (when (eq type 'table-row)
21081 (setq element (org-element-property :parent element))
21082 (setq type 'table))
21083 (if (and (eq type 'table)
21084 (eq (org-element-property :type element) 'org)
21085 (>= (point) (org-element-property :contents-begin element))
21086 (< (point) (org-element-property :contents-end element)))
21087 (call-interactively 'org-table-wrap-region)
21088 (call-interactively 'org-insert-heading)))))
21090 ;;; Menu entries
21092 (defsubst org-in-subtree-not-table-p ()
21093 "Are we in a subtree and not in a table?"
21094 (and (not (org-before-first-heading-p))
21095 (not (org-at-table-p))))
21097 ;; Define the Org-mode menus
21098 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21099 '("Tbl"
21100 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21101 ["Next Field" org-cycle (org-at-table-p)]
21102 ["Previous Field" org-shifttab (org-at-table-p)]
21103 ["Next Row" org-return (org-at-table-p)]
21104 "--"
21105 ["Blank Field" org-table-blank-field (org-at-table-p)]
21106 ["Edit Field" org-table-edit-field (org-at-table-p)]
21107 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21108 "--"
21109 ("Column"
21110 ["Move Column Left" org-metaleft (org-at-table-p)]
21111 ["Move Column Right" org-metaright (org-at-table-p)]
21112 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21113 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21114 ("Row"
21115 ["Move Row Up" org-metaup (org-at-table-p)]
21116 ["Move Row Down" org-metadown (org-at-table-p)]
21117 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21118 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21119 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21120 "--"
21121 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21122 ("Rectangle"
21123 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21124 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21125 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21126 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21127 "--"
21128 ("Calculate"
21129 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21130 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21131 ["Edit Formulas" org-edit-special (org-at-table-p)]
21132 "--"
21133 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21134 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21135 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21136 "--"
21137 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21138 "--"
21139 ["Sum Column/Rectangle" org-table-sum
21140 (or (org-at-table-p) (org-region-active-p))]
21141 ["Which Column?" org-table-current-column (org-at-table-p)])
21142 ["Debug Formulas"
21143 org-table-toggle-formula-debugger
21144 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
21145 ["Show Col/Row Numbers"
21146 org-table-toggle-coordinate-overlays
21147 :style toggle
21148 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
21149 "--"
21150 ["Create" org-table-create (and (not (org-at-table-p))
21151 org-enable-table-editor)]
21152 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21153 ["Import from File" org-table-import (not (org-at-table-p))]
21154 ["Export to File" org-table-export (org-at-table-p)]
21155 "--"
21156 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
21158 (easy-menu-define org-org-menu org-mode-map "Org menu"
21159 '("Org"
21160 ("Show/Hide"
21161 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21162 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21163 ["Sparse Tree..." org-sparse-tree t]
21164 ["Reveal Context" org-reveal t]
21165 ["Show All" show-all t]
21166 "--"
21167 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21168 "--"
21169 ["New Heading" org-insert-heading t]
21170 ("Navigate Headings"
21171 ["Up" outline-up-heading t]
21172 ["Next" outline-next-visible-heading t]
21173 ["Previous" outline-previous-visible-heading t]
21174 ["Next Same Level" outline-forward-same-level t]
21175 ["Previous Same Level" outline-backward-same-level t]
21176 "--"
21177 ["Jump" org-goto t])
21178 ("Edit Structure"
21179 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21180 "--"
21181 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
21182 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
21183 "--"
21184 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21185 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21186 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21187 "--"
21188 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21189 "--"
21190 ["Copy visible text" org-copy-visible t]
21191 "--"
21192 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21193 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21194 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21195 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21196 "--"
21197 ["Sort Region/Children" org-sort t]
21198 "--"
21199 ["Convert to odd levels" org-convert-to-odd-levels t]
21200 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21201 ("Editing"
21202 ["Emphasis..." org-emphasize t]
21203 ["Edit Source Example" org-edit-special t]
21204 "--"
21205 ["Footnote new/jump" org-footnote-action t]
21206 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21207 ("Archive"
21208 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21209 "--"
21210 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
21211 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21212 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21214 "--"
21215 ("Hyperlinks"
21216 ["Store Link (Global)" org-store-link t]
21217 ["Find existing link to here" org-occur-link-in-agenda-files t]
21218 ["Insert Link" org-insert-link t]
21219 ["Follow Link" org-open-at-point t]
21220 "--"
21221 ["Next link" org-next-link t]
21222 ["Previous link" org-previous-link t]
21223 "--"
21224 ["Descriptive Links"
21225 org-toggle-link-display
21226 :style radio
21227 :selected org-descriptive-links
21229 ["Literal Links"
21230 org-toggle-link-display
21231 :style radio
21232 :selected (not org-descriptive-links)])
21233 "--"
21234 ("TODO Lists"
21235 ["TODO/DONE/-" org-todo t]
21236 ("Select keyword"
21237 ["Next keyword" org-shiftright (org-at-heading-p)]
21238 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21239 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21240 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21241 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21242 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21243 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21244 "--"
21245 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21246 :selected org-enforce-todo-dependencies :style toggle :active t]
21247 "Settings for tree at point"
21248 ["Do Children sequentially" org-toggle-ordered-property :style radio
21249 :selected (org-entry-get nil "ORDERED")
21250 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21251 ["Do Children parallel" org-toggle-ordered-property :style radio
21252 :selected (not (org-entry-get nil "ORDERED"))
21253 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21254 "--"
21255 ["Set Priority" org-priority t]
21256 ["Priority Up" org-shiftup t]
21257 ["Priority Down" org-shiftdown t]
21258 "--"
21259 ["Get news from all feeds" org-feed-update-all t]
21260 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21261 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21262 ("TAGS and Properties"
21263 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21264 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21265 "--"
21266 ["Set property" org-set-property (not (org-before-first-heading-p))]
21267 ["Column view of properties" org-columns t]
21268 ["Insert Column View DBlock" org-insert-columns-dblock t])
21269 ("Dates and Scheduling"
21270 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21271 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21272 ("Change Date"
21273 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21274 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21275 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21276 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21277 ["Compute Time Range" org-evaluate-time-range t]
21278 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21279 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21280 "--"
21281 ["Custom time format" org-toggle-time-stamp-overlays
21282 :style radio :selected org-display-custom-times]
21283 "--"
21284 ["Goto Calendar" org-goto-calendar t]
21285 ["Date from Calendar" org-date-from-calendar t]
21286 "--"
21287 ["Start/Restart Timer" org-timer-start t]
21288 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21289 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21290 ["Insert Timer String" org-timer t]
21291 ["Insert Timer Item" org-timer-item t])
21292 ("Logging work"
21293 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21294 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21295 ["Clock out" org-clock-out t]
21296 ["Clock cancel" org-clock-cancel t]
21297 "--"
21298 ["Mark as default task" org-clock-mark-default-task t]
21299 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21300 ["Goto running clock" org-clock-goto t]
21301 "--"
21302 ["Display times" org-clock-display t]
21303 ["Create clock table" org-clock-report t]
21304 "--"
21305 ["Record DONE time"
21306 (progn (setq org-log-done (not org-log-done))
21307 (message "Switching to %s will %s record a timestamp"
21308 (car org-done-keywords)
21309 (if org-log-done "automatically" "not")))
21310 :style toggle :selected org-log-done])
21311 "--"
21312 ["Agenda Command..." org-agenda t]
21313 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21314 ("File List for Agenda")
21315 ("Special views current file"
21316 ["TODO Tree" org-show-todo-tree t]
21317 ["Check Deadlines" org-check-deadlines t]
21318 ["Timeline" org-timeline t]
21319 ["Tags/Property tree" org-match-sparse-tree t])
21320 "--"
21321 ["Export/Publish..." org-export-dispatch t]
21322 ("LaTeX"
21323 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21324 :selected org-cdlatex-mode]
21325 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21326 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21327 ["Modify math symbol" org-cdlatex-math-modify
21328 (org-inside-LaTeX-fragment-p)]
21329 ["Insert citation" org-reftex-citation t]
21330 "--"
21331 ["Template for BEAMER" (org-beamer-insert-options-template) t])
21332 "--"
21333 ("MobileOrg"
21334 ["Push Files and Views" org-mobile-push t]
21335 ["Get Captured and Flagged" org-mobile-pull t]
21336 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21337 "--"
21338 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21339 "--"
21340 ("Documentation"
21341 ["Show Version" org-version t]
21342 ["Info Documentation" org-info t])
21343 ("Customize"
21344 ["Browse Org Group" org-customize t]
21345 "--"
21346 ["Expand This Menu" org-create-customize-menu
21347 (fboundp 'customize-menu-create)])
21348 ["Send bug report" org-submit-bug-report t]
21349 "--"
21350 ("Refresh/Reload"
21351 ["Refresh setup current buffer" org-mode-restart t]
21352 ["Reload Org (after update)" org-reload t]
21353 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21356 (defun org-info (&optional node)
21357 "Read documentation for Org-mode in the info system.
21358 With optional NODE, go directly to that node."
21359 (interactive)
21360 (info (format "(org)%s" (or node ""))))
21362 ;;;###autoload
21363 (defun org-submit-bug-report ()
21364 "Submit a bug report on Org-mode via mail.
21366 Don't hesitate to report any problems or inaccurate documentation.
21368 If you don't have setup sending mail from (X)Emacs, please copy the
21369 output buffer into your mail program, as it gives us important
21370 information about your Org-mode version and configuration."
21371 (interactive)
21372 (require 'reporter)
21373 (org-load-modules-maybe)
21374 (org-require-autoloaded-modules)
21375 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21376 (reporter-submit-bug-report
21377 "emacs-orgmode@gnu.org"
21378 (org-version nil 'full)
21379 (let (list)
21380 (save-window-excursion
21381 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21382 (delete-other-windows)
21383 (erase-buffer)
21384 (insert "You are about to submit a bug report to the Org-mode mailing list.
21386 We would like to add your full Org-mode and Outline configuration to the
21387 bug report. This greatly simplifies the work of the maintainer and
21388 other experts on the mailing list.
21390 HOWEVER, some variables you have customized may contain private
21391 information. The names of customers, colleagues, or friends, might
21392 appear in the form of file names, tags, todo states, or search strings.
21393 If you answer yes to the prompt, you might want to check and remove
21394 such private information before sending the email.")
21395 (add-text-properties (point-min) (point-max) '(face org-warning))
21396 (when (yes-or-no-p "Include your Org-mode configuration ")
21397 (mapatoms
21398 (lambda (v)
21399 (and (boundp v)
21400 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21401 (or (and (symbol-value v)
21402 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21403 (and
21404 (get v 'custom-type) (get v 'standard-value)
21405 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21406 (push v list)))))
21407 (kill-buffer (get-buffer "*Warn about privacy*"))
21408 list))
21409 nil nil
21410 "Remember to cover the basics, that is, what you expected to happen and
21411 what in fact did happen. You don't know how to make a good report? See
21413 http://orgmode.org/manual/Feedback.html#Feedback
21415 Your bug report will be posted to the Org-mode mailing list.
21416 ------------------------------------------------------------------------")
21417 (save-excursion
21418 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21419 (replace-match "\\1Bug: \\3 [\\2]")))))
21422 (defun org-install-agenda-files-menu ()
21423 (let ((bl (buffer-list)))
21424 (save-excursion
21425 (while bl
21426 (set-buffer (pop bl))
21427 (if (derived-mode-p 'org-mode) (setq bl nil)))
21428 (when (derived-mode-p 'org-mode)
21429 (easy-menu-change
21430 '("Org") "File List for Agenda"
21431 (append
21432 (list
21433 ["Edit File List" (org-edit-agenda-file-list) t]
21434 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21435 ["Remove Current File from List" org-remove-file t]
21436 ["Cycle through agenda files" org-cycle-agenda-files t]
21437 ["Occur in all agenda files" org-occur-in-agenda-files t]
21438 "--")
21439 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21441 ;;;; Documentation
21443 (defun org-require-autoloaded-modules ()
21444 (interactive)
21445 (mapc 'require
21446 '(org-agenda org-archive org-attach org-clock org-colview org-id
21447 org-table org-timer)))
21449 ;;;###autoload
21450 (defun org-reload (&optional uncompiled)
21451 "Reload all org lisp files.
21452 With prefix arg UNCOMPILED, load the uncompiled versions."
21453 (interactive "P")
21454 (require 'loadhist)
21455 (let* ((org-dir (org-find-library-dir "org"))
21456 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21457 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21458 (remove-re (mapconcat 'identity
21459 (mapcar (lambda (f) (concat "^" f "$"))
21460 (list (if (featurep 'xemacs)
21461 "org-colview"
21462 "org-colview-xemacs")
21463 "org" "org-loaddefs" "org-version"))
21464 "\\|"))
21465 (feats (delete-dups
21466 (mapcar 'file-name-sans-extension
21467 (mapcar 'file-name-nondirectory
21468 (delq nil
21469 (mapcar 'feature-file
21470 features))))))
21471 (lfeat (append
21472 (sort
21473 (setq feats
21474 (delq nil (mapcar
21475 (lambda (f)
21476 (if (and (string-match feature-re f)
21477 (not (string-match remove-re f)))
21478 f nil))
21479 feats)))
21480 'string-lessp)
21481 (list "org-version" "org")))
21482 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21483 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21484 load-uncore load-misses)
21485 (setq load-misses
21486 (delq 't
21487 (mapcar (lambda (f)
21488 (or (org-load-noerror-mustsuffix (concat org-dir f))
21489 (and (string= org-dir contrib-dir)
21490 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21491 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21492 (add-to-list 'load-uncore f 'append)
21495 lfeat)))
21496 (if load-uncore
21497 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21498 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21499 (if load-misses
21500 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21501 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21502 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21504 ;;;###autoload
21505 (defun org-customize ()
21506 "Call the customize function with org as argument."
21507 (interactive)
21508 (org-load-modules-maybe)
21509 (org-require-autoloaded-modules)
21510 (customize-browse 'org))
21512 (defun org-create-customize-menu ()
21513 "Create a full customization menu for Org-mode, insert it into the menu."
21514 (interactive)
21515 (org-load-modules-maybe)
21516 (org-require-autoloaded-modules)
21517 (if (fboundp 'customize-menu-create)
21518 (progn
21519 (easy-menu-change
21520 '("Org") "Customize"
21521 `(["Browse Org group" org-customize t]
21522 "--"
21523 ,(customize-menu-create 'org)
21524 ["Set" Custom-set t]
21525 ["Save" Custom-save t]
21526 ["Reset to Current" Custom-reset-current t]
21527 ["Reset to Saved" Custom-reset-saved t]
21528 ["Reset to Standard Settings" Custom-reset-standard t]))
21529 (message "\"Org\"-menu now contains full customization menu"))
21530 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21532 ;;;; Miscellaneous stuff
21534 ;;; Generally useful functions
21536 (defsubst org-get-at-eol (property n)
21537 "Get text property PROPERTY at the end of line less N characters."
21538 (get-text-property (- (point-at-eol) n) property))
21540 (defun org-find-text-property-in-string (prop s)
21541 "Return the first non-nil value of property PROP in string S."
21542 (or (get-text-property 0 prop s)
21543 (get-text-property (or (next-single-property-change 0 prop s) 0)
21544 prop s)))
21546 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21547 "Display the given MESSAGE as a warning."
21548 (if (fboundp 'display-warning)
21549 (display-warning 'org message
21550 (if (featurep 'xemacs) 'warning :warning))
21551 (let ((buf (get-buffer-create "*Org warnings*")))
21552 (with-current-buffer buf
21553 (goto-char (point-max))
21554 (insert "Warning (Org): " message)
21555 (unless (bolp)
21556 (newline)))
21557 (display-buffer buf)
21558 (sit-for 0))))
21560 (defun org-eval (form)
21561 "Eval FORM and return result."
21562 (condition-case error
21563 (eval form)
21564 (error (format "%%![Error: %s]" error))))
21566 (defun org-in-clocktable-p ()
21567 "Check if the cursor is in a clocktable."
21568 (let ((pos (point)) start)
21569 (save-excursion
21570 (end-of-line 1)
21571 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21572 (setq start (match-beginning 0))
21573 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21574 (>= (match-end 0) pos)
21575 start))))
21577 (defun org-in-verbatim-emphasis ()
21578 (save-match-data
21579 (and (org-in-regexp org-emph-re 2)
21580 (>= (point) (match-beginning 3))
21581 (<= (point) (match-end 4))
21582 (member (match-string 3) '("=" "~")))))
21584 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21585 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21586 (if (and marker (marker-buffer marker)
21587 (buffer-live-p (marker-buffer marker)))
21588 (progn
21589 (org-pop-to-buffer-same-window (marker-buffer marker))
21590 (if (or (> marker (point-max)) (< marker (point-min)))
21591 (widen))
21592 (goto-char marker)
21593 (org-show-context 'org-goto))
21594 (if bookmark
21595 (bookmark-jump bookmark)
21596 (error "Cannot find location"))))
21598 (defun org-quote-csv-field (s)
21599 "Quote field for inclusion in CSV material."
21600 (if (string-match "[\",]" s)
21601 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21604 (defun org-force-self-insert (N)
21605 "Needed to enforce self-insert under remapping."
21606 (interactive "p")
21607 (self-insert-command N))
21609 (defun org-string-width (s)
21610 "Compute width of string, ignoring invisible characters.
21611 This ignores character with invisibility property `org-link', and also
21612 characters with property `org-cwidth', because these will become invisible
21613 upon the next fontification round."
21614 (let (b l)
21615 (when (or (eq t buffer-invisibility-spec)
21616 (assq 'org-link buffer-invisibility-spec))
21617 (while (setq b (text-property-any 0 (length s)
21618 'invisible 'org-link s))
21619 (setq s (concat (substring s 0 b)
21620 (substring s (or (next-single-property-change
21621 b 'invisible s) (length s)))))))
21622 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21623 (setq s (concat (substring s 0 b)
21624 (substring s (or (next-single-property-change
21625 b 'org-cwidth s) (length s))))))
21626 (setq l (string-width s) b -1)
21627 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21628 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21631 (defun org-shorten-string (s maxlength)
21632 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21633 If the string is shorter or has length MAXLENGTH, just return the
21634 original string. If it is longer, the functions finds a space in the
21635 string, breaks this string off at that locations and adds three dots
21636 as ellipsis. Including the ellipsis, the string will not be longer
21637 than MAXLENGTH. If finding a good breaking point in the string does
21638 not work, the string is just chopped off in the middle of a word
21639 if necessary."
21640 (if (<= (length s) maxlength)
21642 (let* ((n (max (- maxlength 4) 1))
21643 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21644 (if (string-match re s)
21645 (concat (match-string 1 s) "...")
21646 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21648 (defun org-get-indentation (&optional line)
21649 "Get the indentation of the current line, interpreting tabs.
21650 When LINE is given, assume it represents a line and compute its indentation."
21651 (if line
21652 (if (string-match "^ *" (org-remove-tabs line))
21653 (match-end 0))
21654 (save-excursion
21655 (beginning-of-line 1)
21656 (skip-chars-forward " \t")
21657 (current-column))))
21659 (defun org-get-string-indentation (s)
21660 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21661 (let ((n -1) (i 0) (w tab-width) c)
21662 (catch 'exit
21663 (while (< (setq n (1+ n)) (length s))
21664 (setq c (aref s n))
21665 (cond ((= c ?\ ) (setq i (1+ i)))
21666 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21667 (t (throw 'exit t)))))
21670 (defun org-remove-tabs (s &optional width)
21671 "Replace tabulators in S with spaces.
21672 Assumes that s is a single line, starting in column 0."
21673 (setq width (or width tab-width))
21674 (while (string-match "\t" s)
21675 (setq s (replace-match
21676 (make-string
21677 (- (* width (/ (+ (match-beginning 0) width) width))
21678 (match-beginning 0)) ?\ )
21679 t t s)))
21682 (defun org-fix-indentation (line ind)
21683 "Fix indentation in LINE.
21684 IND is a cons cell with target and minimum indentation.
21685 If the current indentation in LINE is smaller than the minimum,
21686 leave it alone. If it is larger than ind, set it to the target."
21687 (let* ((l (org-remove-tabs line))
21688 (i (org-get-indentation l))
21689 (i1 (car ind)) (i2 (cdr ind)))
21690 (if (>= i i2) (setq l (substring line i2)))
21691 (if (> i1 0)
21692 (concat (make-string i1 ?\ ) l)
21693 l)))
21695 (defun org-remove-indentation (code &optional n)
21696 "Remove the maximum common indentation from the lines in CODE.
21697 N may optionally be the number of spaces to remove."
21698 (with-temp-buffer
21699 (insert code)
21700 (org-do-remove-indentation n)
21701 (buffer-string)))
21703 (defun org-do-remove-indentation (&optional n)
21704 "Remove the maximum common indentation from the buffer."
21705 (untabify (point-min) (point-max))
21706 (let ((min 10000) re)
21707 (if n
21708 (setq min n)
21709 (goto-char (point-min))
21710 (while (re-search-forward "^ *[^ \n]" nil t)
21711 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21712 (unless (or (= min 0) (= min 10000))
21713 (setq re (format "^ \\{%d\\}" min))
21714 (goto-char (point-min))
21715 (while (re-search-forward re nil t)
21716 (replace-match "")
21717 (end-of-line 1))
21718 min)))
21720 (defun org-fill-template (template alist)
21721 "Find each %key of ALIST in TEMPLATE and replace it."
21722 (let ((case-fold-search nil)
21723 entry key value)
21724 (setq alist (sort (copy-sequence alist)
21725 (lambda (a b) (< (length (car a)) (length (car b))))))
21726 (while (setq entry (pop alist))
21727 (setq template
21728 (replace-regexp-in-string
21729 (concat "%" (regexp-quote (car entry)))
21730 (or (cdr entry) "") template t t)))
21731 template))
21733 (defun org-base-buffer (buffer)
21734 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21735 (if (not buffer)
21736 buffer
21737 (or (buffer-base-buffer buffer)
21738 buffer)))
21740 (defun org-wrap (string &optional width lines)
21741 "Wrap string to either a number of lines, or a width in characters.
21742 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21743 that costs. If there is a word longer than WIDTH, the text is actually
21744 wrapped to the length of that word.
21745 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21746 many lines, whatever width that takes.
21747 The return value is a list of lines, without newlines at the end."
21748 (let* ((words (org-split-string string "[ \t\n]+"))
21749 (maxword (apply 'max (mapcar 'org-string-width words)))
21750 w ll)
21751 (cond (width
21752 (org-do-wrap words (max maxword width)))
21753 (lines
21754 (setq w maxword)
21755 (setq ll (org-do-wrap words maxword))
21756 (if (<= (length ll) lines)
21758 (setq ll words)
21759 (while (> (length ll) lines)
21760 (setq w (1+ w))
21761 (setq ll (org-do-wrap words w)))
21762 ll))
21763 (t (error "Cannot wrap this")))))
21765 (defun org-do-wrap (words width)
21766 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21767 (let (lines line)
21768 (while words
21769 (setq line (pop words))
21770 (while (and words (< (+ (length line) (length (car words))) width))
21771 (setq line (concat line " " (pop words))))
21772 (setq lines (push line lines)))
21773 (nreverse lines)))
21775 (defun org-split-string (string &optional separators)
21776 "Splits STRING into substrings at SEPARATORS.
21777 No empty strings are returned if there are matches at the beginning
21778 and end of string."
21779 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21780 (start 0)
21781 notfirst
21782 (list nil))
21783 (while (and (string-match rexp string
21784 (if (and notfirst
21785 (= start (match-beginning 0))
21786 (< start (length string)))
21787 (1+ start) start))
21788 (< (match-beginning 0) (length string)))
21789 (setq notfirst t)
21790 (or (eq (match-beginning 0) 0)
21791 (and (eq (match-beginning 0) (match-end 0))
21792 (eq (match-beginning 0) start))
21793 (setq list
21794 (cons (substring string start (match-beginning 0))
21795 list)))
21796 (setq start (match-end 0)))
21797 (or (eq start (length string))
21798 (setq list
21799 (cons (substring string start)
21800 list)))
21801 (nreverse list)))
21803 (defun org-quote-vert (s)
21804 "Replace \"|\" with \"\\vert\"."
21805 (while (string-match "|" s)
21806 (setq s (replace-match "\\vert" t t s)))
21809 (defun org-uuidgen-p (s)
21810 "Is S an ID created by UUIDGEN?"
21811 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21813 (defun org-in-src-block-p (&optional inside)
21814 "Whether point is in a code source block.
21815 When INSIDE is non-nil, don't consider we are within a src block
21816 when point is at #+BEGIN_SRC or #+END_SRC."
21817 (let ((case-fold-search t) ov)
21818 (or (and (setq ov (overlays-at (point)))
21819 (memq 'org-block-background
21820 (overlay-properties (car ov))))
21821 (and (not inside)
21822 (save-match-data
21823 (save-excursion
21824 (beginning-of-line)
21825 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21827 (defun org-context ()
21828 "Return a list of contexts of the current cursor position.
21829 If several contexts apply, all are returned.
21830 Each context entry is a list with a symbol naming the context, and
21831 two positions indicating start and end of the context. Possible
21832 contexts are:
21834 :headline anywhere in a headline
21835 :headline-stars on the leading stars in a headline
21836 :todo-keyword on a TODO keyword (including DONE) in a headline
21837 :tags on the TAGS in a headline
21838 :priority on the priority cookie in a headline
21839 :item on the first line of a plain list item
21840 :item-bullet on the bullet/number of a plain list item
21841 :checkbox on the checkbox in a plain list item
21842 :table in an org-mode table
21843 :table-special on a special filed in a table
21844 :table-table in a table.el table
21845 :clocktable in a clocktable
21846 :src-block in a source block
21847 :link on a hyperlink
21848 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
21849 :target on a <<target>>
21850 :radio-target on a <<<radio-target>>>
21851 :latex-fragment on a LaTeX fragment
21852 :latex-preview on a LaTeX fragment with overlaid preview image
21854 This function expects the position to be visible because it uses font-lock
21855 faces as a help to recognize the following contexts: :table-special, :link,
21856 and :keyword."
21857 (let* ((f (get-text-property (point) 'face))
21858 (faces (if (listp f) f (list f)))
21859 (case-fold-search t)
21860 (p (point)) clist o)
21861 ;; First the large context
21862 (cond
21863 ((org-at-heading-p t)
21864 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21865 (when (progn
21866 (beginning-of-line 1)
21867 (looking-at org-todo-line-tags-regexp))
21868 (push (org-point-in-group p 1 :headline-stars) clist)
21869 (push (org-point-in-group p 2 :todo-keyword) clist)
21870 (push (org-point-in-group p 4 :tags) clist))
21871 (goto-char p)
21872 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21873 (if (looking-at "\\[#[A-Z0-9]\\]")
21874 (push (org-point-in-group p 0 :priority) clist)))
21876 ((org-at-item-p)
21877 (push (org-point-in-group p 2 :item-bullet) clist)
21878 (push (list :item (point-at-bol)
21879 (save-excursion (org-end-of-item) (point)))
21880 clist)
21881 (and (org-at-item-checkbox-p)
21882 (push (org-point-in-group p 0 :checkbox) clist)))
21884 ((org-at-table-p)
21885 (push (list :table (org-table-begin) (org-table-end)) clist)
21886 (if (memq 'org-formula faces)
21887 (push (list :table-special
21888 (previous-single-property-change p 'face)
21889 (next-single-property-change p 'face)) clist)))
21890 ((org-at-table-p 'any)
21891 (push (list :table-table) clist)))
21892 (goto-char p)
21894 (let ((case-fold-search t))
21895 ;; New the "medium" contexts: clocktables, source blocks
21896 (cond ((org-in-clocktable-p)
21897 (push (list :clocktable
21898 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
21899 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
21900 (match-beginning 1))
21901 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
21902 (match-end 0))) clist))
21903 ((org-in-src-block-p)
21904 (push (list :src-block
21905 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
21906 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
21907 (match-beginning 1))
21908 (and (search-forward "#+END_SRC" nil t)
21909 (match-beginning 0))) clist))))
21910 (goto-char p)
21912 ;; Now the small context
21913 (cond
21914 ((org-at-timestamp-p)
21915 (push (org-point-in-group p 0 :timestamp) clist))
21916 ((memq 'org-link faces)
21917 (push (list :link
21918 (previous-single-property-change p 'face)
21919 (next-single-property-change p 'face)) clist))
21920 ((memq 'org-special-keyword faces)
21921 (push (list :keyword
21922 (previous-single-property-change p 'face)
21923 (next-single-property-change p 'face)) clist))
21924 ((org-at-target-p)
21925 (push (org-point-in-group p 0 :target) clist)
21926 (goto-char (1- (match-beginning 0)))
21927 (if (looking-at org-radio-target-regexp)
21928 (push (org-point-in-group p 0 :radio-target) clist))
21929 (goto-char p))
21930 ((setq o (car (delq nil
21931 (mapcar
21932 (lambda (x)
21933 (if (memq x org-latex-fragment-image-overlays) x))
21934 (overlays-at (point))))))
21935 (push (list :latex-fragment
21936 (overlay-start o) (overlay-end o)) clist)
21937 (push (list :latex-preview
21938 (overlay-start o) (overlay-end o)) clist))
21939 ((org-inside-LaTeX-fragment-p)
21940 ;; FIXME: positions wrong.
21941 (push (list :latex-fragment (point) (point)) clist)))
21943 (setq clist (nreverse (delq nil clist)))
21944 clist))
21946 ;; FIXME: Compare with at-regexp-p Do we need both?
21947 (defun org-in-regexp (re &optional nlines visually)
21948 "Check if point is inside a match of regexp.
21949 Normally only the current line is checked, but you can include NLINES extra
21950 lines both before and after point into the search.
21951 If VISUALLY is set, require that the cursor is not after the match but
21952 really on, so that the block visually is on the match."
21953 (catch 'exit
21954 (let ((pos (point))
21955 (eol (point-at-eol (+ 1 (or nlines 0))))
21956 (inc (if visually 1 0)))
21957 (save-excursion
21958 (beginning-of-line (- 1 (or nlines 0)))
21959 (while (re-search-forward re eol t)
21960 (if (and (<= (match-beginning 0) pos)
21961 (>= (+ inc (match-end 0)) pos))
21962 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21964 (defun org-at-regexp-p (regexp)
21965 "Is point inside a match of REGEXP in the current line?"
21966 (catch 'exit
21967 (save-excursion
21968 (let ((pos (point)) (end (point-at-eol)))
21969 (beginning-of-line 1)
21970 (while (re-search-forward regexp end t)
21971 (if (and (<= (match-beginning 0) pos)
21972 (>= (match-end 0) pos))
21973 (throw 'exit t)))
21974 nil))))
21976 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21977 "Non-nil when point is between matches of START-RE and END-RE.
21979 Also return a non-nil value when point is on one of the matches.
21981 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21982 buffer positions. Default values are the positions of headlines
21983 surrounding the point.
21985 The functions returns a cons cell whose car (resp. cdr) is the
21986 position before START-RE (resp. after END-RE)."
21987 (save-match-data
21988 (let ((pos (point))
21989 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21990 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21991 beg end)
21992 (save-excursion
21993 ;; Point is on a block when on START-RE or if START-RE can be
21994 ;; found before it...
21995 (and (or (org-at-regexp-p start-re)
21996 (re-search-backward start-re limit-up t))
21997 (setq beg (match-beginning 0))
21998 ;; ... and END-RE after it...
21999 (goto-char (match-end 0))
22000 (re-search-forward end-re limit-down t)
22001 (> (setq end (match-end 0)) pos)
22002 ;; ... without another START-RE in-between.
22003 (goto-char (match-beginning 0))
22004 (not (re-search-backward start-re (1+ beg) t))
22005 ;; Return value.
22006 (cons beg end))))))
22008 (defun org-in-block-p (names)
22009 "Non-nil when point belongs to a block whose name belongs to NAMES.
22011 NAMES is a list of strings containing names of blocks.
22013 Return first block name matched, or nil. Beware that in case of
22014 nested blocks, the returned name may not belong to the closest
22015 block from point."
22016 (save-match-data
22017 (catch 'exit
22018 (let ((case-fold-search t)
22019 (lim-up (save-excursion (outline-previous-heading)))
22020 (lim-down (save-excursion (outline-next-heading))))
22021 (mapc (lambda (name)
22022 (let ((n (regexp-quote name)))
22023 (when (org-between-regexps-p
22024 (concat "^[ \t]*#\\+begin_" n)
22025 (concat "^[ \t]*#\\+end_" n)
22026 lim-up lim-down)
22027 (throw 'exit n))))
22028 names))
22029 nil)))
22031 (defun org-in-drawer-p ()
22032 "Non-nil if point is within a drawer.
22033 If point is within a drawer, return it, as parsed data."
22034 (let ((element (save-match-data (org-element-at-point))))
22035 (while (and element (not (memq (org-element-type element)
22036 '(drawer property-drawer))))
22037 (setq element (org-element-property :parent element)))
22038 element))
22040 (defun org-occur-in-agenda-files (regexp &optional nlines)
22041 "Call `multi-occur' with buffers for all agenda files."
22042 (interactive "sOrg-files matching: \np")
22043 (let* ((files (org-agenda-files))
22044 (tnames (mapcar 'file-truename files))
22045 (extra org-agenda-text-search-extra-files)
22047 (when (eq (car extra) 'agenda-archives)
22048 (setq extra (cdr extra))
22049 (setq files (org-add-archive-files files)))
22050 (while (setq f (pop extra))
22051 (unless (member (file-truename f) tnames)
22052 (add-to-list 'files f 'append)
22053 (add-to-list 'tnames (file-truename f) 'append)))
22054 (multi-occur
22055 (mapcar (lambda (x)
22056 (with-current-buffer
22057 (or (get-file-buffer x) (find-file-noselect x))
22058 (widen)
22059 (current-buffer)))
22060 files)
22061 regexp)))
22063 (if (boundp 'occur-mode-find-occurrence-hook)
22064 ;; Emacs 23
22065 (add-hook 'occur-mode-find-occurrence-hook
22066 (lambda ()
22067 (when (derived-mode-p 'org-mode)
22068 (org-reveal))))
22069 ;; Emacs 22
22070 (defadvice occur-mode-goto-occurrence
22071 (after org-occur-reveal activate)
22072 (and (derived-mode-p 'org-mode) (org-reveal)))
22073 (defadvice occur-mode-goto-occurrence-other-window
22074 (after org-occur-reveal activate)
22075 (and (derived-mode-p 'org-mode) (org-reveal)))
22076 (defadvice occur-mode-display-occurrence
22077 (after org-occur-reveal activate)
22078 (when (derived-mode-p 'org-mode)
22079 (let ((pos (occur-mode-find-occurrence)))
22080 (with-current-buffer (marker-buffer pos)
22081 (save-excursion
22082 (goto-char pos)
22083 (org-reveal)))))))
22085 (defun org-occur-link-in-agenda-files ()
22086 "Create a link and search for it in the agendas.
22087 The link is not stored in `org-stored-links', it is just created
22088 for the search purpose."
22089 (interactive)
22090 (let ((link (condition-case nil
22091 (org-store-link nil)
22092 (error "Unable to create a link to here"))))
22093 (org-occur-in-agenda-files (regexp-quote link))))
22095 (defun org-reverse-string (string)
22096 "Return the reverse of STRING."
22097 (apply 'string (reverse (string-to-list string))))
22099 ;; defsubst org-uniquify must be defined before first use
22101 (defun org-uniquify-alist (alist)
22102 "Merge elements of ALIST with the same key.
22104 For example, in this alist:
22106 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
22107 => '((a 1 3) (b 2))
22109 merge (a 1) and (a 3) into (a 1 3).
22111 The function returns the new ALIST."
22112 (let (rtn)
22113 (mapc
22114 (lambda (e)
22115 (let (n)
22116 (if (not (assoc (car e) rtn))
22117 (push e rtn)
22118 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22119 (setq rtn (assq-delete-all (car e) rtn))
22120 (push n rtn))))
22121 alist)
22122 rtn))
22124 (defun org-delete-all (elts list)
22125 "Remove all elements in ELTS from LIST."
22126 (while elts
22127 (setq list (delete (pop elts) list)))
22128 list)
22130 (defun org-count (cl-item cl-seq)
22131 "Count the number of occurrences of ITEM in SEQ.
22132 Taken from `count' in cl-seq.el with all keyword arguments removed."
22133 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
22134 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
22135 (while (< cl-start cl-end)
22136 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
22137 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
22138 (setq cl-start (1+ cl-start)))
22139 cl-count))
22141 (defun org-remove-if (predicate seq)
22142 "Remove everything from SEQ that fulfills PREDICATE."
22143 (let (res e)
22144 (while seq
22145 (setq e (pop seq))
22146 (if (not (funcall predicate e)) (push e res)))
22147 (nreverse res)))
22149 (defun org-remove-if-not (predicate seq)
22150 "Remove everything from SEQ that does not fulfill PREDICATE."
22151 (let (res e)
22152 (while seq
22153 (setq e (pop seq))
22154 (if (funcall predicate e) (push e res)))
22155 (nreverse res)))
22157 (defun org-reduce (cl-func cl-seq &rest cl-keys)
22158 "Reduce two-argument FUNCTION across SEQ.
22159 Taken from `reduce' in cl-seq.el with all keyword arguments but
22160 \":initial-value\" removed."
22161 (let ((cl-accum (cond ((memq :initial-value cl-keys)
22162 (cadr (memq :initial-value cl-keys)))
22163 (cl-seq (pop cl-seq))
22164 (t (funcall cl-func)))))
22165 (while cl-seq
22166 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
22167 cl-accum))
22169 (defun org-every (pred seq)
22170 "Return true if PREDICATE is true of every element of SEQ.
22171 Adapted from `every' in cl.el."
22172 (catch 'org-every
22173 (mapc (lambda (e) (unless (funcall pred e) (throw 'org-every nil))) seq)
22176 (defun org-some (pred seq)
22177 "Return true if PREDICATE is true of any element of SEQ.
22178 Adapted from `some' in cl.el."
22179 (catch 'org-some
22180 (mapc (lambda (e) (when (funcall pred e) (throw 'org-some t))) seq)
22181 nil))
22183 (defun org-back-over-empty-lines ()
22184 "Move backwards over whitespace, to the beginning of the first empty line.
22185 Returns the number of empty lines passed."
22186 (let ((pos (point)))
22187 (if (cdr (assoc 'heading org-blank-before-new-entry))
22188 (skip-chars-backward " \t\n\r")
22189 (unless (eobp)
22190 (forward-line -1)))
22191 (beginning-of-line 2)
22192 (goto-char (min (point) pos))
22193 (count-lines (point) pos)))
22195 (defun org-skip-whitespace ()
22196 (skip-chars-forward " \t\n\r"))
22198 (defun org-point-in-group (point group &optional context)
22199 "Check if POINT is in match-group GROUP.
22200 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22201 match. If the match group does not exist or point is not inside it,
22202 return nil."
22203 (and (match-beginning group)
22204 (>= point (match-beginning group))
22205 (<= point (match-end group))
22206 (if context
22207 (list context (match-beginning group) (match-end group))
22208 t)))
22210 (defun org-switch-to-buffer-other-window (&rest args)
22211 "Switch to buffer in a second window on the current frame.
22212 In particular, do not allow pop-up frames.
22213 Returns the newly created buffer."
22214 (org-no-popups
22215 (apply 'switch-to-buffer-other-window args)))
22217 (defun org-combine-plists (&rest plists)
22218 "Create a single property list from all plists in PLISTS.
22219 The process starts by copying the first list, and then setting properties
22220 from the other lists. Settings in the last list are the most significant
22221 ones and overrule settings in the other lists."
22222 (let ((rtn (copy-sequence (pop plists)))
22223 p v ls)
22224 (while plists
22225 (setq ls (pop plists))
22226 (while ls
22227 (setq p (pop ls) v (pop ls))
22228 (setq rtn (plist-put rtn p v))))
22229 rtn))
22231 (defun org-replace-escapes (string table)
22232 "Replace %-escapes in STRING with values in TABLE.
22233 TABLE is an association list with keys like \"%a\" and string values.
22234 The sequences in STRING may contain normal field width and padding information,
22235 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22236 so values can contain further %-escapes if they are define later in TABLE."
22237 (let ((tbl (copy-alist table))
22238 (case-fold-search nil)
22239 (pchg 0)
22240 e re rpl)
22241 (while (setq e (pop tbl))
22242 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22243 (when (and (cdr e) (string-match re (cdr e)))
22244 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22245 (safe "SREF"))
22246 (add-text-properties 0 3 (list 'sref sref) safe)
22247 (setcdr e (replace-match safe t t (cdr e)))))
22248 (while (string-match re string)
22249 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22250 (cdr e)))
22251 (setq string (replace-match rpl t t string))))
22252 (while (setq pchg (next-property-change pchg string))
22253 (let ((sref (get-text-property pchg 'sref string)))
22254 (when (and sref (string-match "SREF" string pchg))
22255 (setq string (replace-match sref t t string)))))
22256 string))
22258 (defun org-sublist (list start end)
22259 "Return a section of LIST, from START to END.
22260 Counting starts at 1."
22261 (let (rtn (c start))
22262 (setq list (nthcdr (1- start) list))
22263 (while (and list (<= c end))
22264 (push (pop list) rtn)
22265 (setq c (1+ c)))
22266 (nreverse rtn)))
22268 (defun org-find-base-buffer-visiting (file)
22269 "Like `find-buffer-visiting' but always return the base buffer and
22270 not an indirect buffer."
22271 (let ((buf (or (get-file-buffer file)
22272 (find-buffer-visiting file))))
22273 (if buf
22274 (or (buffer-base-buffer buf) buf)
22275 nil)))
22277 (defun org-image-file-name-regexp (&optional extensions)
22278 "Return regexp matching the file names of images.
22279 If EXTENSIONS is given, only match these."
22280 (if (and (not extensions) (fboundp 'image-file-name-regexp))
22281 (image-file-name-regexp)
22282 (let ((image-file-name-extensions
22283 (or extensions
22284 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
22285 "xbm" "xpm" "pbm" "pgm" "ppm"))))
22286 (concat "\\."
22287 (regexp-opt (nconc (mapcar 'upcase
22288 image-file-name-extensions)
22289 image-file-name-extensions)
22291 "\\'"))))
22293 (defun org-file-image-p (file &optional extensions)
22294 "Return non-nil if FILE is an image."
22295 (save-match-data
22296 (string-match (org-image-file-name-regexp extensions) file)))
22298 (defun org-get-cursor-date (&optional with-time)
22299 "Return the date at cursor in as a time.
22300 This works in the calendar and in the agenda, anywhere else it just
22301 returns the current time.
22302 If WITH-TIME is non-nil, returns the time of the event at point (in
22303 the agenda) or the current time of the day."
22304 (let (date day defd tp tm hod mod)
22305 (when with-time
22306 (setq tp (get-text-property (point) 'time))
22307 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22308 (setq hod (string-to-number (match-string 1 tp))
22309 mod (string-to-number (match-string 2 tp))))
22310 (or tp (setq hod (nth 2 (decode-time (current-time)))
22311 mod (nth 1 (decode-time (current-time))))))
22312 (cond
22313 ((eq major-mode 'calendar-mode)
22314 (setq date (calendar-cursor-to-date)
22315 defd (encode-time 0 (or mod 0) (or hod 0)
22316 (nth 1 date) (nth 0 date) (nth 2 date))))
22317 ((eq major-mode 'org-agenda-mode)
22318 (setq day (get-text-property (point) 'day))
22319 (if day
22320 (setq date (calendar-gregorian-from-absolute day)
22321 defd (encode-time 0 (or mod 0) (or hod 0)
22322 (nth 1 date) (nth 0 date) (nth 2 date))))))
22323 (or defd (current-time))))
22325 (defun org-mark-subtree (&optional up)
22326 "Mark the current subtree.
22327 This puts point at the start of the current subtree, and mark at
22328 the end. If a numeric prefix UP is given, move up into the
22329 hierarchy of headlines by UP levels before marking the subtree."
22330 (interactive "P")
22331 (org-with-limited-levels
22332 (cond ((org-at-heading-p) (beginning-of-line))
22333 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22334 (t (outline-previous-visible-heading 1))))
22335 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
22336 (if (org-called-interactively-p 'any)
22337 (call-interactively 'org-mark-element)
22338 (org-mark-element)))
22341 ;;; Indentation
22343 (defun org--get-expected-indentation (element contentsp)
22344 "Expected indentation column for current line, according to ELEMENT.
22345 ELEMENT is an element containing point. CONTENTSP is non-nil
22346 when indentation is to be computed according to contents of
22347 ELEMENT."
22348 (let ((type (org-element-type element))
22349 (start (org-element-property :begin element)))
22350 (org-with-wide-buffer
22351 (cond
22352 (contentsp
22353 (case type
22354 (footnote-definition 0)
22355 ((headline inlinetask nil)
22356 (if (not org-adapt-indentation) 0
22357 (let ((level (org-current-level)))
22358 (if level (1+ level) 0))))
22359 ((item plain list)
22360 (org-list-item-body-column
22361 (or (org-element-property :post-affiliated element) start)))
22362 (otherwise
22363 (goto-char start)
22364 (org-get-indentation))))
22365 ((memq type '(headline inlinetask nil))
22366 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
22367 (org--get-expected-indentation element t)
22369 ((eq type 'footnote-definition) 0)
22370 ;; First paragraph of a footnote definition or an item.
22371 ;; Indent like parent.
22372 ((< (line-beginning-position) start)
22373 (org--get-expected-indentation
22374 (org-element-property :parent element) t))
22375 ;; At first line: indent according to previous sibling, if any,
22376 ;; ignoring footnote definitions and inline tasks, or parent's
22377 ;; contents.
22378 ((= (line-beginning-position) start)
22379 (catch 'exit
22380 (while t
22381 (if (= (point-min) start) (throw 'exit 0)
22382 (goto-char (1- start))
22383 (let ((previous (org-element-at-point)))
22384 (while (let ((parent (org-element-property :parent previous)))
22385 (and parent
22386 (setq previous parent)
22387 (<= (org-element-property :end parent) start))))
22388 (cond ((or (not previous)
22389 (> (org-element-property :end previous) start))
22390 (throw 'exit (org--get-expected-indentation previous t)))
22391 ((memq (org-element-type previous)
22392 '(footnote-definition inlinetask))
22393 (setq start (org-element-property :begin previous)))
22394 (t (goto-char (org-element-property :begin previous))
22395 (throw 'exit (org-get-indentation)))))))))
22396 ;; Otherwise, move to the first non-blank line above.
22398 (beginning-of-line)
22399 (let ((pos (point)))
22400 (skip-chars-backward " \r\t\n")
22401 (cond
22402 ;; Two blank lines end a footnote definition or a plain
22403 ;; list. When we indent an empty line after them, the
22404 ;; containing list or footnote definition is over, so it
22405 ;; qualifies as a previous sibling. Therefore, we indent
22406 ;; like its first line.
22407 ((and (memq type '(footnote-definition plain-list))
22408 (> (count-lines (point) pos) 2))
22409 (goto-char start)
22410 (org-get-indentation))
22411 ;; Line above is the first one of a paragraph at the
22412 ;; beginning of an item or a footnote definition. Indent
22413 ;; like parent.
22414 ((< (line-beginning-position) start)
22415 (org--get-expected-indentation
22416 (org-element-property :parent element) t))
22417 ;; POS is after contents in a greater element. Indent like
22418 ;; the beginning of the element.
22420 ;; As a special case, if point is at the end of a footnote
22421 ;; definition or an item, indent like the very last element
22422 ;; within.
22423 ((let ((cend (org-element-property :contents-end element)))
22424 (and cend (<= cend pos)))
22425 (if (memq type '(footnote-definition item plain-list))
22426 (org--get-expected-indentation (org-element-at-point) nil)
22427 (goto-char start)
22428 (org-get-indentation)))
22429 ;; In any other case, indent like the current line.
22430 (t (org-get-indentation)))))))))
22432 (defun org--align-node-property ()
22433 "Align node property at point.
22434 Alignment is done according to `org-property-format', which see."
22435 (when (save-excursion
22436 (beginning-of-line)
22437 (looking-at org-property-re))
22438 (replace-match
22439 (concat (match-string 4)
22440 (format org-property-format (match-string 1) (match-string 3)))
22441 t t)))
22443 (defun org-indent-line ()
22444 "Indent line depending on context.
22446 Indentation is done according to the following rules:
22448 - Footnote definitions, headlines and inline tasks have to
22449 start at column 0.
22451 - On the very first line of an element, consider, in order, the
22452 next rules until one matches:
22454 1. If there's a sibling element before, ignoring footnote
22455 definitions and inline tasks, indent like its first line.
22457 2. If element has a parent, indent like its contents. More
22458 precisely, if parent is an item, indent after the
22459 description part, if any, or the bullet (see
22460 ``org-list-description-max-indent'). Else, indent like
22461 parent's first line.
22463 3. Otherwise, indent relatively to current level, if
22464 `org-adapt-indentation' is non-nil, or to left margin.
22466 - On a blank line at the end of a plain list, an item, or
22467 a footnote definition, indent like the very last element
22468 within.
22470 - In the code part of a source block, use language major mode
22471 to indent current line if `org-src-tab-acts-natively' is
22472 non-nil. If it is nil, do nothing.
22474 - Otherwise, indent like the first non-blank line above.
22476 The function doesn't indent an item as it could break the whole
22477 list structure. Instead, use \\<org-mode-map>\\[org-shiftmetaleft] or \
22478 \\[org-shiftmetaright].
22480 Also align node properties according to `org-property-format'."
22481 (interactive)
22482 (cond
22483 (orgstruct-is-++
22484 (let ((indent-line-function
22485 (cadadr (assq 'indent-line-function org-fb-vars))))
22486 (indent-according-to-mode)))
22487 ((org-at-heading-p) 'noindent)
22489 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22490 (type (org-element-type element)))
22491 (cond ((and (memq type '(plain-list item))
22492 (= (line-beginning-position)
22493 (or (org-element-property :post-affiliated element)
22494 (org-element-property :begin element))))
22495 'noindent)
22496 ((and (eq type 'src-block)
22497 org-src-tab-acts-natively
22498 (> (line-beginning-position)
22499 (org-element-property :post-affiliated element))
22500 (< (line-beginning-position)
22501 (org-with-wide-buffer
22502 (goto-char (org-element-property :end element))
22503 (skip-chars-backward " \r\t\n")
22504 (line-beginning-position))))
22505 (let ((org-src-strip-leading-and-trailing-blank-lines nil))
22506 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB"))))
22508 (let ((column (org--get-expected-indentation element nil)))
22509 ;; Preserve current column.
22510 (if (<= (current-column) (current-indentation))
22511 (org-indent-line-to column)
22512 (save-excursion (org-indent-line-to column))))
22513 ;; Align node property. Also preserve current column.
22514 (when (eq type 'node-property)
22515 (let ((column (current-column)))
22516 (org--align-node-property)
22517 (org-move-to-column column)))))))))
22519 (defun org-indent-region (start end)
22520 "Indent each non-blank line in the region.
22521 Called from a program, START and END specify the region to
22522 indent. The function will not indent contents of example blocks,
22523 verse blocks and export blocks as leading white spaces are
22524 assumed to be significant there."
22525 (interactive "r")
22526 (save-excursion
22527 (goto-char start)
22528 (beginning-of-line)
22529 (let ((indent-to
22530 (lambda (ind pos)
22531 ;; Set IND as indentation for all lines between point and
22532 ;; POS or END, whichever comes first. Blank lines are
22533 ;; ignored. Leave point after POS once done.
22534 (let ((limit (copy-marker (min end pos))))
22535 (while (< (point) limit)
22536 (unless (org-looking-at-p "[ \t]*$") (org-indent-line-to ind))
22537 (forward-line))
22538 (set-marker limit nil))))
22539 (end (copy-marker end)))
22540 (while (< (point) end)
22541 (if (or (org-looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22542 (let* ((element (org-element-at-point))
22543 (type (org-element-type element))
22544 (element-end (copy-marker (org-element-property :end element)))
22545 (ind (org--get-expected-indentation element nil)))
22546 (if (or (memq type '(paragraph table table-row))
22547 (not (or (org-element-property :contents-begin element)
22548 (memq type
22549 '(example-block export-block src-block)))))
22550 ;; Elements here are indented as a single block. Also
22551 ;; align node properties.
22552 (progn
22553 (when (eq type 'node-property)
22554 (org--align-node-property)
22555 (beginning-of-line))
22556 (funcall indent-to ind element-end))
22557 ;; Elements in this category consist of three parts:
22558 ;; before the contents, the contents, and after the
22559 ;; contents. The contents are treated specially,
22560 ;; according to the element type, or not indented at
22561 ;; all. Other parts are indented as a single block.
22562 (let* ((post (copy-marker
22563 (or (org-element-property :post-affiliated element)
22564 (org-element-property :begin element))))
22565 (cbeg
22566 (copy-marker
22567 (cond
22568 ((not (org-element-property :contents-begin element))
22569 ;; Fake contents for source blocks.
22570 (org-with-wide-buffer
22571 (goto-char post)
22572 (forward-line)
22573 (point)))
22574 ((memq type '(footnote-definition item plain-list))
22575 ;; Contents in these elements could start on
22576 ;; the same line as the beginning of the
22577 ;; element. Make sure we start indenting
22578 ;; from the second line.
22579 (org-with-wide-buffer
22580 (goto-char post)
22581 (forward-line)
22582 (point)))
22583 (t (org-element-property :contents-begin element)))))
22584 (cend (copy-marker
22585 (or (org-element-property :contents-end element)
22586 ;; Fake contents for source blocks.
22587 (org-with-wide-buffer
22588 (goto-char element-end)
22589 (skip-chars-backward " \r\t\n")
22590 (line-beginning-position))))))
22591 (funcall indent-to ind cbeg)
22592 (when (< (point) end)
22593 (case type
22594 ((example-block export-block verse-block))
22595 (src-block
22596 ;; In a source block, indent source code according
22597 ;; to language major mode, but only if
22598 ;; `org-src-tab-acts-natively' is non-nil.
22599 (when (and (< (point) end) org-src-tab-acts-natively)
22600 (ignore-errors
22601 (let (org-src-strip-leading-and-trailing-blank-lines
22602 ;; Region boundaries in edit buffer.
22603 (start (1+ (- (point) cbeg)))
22604 (end (- (min cend end) cbeg)))
22605 (org-babel-do-in-edit-buffer
22606 (indent-region start end))))))
22607 (t (org-indent-region (point) (min cend end))))
22608 (goto-char (min cend end))
22609 (when (< (point) end) (funcall indent-to ind element-end)))
22610 (set-marker post nil)
22611 (set-marker cbeg nil)
22612 (set-marker cend nil)))
22613 (set-marker element-end nil))))
22614 (set-marker end nil))))
22616 (defun org-indent-drawer ()
22617 "Indent the drawer at point."
22618 (interactive)
22619 (unless (save-excursion
22620 (beginning-of-line)
22621 (org-looking-at-p org-drawer-regexp))
22622 (user-error "Not at a drawer"))
22623 (let ((element (org-element-at-point)))
22624 (unless (memq (org-element-type element) '(drawer property-drawer))
22625 (user-error "Not at a drawer"))
22626 (org-with-wide-buffer
22627 (org-indent-region (org-element-property :begin element)
22628 (org-element-property :end element))))
22629 (message "Drawer at point indented"))
22631 (defun org-indent-block ()
22632 "Indent the block at point."
22633 (interactive)
22634 (unless (save-excursion
22635 (beginning-of-line)
22636 (let ((case-fold-search t))
22637 (org-looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
22638 (user-error "Not at a block"))
22639 (let ((element (org-element-at-point)))
22640 (unless (memq (org-element-type element)
22641 '(comment-block center-block example-block export-block
22642 quote-block special-block src-block
22643 verse-block))
22644 (user-error "Not at a block"))
22645 (org-with-wide-buffer
22646 (org-indent-region (org-element-property :begin element)
22647 (org-element-property :end element))))
22648 (message "Block at point indented"))
22651 ;;; Filling
22653 ;; We use our own fill-paragraph and auto-fill functions.
22655 ;; `org-fill-paragraph' relies on adaptive filling and context
22656 ;; checking. Appropriate `fill-prefix' is computed with
22657 ;; `org-adaptive-fill-function'.
22659 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22660 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22661 ;; `org-adaptive-fill-function' value. Internally,
22662 ;; `org-comment-line-break-function' breaks the line.
22664 ;; `org-setup-filling' installs filling and auto-filling related
22665 ;; variables during `org-mode' initialization.
22667 (defvar org-element-paragraph-separate) ; org-element.el
22668 (defun org-setup-filling ()
22669 (require 'org-element)
22670 ;; Prevent auto-fill from inserting unwanted new items.
22671 (when (boundp 'fill-nobreak-predicate)
22672 (org-set-local
22673 'fill-nobreak-predicate
22674 (org-uniquify
22675 (append fill-nobreak-predicate
22676 '(org-fill-line-break-nobreak-p
22677 org-fill-paragraph-with-timestamp-nobreak-p)))))
22678 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22679 (org-set-local 'paragraph-start paragraph-ending)
22680 (org-set-local 'paragraph-separate paragraph-ending))
22681 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22682 (org-set-local 'auto-fill-inhibit-regexp nil)
22683 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22684 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22685 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22687 (defun org-fill-line-break-nobreak-p ()
22688 "Non-nil when a new line at point would create an Org line break."
22689 (save-excursion
22690 (skip-chars-backward "[ \t]")
22691 (skip-chars-backward "\\\\")
22692 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22694 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22695 "Non-nil when a new line at point would split a timestamp."
22696 (and (org-at-timestamp-p t)
22697 (not (looking-at org-ts-regexp-both))))
22699 (declare-function message-in-body-p "message" ())
22700 (defvar orgtbl-line-start-regexp) ; From org-table.el
22701 (defun org-adaptive-fill-function ()
22702 "Compute a fill prefix for the current line.
22703 Return fill prefix, as a string, or nil if current line isn't
22704 meant to be filled. For convenience, if `adaptive-fill-regexp'
22705 matches in paragraphs or comments, use it."
22706 (catch 'exit
22707 (when (derived-mode-p 'message-mode)
22708 (save-excursion
22709 (beginning-of-line)
22710 (cond ((or (not (message-in-body-p))
22711 (looking-at orgtbl-line-start-regexp))
22712 (throw 'exit nil))
22713 ((looking-at message-cite-prefix-regexp)
22714 (throw 'exit (match-string-no-properties 0)))
22715 ((looking-at org-outline-regexp)
22716 (throw 'exit (make-string (length (match-string 0)) ? ))))))
22717 (org-with-wide-buffer
22718 (let* ((p (line-beginning-position))
22719 (element (save-excursion
22720 (beginning-of-line)
22721 (or (ignore-errors (org-element-at-point))
22722 (user-error "An element cannot be parsed line %d"
22723 (line-number-at-pos (point))))))
22724 (type (org-element-type element))
22725 (post-affiliated (org-element-property :post-affiliated element)))
22726 (unless (and post-affiliated (< p post-affiliated))
22727 (case type
22728 (comment
22729 (save-excursion
22730 (beginning-of-line)
22731 (looking-at "[ \t]*")
22732 (concat (match-string 0) "# ")))
22733 (footnote-definition "")
22734 ((item plain-list)
22735 (make-string (org-list-item-body-column
22736 (or post-affiliated
22737 (org-element-property :begin element)))
22738 ? ))
22739 (paragraph
22740 ;; Fill prefix is usually the same as the current line,
22741 ;; unless the paragraph is at the beginning of an item.
22742 (let ((parent (org-element-property :parent element)))
22743 (save-excursion
22744 (beginning-of-line)
22745 (cond ((eq (org-element-type parent) 'item)
22746 (make-string (org-list-item-body-column
22747 (org-element-property :begin parent))
22748 ? ))
22749 ((and adaptive-fill-regexp
22750 ;; Locally disable
22751 ;; `adaptive-fill-function' to let
22752 ;; `fill-context-prefix' handle
22753 ;; `adaptive-fill-regexp' variable.
22754 (let (adaptive-fill-function)
22755 (fill-context-prefix
22756 post-affiliated
22757 (org-element-property :end element)))))
22758 ((looking-at "[ \t]+") (match-string 0))
22759 (t "")))))
22760 (comment-block
22761 ;; Only fill contents if P is within block boundaries.
22762 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22763 (forward-line)
22764 (point)))
22765 (cend (save-excursion
22766 (goto-char (org-element-property :end element))
22767 (skip-chars-backward " \r\t\n")
22768 (line-beginning-position))))
22769 (when (and (>= p cbeg) (< p cend))
22770 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22771 (match-string 0)
22772 ""))))))))))
22774 (declare-function message-goto-body "message" ())
22775 (defvar message-cite-prefix-regexp) ; From message.el
22776 (defun org-fill-paragraph (&optional justify)
22777 "Fill element at point, when applicable.
22779 This function only applies to comment blocks, comments, example
22780 blocks and paragraphs. Also, as a special case, re-align table
22781 when point is at one.
22783 If JUSTIFY is non-nil (interactively, with prefix argument),
22784 justify as well. If `sentence-end-double-space' is non-nil, then
22785 period followed by one space does not end a sentence, so don't
22786 break a line there. The variable `fill-column' controls the
22787 width for filling.
22789 For convenience, when point is at a plain list, an item or
22790 a footnote definition, try to fill the first paragraph within."
22791 (interactive)
22792 (if (and (derived-mode-p 'message-mode)
22793 (or (not (message-in-body-p))
22794 (save-excursion (move-beginning-of-line 1)
22795 (looking-at message-cite-prefix-regexp))))
22796 ;; First ensure filling is correct in message-mode.
22797 (let ((fill-paragraph-function
22798 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22799 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22800 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22801 (paragraph-separate
22802 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22803 (fill-paragraph nil))
22804 (with-syntax-table org-mode-transpose-word-syntax-table
22805 ;; Move to end of line in order to get the first paragraph
22806 ;; within a plain list or a footnote definition.
22807 (let ((element (save-excursion
22808 (end-of-line)
22809 (or (ignore-errors (org-element-at-point))
22810 (user-error "An element cannot be parsed line %d"
22811 (line-number-at-pos (point)))))))
22812 ;; First check if point is in a blank line at the beginning of
22813 ;; the buffer. In that case, ignore filling.
22814 (case (org-element-type element)
22815 ;; Use major mode filling function is src blocks.
22816 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22817 ;; Align Org tables, leave table.el tables as-is.
22818 (table-row (org-table-align) t)
22819 (table
22820 (when (eq (org-element-property :type element) 'org)
22821 (save-excursion
22822 (goto-char (org-element-property :post-affiliated element))
22823 (org-table-align)))
22825 (paragraph
22826 ;; Paragraphs may contain `line-break' type objects.
22827 (let ((beg (max (point-min)
22828 (org-element-property :contents-begin element)))
22829 (end (min (point-max)
22830 (org-element-property :contents-end element))))
22831 ;; Do nothing if point is at an affiliated keyword.
22832 (if (< (line-end-position) beg) t
22833 (when (derived-mode-p 'message-mode)
22834 ;; In `message-mode', do not fill following citation
22835 ;; in current paragraph nor text before message body.
22836 (let ((body-start (save-excursion (message-goto-body))))
22837 (when body-start (setq beg (max body-start beg))))
22838 (when (save-excursion
22839 (re-search-forward
22840 (concat "^" message-cite-prefix-regexp) end t))
22841 (setq end (match-beginning 0))))
22842 ;; Fill paragraph, taking line breaks into account.
22843 ;; For that, slice the paragraph using line breaks as
22844 ;; separators, and fill the parts in reverse order to
22845 ;; avoid messing with markers.
22846 (save-excursion
22847 (goto-char end)
22848 (mapc
22849 (lambda (pos)
22850 (fill-region-as-paragraph pos (point) justify)
22851 (goto-char pos))
22852 ;; Find the list of ending positions for line breaks
22853 ;; in the current paragraph. Add paragraph
22854 ;; beginning to include first slice.
22855 (nreverse
22856 (cons beg
22857 (org-element-map
22858 (org-element--parse-objects
22859 beg end nil (org-element-restriction 'paragraph))
22860 'line-break
22861 (lambda (lb) (org-element-property :end lb)))))))
22862 t)))
22863 ;; Contents of `comment-block' type elements should be
22864 ;; filled as plain text, but only if point is within block
22865 ;; markers.
22866 (comment-block
22867 (let* ((case-fold-search t)
22868 (beg (save-excursion
22869 (goto-char (org-element-property :begin element))
22870 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22871 (forward-line)
22872 (point)))
22873 (end (save-excursion
22874 (goto-char (org-element-property :end element))
22875 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22876 (line-beginning-position))))
22877 (if (or (< (point) beg) (> (point) end)) t
22878 (fill-region-as-paragraph
22879 (save-excursion (end-of-line)
22880 (re-search-backward "^[ \t]*$" beg 'move)
22881 (line-beginning-position))
22882 (save-excursion (beginning-of-line)
22883 (re-search-forward "^[ \t]*$" end 'move)
22884 (line-beginning-position))
22885 justify))))
22886 ;; Fill comments.
22887 (comment
22888 (let ((begin (org-element-property :post-affiliated element))
22889 (end (org-element-property :end element)))
22890 (when (and (>= (point) begin) (<= (point) end))
22891 (let ((begin (save-excursion
22892 (end-of-line)
22893 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22894 (progn (forward-line) (point))
22895 begin)))
22896 (end (save-excursion
22897 (end-of-line)
22898 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22899 (1- (line-beginning-position))
22900 (skip-chars-backward " \r\t\n")
22901 (line-end-position)))))
22902 ;; Do not fill comments when at a blank line.
22903 (when (> end begin)
22904 (let ((fill-prefix
22905 (save-excursion
22906 (beginning-of-line)
22907 (looking-at "[ \t]*#")
22908 (let ((comment-prefix (match-string 0)))
22909 (goto-char (match-end 0))
22910 (if (looking-at adaptive-fill-regexp)
22911 (concat comment-prefix (match-string 0))
22912 (concat comment-prefix " "))))))
22913 (save-excursion
22914 (fill-region-as-paragraph begin end justify))))))
22916 ;; Ignore every other element.
22917 (otherwise t))))))
22919 (defun org-auto-fill-function ()
22920 "Auto-fill function."
22921 ;; Check if auto-filling is meaningful.
22922 (let ((fc (current-fill-column)))
22923 (when (and fc (> (current-column) fc))
22924 (let* ((fill-prefix (org-adaptive-fill-function))
22925 ;; Enforce empty fill prefix, if required. Otherwise, it
22926 ;; will be computed again.
22927 (adaptive-fill-mode (not (equal fill-prefix ""))))
22928 (when fill-prefix (do-auto-fill))))))
22930 (defun org-comment-line-break-function (&optional soft)
22931 "Break line at point and indent, continuing comment if within one.
22932 The inserted newline is marked hard if variable
22933 `use-hard-newlines' is true, unless optional argument SOFT is
22934 non-nil."
22935 (if soft (insert-and-inherit ?\n) (newline 1))
22936 (save-excursion (forward-char -1) (delete-horizontal-space))
22937 (delete-horizontal-space)
22938 (indent-to-left-margin)
22939 (insert-before-markers-and-inherit fill-prefix))
22942 ;;; Fixed Width Areas
22944 (defun org-toggle-fixed-width ()
22945 "Toggle fixed-width markup.
22947 Add or remove fixed-width markup on current line, whenever it
22948 makes sense. Return an error otherwise.
22950 If a region is active and if it contains only fixed-width areas
22951 or blank lines, remove all fixed-width markup in it. If the
22952 region contains anything else, convert all non-fixed-width lines
22953 to fixed-width ones.
22955 Blank lines at the end of the region are ignored unless the
22956 region only contains such lines."
22957 (interactive)
22958 (if (not (org-region-active-p))
22959 ;; No region:
22961 ;; Remove fixed width marker only in a fixed-with element.
22963 ;; Add fixed width maker in paragraphs, in blank lines after
22964 ;; elements or at the beginning of a headline or an inlinetask,
22965 ;; and before any one-line elements (e.g., a clock).
22966 (progn
22967 (beginning-of-line)
22968 (let* ((element (org-element-at-point))
22969 (type (org-element-type element)))
22970 (cond
22971 ((and (eq type 'fixed-width)
22972 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
22973 (replace-match
22974 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
22975 ((and (memq type '(babel-call clock comment diary-sexp headline
22976 horizontal-rule keyword paragraph
22977 planning))
22978 (or (not (org-element-property :post-affiliated element))
22979 (<= (org-element-property :post-affiliated element)
22980 (point))))
22981 (skip-chars-forward " \t")
22982 (insert ": "))
22983 ((and (org-looking-at-p "[ \t]*$")
22984 (or (eq type 'inlinetask)
22985 (save-excursion
22986 (skip-chars-forward " \r\t\n")
22987 (<= (org-element-property :end element) (point)))))
22988 (delete-region (point) (line-end-position))
22989 (org-indent-line)
22990 (insert ": "))
22991 (t (user-error "Cannot insert a fixed-width line here")))))
22992 ;; Region active.
22993 (let* ((begin (save-excursion
22994 (goto-char (region-beginning))
22995 (line-beginning-position)))
22996 (end (copy-marker
22997 (save-excursion
22998 (goto-char (region-end))
22999 (unless (eolp) (beginning-of-line))
23000 (if (save-excursion (re-search-backward "\\S-" begin t))
23001 (progn (skip-chars-backward " \r\t\n") (point))
23002 (point)))))
23003 (all-fixed-width-p
23004 (catch 'not-all-p
23005 (save-excursion
23006 (goto-char begin)
23007 (skip-chars-forward " \r\t\n")
23008 (when (eobp) (throw 'not-all-p nil))
23009 (while (< (point) end)
23010 (let ((element (org-element-at-point)))
23011 (if (eq (org-element-type element) 'fixed-width)
23012 (goto-char (org-element-property :end element))
23013 (throw 'not-all-p nil))))
23014 t))))
23015 (if all-fixed-width-p
23016 (save-excursion
23017 (goto-char begin)
23018 (while (< (point) end)
23019 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23020 (replace-match
23021 "" nil nil nil
23022 (if (= (line-end-position) (match-end 0)) 0 1)))
23023 (forward-line)))
23024 (let ((min-ind (point-max)))
23025 ;; Find minimum indentation across all lines.
23026 (save-excursion
23027 (goto-char begin)
23028 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23029 (setq min-ind 0)
23030 (catch 'zerop
23031 (while (< (point) end)
23032 (unless (org-looking-at-p "[ \t]*$")
23033 (let ((ind (org-get-indentation)))
23034 (setq min-ind (min min-ind ind))
23035 (when (zerop ind) (throw 'zerop t))))
23036 (forward-line)))))
23037 ;; Loop over all lines and add fixed-width markup everywhere
23038 ;; but in fixed-width lines.
23039 (save-excursion
23040 (goto-char begin)
23041 (while (< (point) end)
23042 (cond
23043 ((org-at-heading-p)
23044 (insert ": ")
23045 (forward-line)
23046 (while (and (< (point) end) (org-looking-at-p "[ \t]*$"))
23047 (insert ":")
23048 (forward-line)))
23049 ((org-looking-at-p "[ \t]*:\\( \\|$\\)")
23050 (let* ((element (org-element-at-point))
23051 (element-end (org-element-property :end element)))
23052 (if (eq (org-element-type element) 'fixed-width)
23053 (progn (goto-char element-end)
23054 (skip-chars-backward " \r\t\n")
23055 (forward-line))
23056 (let ((limit (min end element-end)))
23057 (while (< (point) limit)
23058 (org-move-to-column min-ind t)
23059 (insert ": ")
23060 (forward-line))))))
23062 (org-move-to-column min-ind t)
23063 (insert ": ")
23064 (forward-line)))))))
23065 (set-marker end nil))))
23068 ;;; Comments
23070 ;; Org comments syntax is quite complex. It requires the entire line
23071 ;; to be just a comment. Also, even with the right syntax at the
23072 ;; beginning of line, some some elements (i.e. verse-block or
23073 ;; example-block) don't accept comments. Usual Emacs comment commands
23074 ;; cannot cope with those requirements. Therefore, Org replaces them.
23076 ;; Org still relies on `comment-dwim', but cannot trust
23077 ;; `comment-only-p'. So, `comment-region-function' and
23078 ;; `uncomment-region-function' both point
23079 ;; to`org-comment-or-uncomment-region'. Eventually,
23080 ;; `org-insert-comment' takes care of insertion of comments at the
23081 ;; beginning of line.
23083 ;; `org-setup-comments-handling' install comments related variables
23084 ;; during `org-mode' initialization.
23086 (defun org-setup-comments-handling ()
23087 (interactive)
23088 (org-set-local 'comment-use-syntax nil)
23089 (org-set-local 'comment-start "# ")
23090 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23091 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
23092 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
23093 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
23095 (defun org-insert-comment ()
23096 "Insert an empty comment above current line.
23097 If the line is empty, insert comment at its beginning. When
23098 point is within a source block, comment according to the related
23099 major mode."
23100 (if (let ((element (org-element-at-point)))
23101 (and (eq (org-element-type element) 'src-block)
23102 (< (save-excursion
23103 (goto-char (org-element-property :post-affiliated element))
23104 (line-end-position))
23105 (point))
23106 (> (save-excursion
23107 (goto-char (org-element-property :end element))
23108 (skip-chars-backward " \r\t\n")
23109 (line-beginning-position))
23110 (point))))
23111 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23112 (beginning-of-line)
23113 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23114 (open-line 1))
23115 (org-indent-line)
23116 (insert "# ")))
23118 (defvar comment-empty-lines) ; From newcomment.el.
23119 (defun org-comment-or-uncomment-region (beg end &rest ignore)
23120 "Comment or uncomment each non-blank line in the region.
23121 Uncomment each non-blank line between BEG and END if it only
23122 contains commented lines. Otherwise, comment them. If region is
23123 strictly within a source block, use appropriate comment syntax."
23124 (if (let ((element (org-element-at-point)))
23125 (and (eq (org-element-type element) 'src-block)
23126 (< (save-excursion
23127 (goto-char (org-element-property :post-affiliated element))
23128 (line-end-position))
23129 beg)
23130 (>= (save-excursion
23131 (goto-char (org-element-property :end element))
23132 (skip-chars-backward " \r\t\n")
23133 (line-beginning-position))
23134 end)))
23135 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23136 (save-restriction
23137 ;; Restrict region
23138 (narrow-to-region (save-excursion (goto-char beg)
23139 (skip-chars-forward " \r\t\n" end)
23140 (line-beginning-position))
23141 (save-excursion (goto-char end)
23142 (skip-chars-backward " \r\t\n" beg)
23143 (line-end-position)))
23144 (let ((uncommentp
23145 ;; UNCOMMENTP is non-nil when every non blank line between
23146 ;; BEG and END is a comment.
23147 (save-excursion
23148 (goto-char (point-min))
23149 (while (and (not (eobp))
23150 (let ((element (org-element-at-point)))
23151 (and (eq (org-element-type element) 'comment)
23152 (goto-char (min (point-max)
23153 (org-element-property
23154 :end element)))))))
23155 (eobp))))
23156 (if uncommentp
23157 ;; Only blank lines and comments in region: uncomment it.
23158 (save-excursion
23159 (goto-char (point-min))
23160 (while (not (eobp))
23161 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23162 (replace-match "" nil nil nil 1))
23163 (forward-line)))
23164 ;; Comment each line in region.
23165 (let ((min-indent (point-max)))
23166 ;; First find the minimum indentation across all lines.
23167 (save-excursion
23168 (goto-char (point-min))
23169 (while (and (not (eobp)) (not (zerop min-indent)))
23170 (unless (looking-at "[ \t]*$")
23171 (setq min-indent (min min-indent (current-indentation))))
23172 (forward-line)))
23173 ;; Then loop over all lines.
23174 (save-excursion
23175 (goto-char (point-min))
23176 (while (not (eobp))
23177 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23178 ;; Don't get fooled by invisible text (e.g. link path)
23179 ;; when moving to column MIN-INDENT.
23180 (let ((buffer-invisibility-spec nil))
23181 (org-move-to-column min-indent t))
23182 (insert comment-start))
23183 (forward-line)))))))))
23185 (defun org-comment-dwim (arg)
23186 (interactive "*P")
23187 "Call `comment-dwim' within a source edit buffer if needed."
23188 (if (org-in-src-block-p)
23189 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23190 (call-interactively 'comment-dwim)))
23193 ;;; Planning
23195 ;; This section contains tools to operate on timestamp objects, as
23196 ;; returned by, e.g. `org-element-context'.
23198 (defun org-timestamp-has-time-p (timestamp)
23199 "Non-nil when TIMESTAMP has a time specified."
23200 (org-element-property :hour-start timestamp))
23202 (defun org-timestamp-format (timestamp format &optional end utc)
23203 "Format a TIMESTAMP element into a string.
23205 FORMAT is a format specifier to be passed to
23206 `format-time-string'.
23208 When optional argument END is non-nil, use end of date-range or
23209 time-range, if possible.
23211 When optional argument UTC is non-nil, time will be expressed as
23212 Universal Time."
23213 (format-time-string
23214 format
23215 (apply 'encode-time
23216 (cons 0
23217 (mapcar
23218 (lambda (prop) (or (org-element-property prop timestamp) 0))
23219 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23220 '(:minute-start :hour-start :day-start :month-start
23221 :year-start)))))
23222 utc))
23224 (defun org-timestamp-split-range (timestamp &optional end)
23225 "Extract a timestamp object from a date or time range.
23227 TIMESTAMP is a timestamp object. END, when non-nil, means extract
23228 the end of the range. Otherwise, extract its start.
23230 Return a new timestamp object sharing the same parent as
23231 TIMESTAMP."
23232 (let ((type (org-element-property :type timestamp)))
23233 (if (memq type '(active inactive diary)) timestamp
23234 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
23235 ;; Set new type.
23236 (org-element-put-property
23237 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23238 ;; Copy start properties over end properties if END is
23239 ;; non-nil. Otherwise, copy end properties over `start' ones.
23240 (let ((p-alist '((:minute-start . :minute-end)
23241 (:hour-start . :hour-end)
23242 (:day-start . :day-end)
23243 (:month-start . :month-end)
23244 (:year-start . :year-end))))
23245 (dolist (p-cell p-alist)
23246 (org-element-put-property
23247 split-ts
23248 (funcall (if end 'car 'cdr) p-cell)
23249 (org-element-property
23250 (funcall (if end 'cdr 'car) p-cell) split-ts)))
23251 ;; Eventually refresh `:raw-value'.
23252 (org-element-put-property split-ts :raw-value nil)
23253 (org-element-put-property
23254 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23256 (defun org-timestamp-translate (timestamp &optional boundary)
23257 "Apply `org-translate-time' on a TIMESTAMP object.
23258 When optional argument BOUNDARY is non-nil, it is either the
23259 symbol `start' or `end'. In this case, only translate the
23260 starting or ending part of TIMESTAMP if it is a date or time
23261 range. Otherwise, translate both parts."
23262 (if (and (not boundary)
23263 (memq (org-element-property :type timestamp)
23264 '(active-range inactive-range)))
23265 (concat
23266 (org-translate-time
23267 (org-element-property :raw-value
23268 (org-timestamp-split-range timestamp)))
23269 "--"
23270 (org-translate-time
23271 (org-element-property :raw-value
23272 (org-timestamp-split-range timestamp t))))
23273 (org-translate-time
23274 (org-element-property
23275 :raw-value
23276 (if (not boundary) timestamp
23277 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
23281 ;;; Other stuff.
23283 (defun org-reftex-citation ()
23284 "Use reftex-citation to insert a citation into the buffer.
23285 This looks for a line like
23287 #+BIBLIOGRAPHY: foo plain option:-d
23289 and derives from it that foo.bib is the bibliography file relevant
23290 for this document. It then installs the necessary environment for RefTeX
23291 to work in this buffer and calls `reftex-citation' to insert a citation
23292 into the buffer.
23294 Export of such citations to both LaTeX and HTML is handled by the contributed
23295 package ox-bibtex by Taru Karttunen."
23296 (interactive)
23297 (let ((reftex-docstruct-symbol 'rds)
23298 (reftex-cite-format "\\cite{%l}")
23299 rds bib)
23300 (save-excursion
23301 (save-restriction
23302 (widen)
23303 (let ((case-fold-search t)
23304 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23305 (if (not (save-excursion
23306 (or (re-search-forward re nil t)
23307 (re-search-backward re nil t))))
23308 (user-error "No bibliography defined in file")
23309 (setq bib (concat (match-string 1) ".bib")
23310 rds (list (list 'bib bib)))))))
23311 (call-interactively 'reftex-citation)))
23313 ;;;; Functions extending outline functionality
23315 (defun org-beginning-of-line (&optional arg)
23316 "Go to the beginning of the current line. If that is invisible, continue
23317 to a visible line beginning. This makes the function of C-a more intuitive.
23318 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
23319 first attempt, and only move to after the tags when the cursor is already
23320 beyond the end of the headline."
23321 (interactive "P")
23322 (let ((pos (point))
23323 (special (if (consp org-special-ctrl-a/e)
23324 (car org-special-ctrl-a/e)
23325 org-special-ctrl-a/e))
23326 deactivate-mark refpos)
23327 (if (org-bound-and-true-p visual-line-mode)
23328 (beginning-of-visual-line 1)
23329 (beginning-of-line 1))
23330 (if (and arg (fboundp 'move-beginning-of-line))
23331 (call-interactively 'move-beginning-of-line)
23332 (if (bobp)
23334 (backward-char 1)
23335 (if (org-truely-invisible-p)
23336 (while (and (not (bobp)) (org-truely-invisible-p))
23337 (backward-char 1)
23338 (beginning-of-line 1))
23339 (forward-char 1))))
23340 (when special
23341 (cond
23342 ((and (looking-at org-complex-heading-regexp)
23343 (= (char-after (match-end 1)) ?\ ))
23344 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23345 (point-at-eol)))
23346 (goto-char
23347 (if (eq special t)
23348 (cond ((> pos refpos) refpos)
23349 ((= pos (point)) refpos)
23350 (t (point)))
23351 (cond ((> pos (point)) (point))
23352 ((not (eq last-command this-command)) (point))
23353 (t refpos)))))
23354 ((org-at-item-p)
23355 ;; Being at an item and not looking at an the item means point
23356 ;; was previously moved to beginning of a visual line, which
23357 ;; doesn't contain the item. Therefore, do nothing special,
23358 ;; just stay here.
23359 (when (looking-at org-list-full-item-re)
23360 ;; Set special position at first white space character after
23361 ;; bullet, and check-box, if any.
23362 (let ((after-bullet
23363 (let ((box (match-end 3)))
23364 (if (not box) (match-end 1)
23365 (let ((after (char-after box)))
23366 (if (and after (= after ? )) (1+ box) box))))))
23367 ;; Special case: Move point to special position when
23368 ;; currently after it or at beginning of line.
23369 (if (eq special t)
23370 (when (or (> pos after-bullet) (= (point) pos))
23371 (goto-char after-bullet))
23372 ;; Reversed case: Move point to special position when
23373 ;; point was already at beginning of line and command is
23374 ;; repeated.
23375 (when (and (= (point) pos) (eq last-command this-command))
23376 (goto-char after-bullet))))))))
23377 (org-no-warnings
23378 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23379 (setq disable-point-adjustment
23380 (or (not (invisible-p (point)))
23381 (not (invisible-p (max (point-min) (1- (point))))))))
23383 (defun org-end-of-line (&optional arg)
23384 "Go to the end of the line.
23385 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23386 tags on the first attempt, and only move to after the tags when
23387 the cursor is already beyond the end of the headline."
23388 (interactive "P")
23389 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
23390 org-special-ctrl-a/e))
23391 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
23392 'end-of-visual-line)
23393 ((fboundp 'move-end-of-line) 'move-end-of-line)
23394 (t 'end-of-line)))
23395 deactivate-mark)
23396 (if (or (not special) arg) (call-interactively move-fun)
23397 (let* ((element (save-excursion (beginning-of-line)
23398 (org-element-at-point)))
23399 (type (org-element-type element)))
23400 (cond
23401 ((memq type '(headline inlinetask))
23402 (let ((pos (point)))
23403 (beginning-of-line 1)
23404 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
23405 (if (eq special t)
23406 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
23407 (goto-char (match-beginning 1))
23408 (goto-char (match-end 0)))
23409 (if (or (< pos (match-end 0))
23410 (not (eq this-command last-command)))
23411 (goto-char (match-end 0))
23412 (goto-char (match-beginning 1))))
23413 (call-interactively move-fun))))
23414 ((outline-invisible-p (line-end-position))
23415 ;; If element is hidden, `move-end-of-line' would put point
23416 ;; after it. Use `end-of-line' to stay on current line.
23417 (call-interactively 'end-of-line))
23418 (t (call-interactively move-fun)))))
23419 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23420 (setq disable-point-adjustment
23421 (or (not (invisible-p (point)))
23422 (not (invisible-p (max (point-min) (1- (point))))))))
23424 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23425 (define-key org-mode-map "\C-e" 'org-end-of-line)
23427 (defun org-backward-sentence (&optional arg)
23428 "Go to beginning of sentence, or beginning of table field.
23429 This will call `backward-sentence' or `org-table-beginning-of-field',
23430 depending on context."
23431 (interactive "P")
23432 (cond
23433 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
23434 (t (call-interactively 'backward-sentence))))
23436 (defun org-forward-sentence (&optional arg)
23437 "Go to end of sentence, or end of table field.
23438 This will call `forward-sentence' or `org-table-end-of-field',
23439 depending on context."
23440 (interactive "P")
23441 (cond
23442 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
23443 (t (call-interactively 'forward-sentence))))
23445 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23446 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23448 (defun org-kill-line (&optional arg)
23449 "Kill line, to tags or end of line."
23450 (interactive "P")
23451 (cond
23452 ((or (not org-special-ctrl-k)
23453 (bolp)
23454 (not (org-at-heading-p)))
23455 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23456 org-ctrl-k-protect-subtree)
23457 (if (or (eq org-ctrl-k-protect-subtree 'error)
23458 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
23459 (user-error "C-k aborted as it would kill a hidden subtree")))
23460 (call-interactively
23461 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23462 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
23463 (kill-region (point) (match-beginning 1))
23464 (org-set-tags nil t))
23465 (t (kill-region (point) (point-at-eol)))))
23467 (define-key org-mode-map "\C-k" 'org-kill-line)
23469 (defun org-yank (&optional arg)
23470 "Yank. If the kill is a subtree, treat it specially.
23471 This command will look at the current kill and check if is a single
23472 subtree, or a series of subtrees[1]. If it passes the test, and if the
23473 cursor is at the beginning of a line or after the stars of a currently
23474 empty headline, then the yank is handled specially. How exactly depends
23475 on the value of the following variables, both set by default.
23477 org-yank-folded-subtrees
23478 When set, the subtree(s) will be folded after insertion, but only
23479 if doing so would now swallow text after the yanked text.
23481 org-yank-adjusted-subtrees
23482 When set, the subtree will be promoted or demoted in order to
23483 fit into the local outline tree structure, which means that the level
23484 will be adjusted so that it becomes the smaller one of the two
23485 *visible* surrounding headings.
23487 Any prefix to this command will cause `yank' to be called directly with
23488 no special treatment. In particular, a simple \\[universal-argument] prefix \
23489 will just
23490 plainly yank the text as it is.
23492 \[1] The test checks if the first non-white line is a heading
23493 and if there are no other headings with fewer stars."
23494 (interactive "P")
23495 (org-yank-generic 'yank arg))
23497 (defun org-yank-generic (command arg)
23498 "Perform some yank-like command.
23500 This function implements the behavior described in the `org-yank'
23501 documentation. However, it has been generalized to work for any
23502 interactive command with similar behavior."
23504 ;; pretend to be command COMMAND
23505 (setq this-command command)
23507 (if arg
23508 (call-interactively command)
23510 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23511 (and (org-kill-is-subtree-p)
23512 (or (bolp)
23513 (and (looking-at "[ \t]*$")
23514 (string-match
23515 "\\`\\*+\\'"
23516 (buffer-substring (point-at-bol) (point)))))))
23517 swallowp)
23518 (cond
23519 ((and subtreep org-yank-folded-subtrees)
23520 (let ((beg (point))
23521 end)
23522 (if (and subtreep org-yank-adjusted-subtrees)
23523 (org-paste-subtree nil nil 'for-yank)
23524 (call-interactively command))
23526 (setq end (point))
23527 (goto-char beg)
23528 (when (and (bolp) subtreep
23529 (not (setq swallowp
23530 (org-yank-folding-would-swallow-text beg end))))
23531 (org-with-limited-levels
23532 (or (looking-at org-outline-regexp)
23533 (re-search-forward org-outline-regexp-bol end t))
23534 (while (and (< (point) end) (looking-at org-outline-regexp))
23535 (hide-subtree)
23536 (org-cycle-show-empty-lines 'folded)
23537 (condition-case nil
23538 (outline-forward-same-level 1)
23539 (error (goto-char end))))))
23540 (when swallowp
23541 (message
23542 "Inserted text not folded because that would swallow text"))
23544 (goto-char end)
23545 (skip-chars-forward " \t\n\r")
23546 (beginning-of-line 1)
23547 (push-mark beg 'nomsg)))
23548 ((and subtreep org-yank-adjusted-subtrees)
23549 (let ((beg (point-at-bol)))
23550 (org-paste-subtree nil nil 'for-yank)
23551 (push-mark beg 'nomsg)))
23553 (call-interactively command))))))
23555 (defun org-yank-folding-would-swallow-text (beg end)
23556 "Would hide-subtree at BEG swallow any text after END?"
23557 (let (level)
23558 (org-with-limited-levels
23559 (save-excursion
23560 (goto-char beg)
23561 (when (or (looking-at org-outline-regexp)
23562 (re-search-forward org-outline-regexp-bol end t))
23563 (setq level (org-outline-level)))
23564 (goto-char end)
23565 (skip-chars-forward " \t\r\n\v\f")
23566 (if (or (eobp)
23567 (and (bolp) (looking-at org-outline-regexp)
23568 (<= (org-outline-level) level)))
23569 nil ; Nothing would be swallowed
23570 t))))) ; something would swallow
23572 (define-key org-mode-map "\C-y" 'org-yank)
23574 (defun org-truely-invisible-p ()
23575 "Check if point is at a character currently not visible.
23576 This version does not only check the character property, but also
23577 `visible-mode'."
23578 ;; Early versions of noutline don't have `outline-invisible-p'.
23579 (if (org-bound-and-true-p visible-mode)
23581 (outline-invisible-p)))
23583 (defun org-invisible-p2 ()
23584 "Check if point is at a character currently not visible."
23585 (save-excursion
23586 (if (and (eolp) (not (bobp))) (backward-char 1))
23587 ;; Early versions of noutline don't have `outline-invisible-p'.
23588 (outline-invisible-p)))
23590 (defun org-back-to-heading (&optional invisible-ok)
23591 "Call `outline-back-to-heading', but provide a better error message."
23592 (condition-case nil
23593 (outline-back-to-heading invisible-ok)
23594 (error (error "Before first headline at position %d in buffer %s"
23595 (point) (current-buffer)))))
23597 (defun org-before-first-heading-p ()
23598 "Before first heading?"
23599 (save-excursion
23600 (end-of-line)
23601 (null (re-search-backward org-outline-regexp-bol nil t))))
23603 (defun org-at-heading-p (&optional ignored)
23604 (outline-on-heading-p t))
23605 ;; Compatibility alias with Org versions < 7.8.03
23606 (defalias 'org-on-heading-p 'org-at-heading-p)
23608 (defun org-in-commented-heading-p (&optional no-inheritance)
23609 "Non-nil if point is under a commented heading.
23610 This function also checks ancestors of the current headline,
23611 unless optional argument NO-INHERITANCE is non-nil."
23612 (cond
23613 ((org-before-first-heading-p) nil)
23614 ((let ((headline (nth 4 (org-heading-components))))
23615 (and headline
23616 (let ((case-fold-search nil))
23617 (org-string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
23618 headline)))))
23619 (no-inheritance nil)
23621 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
23623 (defun org-at-comment-p nil
23624 "Is cursor in a commented line?"
23625 (save-excursion
23626 (save-match-data
23627 (beginning-of-line)
23628 (looking-at "^[ \t]*# "))))
23630 (defun org-at-drawer-p nil
23631 "Is cursor at a drawer keyword?"
23632 (save-excursion
23633 (move-beginning-of-line 1)
23634 (looking-at org-drawer-regexp)))
23636 (defun org-at-block-p nil
23637 "Is cursor at a block keyword?"
23638 (save-excursion
23639 (move-beginning-of-line 1)
23640 (looking-at org-block-regexp)))
23642 (defun org-point-at-end-of-empty-headline ()
23643 "If point is at the end of an empty headline, return t, else nil.
23644 If the heading only contains a TODO keyword, it is still still considered
23645 empty."
23646 (and (looking-at "[ \t]*$")
23647 (when org-todo-line-regexp
23648 (save-excursion
23649 (beginning-of-line 1)
23650 (let ((case-fold-search nil))
23651 (looking-at org-todo-line-regexp)
23652 (string= (match-string 3) ""))))))
23654 (defun org-at-heading-or-item-p ()
23655 (or (org-at-heading-p) (org-at-item-p)))
23657 (defun org-at-target-p ()
23658 (or (org-in-regexp org-radio-target-regexp)
23659 (org-in-regexp org-target-regexp)))
23660 ;; Compatibility alias with Org versions < 7.8.03
23661 (defalias 'org-on-target-p 'org-at-target-p)
23663 (defun org-up-heading-all (arg)
23664 "Move to the heading line of which the present line is a subheading.
23665 This function considers both visible and invisible heading lines.
23666 With argument, move up ARG levels."
23667 (if (fboundp 'outline-up-heading-all)
23668 (outline-up-heading-all arg) ; emacs 21 version of outline.el
23669 (outline-up-heading arg t))) ; emacs 22 version of outline.el
23671 (defun org-up-heading-safe ()
23672 "Move to the heading line of which the present line is a subheading.
23673 This version will not throw an error. It will return the level of the
23674 headline found, or nil if no higher level is found.
23676 Also, this function will be a lot faster than `outline-up-heading',
23677 because it relies on stars being the outline starters. This can really
23678 make a significant difference in outlines with very many siblings."
23679 (let (start-level re)
23680 (org-back-to-heading t)
23681 (setq start-level (funcall outline-level))
23682 (if (equal start-level 1)
23684 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
23685 (if (re-search-backward re nil t)
23686 (funcall outline-level)))))
23688 (defun org-first-sibling-p ()
23689 "Is this heading the first child of its parents?"
23690 (interactive)
23691 (let ((re org-outline-regexp-bol)
23692 level l)
23693 (unless (org-at-heading-p t)
23694 (user-error "Not at a heading"))
23695 (setq level (funcall outline-level))
23696 (save-excursion
23697 (if (not (re-search-backward re nil t))
23699 (setq l (funcall outline-level))
23700 (< l level)))))
23702 (defun org-goto-sibling (&optional previous)
23703 "Goto the next sibling, even if it is invisible.
23704 When PREVIOUS is set, go to the previous sibling instead. Returns t
23705 when a sibling was found. When none is found, return nil and don't
23706 move point."
23707 (let ((fun (if previous 're-search-backward 're-search-forward))
23708 (pos (point))
23709 (re org-outline-regexp-bol)
23710 level l)
23711 (when (ignore-errors (org-back-to-heading t))
23712 (setq level (funcall outline-level))
23713 (catch 'exit
23714 (or previous (forward-char 1))
23715 (while (funcall fun re nil t)
23716 (setq l (funcall outline-level))
23717 (when (< l level) (goto-char pos) (throw 'exit nil))
23718 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23719 (goto-char pos)
23720 nil))))
23722 (defun org-show-siblings ()
23723 "Show all siblings of the current headline."
23724 (save-excursion
23725 (while (org-goto-sibling) (org-flag-heading nil)))
23726 (save-excursion
23727 (while (org-goto-sibling 'previous)
23728 (org-flag-heading nil))))
23730 (defun org-goto-first-child ()
23731 "Goto the first child, even if it is invisible.
23732 Return t when a child was found. Otherwise don't move point and
23733 return nil."
23734 (let (level (pos (point)) (re org-outline-regexp-bol))
23735 (when (ignore-errors (org-back-to-heading t))
23736 (setq level (outline-level))
23737 (forward-char 1)
23738 (if (and (re-search-forward re nil t) (> (outline-level) level))
23739 (progn (goto-char (match-beginning 0)) t)
23740 (goto-char pos) nil))))
23742 (defun org-show-hidden-entry ()
23743 "Show an entry where even the heading is hidden."
23744 (save-excursion
23745 (org-show-entry)))
23747 (defun org-flag-heading (flag &optional entry)
23748 "Flag the current heading. FLAG non-nil means make invisible.
23749 When ENTRY is non-nil, show the entire entry."
23750 (save-excursion
23751 (org-back-to-heading t)
23752 ;; Check if we should show the entire entry
23753 (if entry
23754 (progn
23755 (org-show-entry)
23756 (save-excursion
23757 (and (outline-next-heading)
23758 (org-flag-heading nil))))
23759 (outline-flag-region (max (point-min) (1- (point)))
23760 (save-excursion (outline-end-of-heading) (point))
23761 flag))))
23763 (defun org-get-next-sibling ()
23764 "Move to next heading of the same level, and return point.
23765 If there is no such heading, return nil.
23766 This is like outline-next-sibling, but invisible headings are ok."
23767 (let ((level (funcall outline-level)))
23768 (outline-next-heading)
23769 (while (and (not (eobp)) (> (funcall outline-level) level))
23770 (outline-next-heading))
23771 (if (or (eobp) (< (funcall outline-level) level))
23773 (point))))
23775 (defun org-get-last-sibling ()
23776 "Move to previous heading of the same level, and return point.
23777 If there is no such heading, return nil."
23778 (let ((opoint (point))
23779 (level (funcall outline-level)))
23780 (outline-previous-heading)
23781 (when (and (/= (point) opoint) (outline-on-heading-p t))
23782 (while (and (> (funcall outline-level) level)
23783 (not (bobp)))
23784 (outline-previous-heading))
23785 (if (< (funcall outline-level) level)
23787 (point)))))
23789 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23790 "Goto to the end of a subtree."
23791 ;; This contains an exact copy of the original function, but it uses
23792 ;; `org-back-to-heading', to make it work also in invisible
23793 ;; trees. And is uses an invisible-ok argument.
23794 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23795 ;; Furthermore, when used inside Org, finding the end of a large subtree
23796 ;; with many children and grandchildren etc, this can be much faster
23797 ;; than the outline version.
23798 (org-back-to-heading invisible-ok)
23799 (let ((first t)
23800 (level (funcall outline-level)))
23801 (if (and (derived-mode-p 'org-mode) (< level 1000))
23802 ;; A true heading (not a plain list item), in Org-mode
23803 ;; This means we can easily find the end by looking
23804 ;; only for the right number of stars. Using a regexp to do
23805 ;; this is so much faster than using a Lisp loop.
23806 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23807 (forward-char 1)
23808 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23809 ;; something else, do it the slow way
23810 (while (and (not (eobp))
23811 (or first (> (funcall outline-level) level)))
23812 (setq first nil)
23813 (outline-next-heading)))
23814 (unless to-heading
23815 (if (memq (preceding-char) '(?\n ?\^M))
23816 (progn
23817 ;; Go to end of line before heading
23818 (forward-char -1)
23819 (if (memq (preceding-char) '(?\n ?\^M))
23820 ;; leave blank line before heading
23821 (forward-char -1))))))
23822 (point))
23824 (defun org-end-of-meta-data-and-drawers ()
23825 "Jump to the first text after meta data and drawers in the current entry.
23826 This will move over empty lines, lines with planning time stamps,
23827 clocking lines, and drawers."
23828 (org-back-to-heading t)
23829 (let ((end (save-excursion (outline-next-heading) (point)))
23830 (re (concat "\\(" org-drawer-regexp "\\)"
23831 "\\|" "[ \t]*" org-keyword-time-regexp)))
23832 (forward-line 1)
23833 (while (re-search-forward re end t)
23834 (if (not (match-end 1))
23835 ;; empty or planning line
23836 (forward-line 1)
23837 ;; a drawer, find the end
23838 (re-search-forward "^[ \t]*:END:" end 'move)
23839 (forward-line 1)))
23840 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23841 (point)))
23843 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23844 "Move forward to the ARG'th subheading at same level as this one.
23845 Stop at the first and last subheadings of a superior heading.
23846 Normally this only looks at visible headings, but when INVISIBLE-OK is
23847 non-nil it will also look at invisible ones."
23848 (interactive "p")
23849 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23850 (if (and arg (< arg 0))
23851 (goto-char (point-min))
23852 (outline-next-heading))
23853 (org-at-heading-p)
23854 (let ((level (- (match-end 0) (match-beginning 0) 1))
23855 (f (if (and arg (< arg 0))
23856 're-search-backward
23857 're-search-forward))
23858 (count (if arg (abs arg) 1))
23859 (result (point)))
23860 (while (and (prog1 (> count 0)
23861 (forward-char (if (and arg (< arg 0)) -1 1)))
23862 (funcall f org-outline-regexp-bol nil 'move))
23863 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23864 (cond ((< l level) (setq count 0))
23865 ((and (= l level)
23866 (or invisible-ok
23867 (progn
23868 (goto-char (line-beginning-position))
23869 (not (outline-invisible-p)))))
23870 (setq count (1- count))
23871 (when (eq l level)
23872 (setq result (point)))))))
23873 (goto-char result))
23874 (beginning-of-line 1)))
23876 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23877 "Move backward to the ARG'th subheading at same level as this one.
23878 Stop at the first and last subheadings of a superior heading."
23879 (interactive "p")
23880 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23882 (defun org-next-block (arg &optional backward block-regexp)
23883 "Jump to the next block.
23884 With a prefix argument ARG, jump forward ARG many source blocks.
23885 When BACKWARD is non-nil, jump to the previous block.
23886 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23887 (interactive "p")
23888 (let ((re (or block-regexp org-block-regexp))
23889 (re-search-fn (or (and backward 're-search-backward)
23890 're-search-forward)))
23891 (if (looking-at re) (forward-char 1))
23892 (condition-case nil
23893 (funcall re-search-fn re nil nil arg)
23894 (error (user-error "No %s code blocks"
23895 (if backward "previous" "further" ))))
23896 (goto-char (match-beginning 0)) (org-show-context)))
23898 (defun org-previous-block (arg &optional block-regexp)
23899 "Jump to the previous block.
23900 With a prefix argument ARG, jump backward ARG many source blocks.
23901 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23902 (interactive "p")
23903 (org-next-block arg t block-regexp))
23905 (defun org-forward-paragraph ()
23906 "Move forward to beginning of next paragraph or equivalent.
23908 The function moves point to the beginning of the next visible
23909 structural element, which can be a paragraph, a table, a list
23910 item, etc. It also provides some special moves for convenience:
23912 - On an affiliated keyword, jump to the beginning of the
23913 relative element.
23914 - On an item or a footnote definition, move to the second
23915 element inside, if any.
23916 - On a table or a property drawer, jump after it.
23917 - On a verse or source block, stop after blank lines."
23918 (interactive)
23919 (when (eobp) (user-error "Cannot move further down"))
23920 (let* ((deactivate-mark nil)
23921 (element (org-element-at-point))
23922 (type (org-element-type element))
23923 (post-affiliated (org-element-property :post-affiliated element))
23924 (contents-begin (org-element-property :contents-begin element))
23925 (contents-end (org-element-property :contents-end element))
23926 (end (let ((end (org-element-property :end element)) (parent element))
23927 (while (and (setq parent (org-element-property :parent parent))
23928 (= (org-element-property :contents-end parent) end))
23929 (setq end (org-element-property :end parent)))
23930 end)))
23931 (cond ((not element)
23932 (skip-chars-forward " \r\t\n")
23933 (or (eobp) (beginning-of-line)))
23934 ;; On affiliated keywords, move to element's beginning.
23935 ((and post-affiliated (< (point) post-affiliated))
23936 (goto-char post-affiliated))
23937 ;; At a table row, move to the end of the table. Similarly,
23938 ;; at a node property, move to the end of the property
23939 ;; drawer.
23940 ((memq type '(node-property table-row))
23941 (goto-char (org-element-property
23942 :end (org-element-property :parent element))))
23943 ((memq type '(property-drawer table)) (goto-char end))
23944 ;; Consider blank lines as separators in verse and source
23945 ;; blocks to ease editing.
23946 ((memq type '(src-block verse-block))
23947 (when (eq type 'src-block)
23948 (setq contents-end
23949 (save-excursion (goto-char end)
23950 (skip-chars-backward " \r\t\n")
23951 (line-beginning-position))))
23952 (beginning-of-line)
23953 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23954 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23955 (goto-char end)
23956 (skip-chars-forward " \r\t\n")
23957 (if (= (point) contents-end) (goto-char end)
23958 (beginning-of-line))))
23959 ;; With no contents, just skip element.
23960 ((not contents-begin) (goto-char end))
23961 ;; If contents are invisible, skip the element altogether.
23962 ((outline-invisible-p (line-end-position))
23963 (case type
23964 (headline
23965 (org-with-limited-levels (outline-next-visible-heading 1)))
23966 ;; At a plain list, make sure we move to the next item
23967 ;; instead of skipping the whole list.
23968 (plain-list (forward-char)
23969 (org-forward-paragraph))
23970 (otherwise (goto-char end))))
23971 ((>= (point) contents-end) (goto-char end))
23972 ((>= (point) contents-begin)
23973 ;; This can only happen on paragraphs and plain lists.
23974 (case type
23975 (paragraph (goto-char end))
23976 ;; At a plain list, try to move to second element in
23977 ;; first item, if possible.
23978 (plain-list (end-of-line)
23979 (org-forward-paragraph))))
23980 ;; When contents start on the middle of a line (e.g. in
23981 ;; items and footnote definitions), try to reach first
23982 ;; element starting after current line.
23983 ((> (line-end-position) contents-begin)
23984 (end-of-line)
23985 (org-forward-paragraph))
23986 (t (goto-char contents-begin)))))
23988 (defun org-backward-paragraph ()
23989 "Move backward to start of previous paragraph or equivalent.
23991 The function moves point to the beginning of the current
23992 structural element, which can be a paragraph, a table, a list
23993 item, etc., or to the beginning of the previous visible one if
23994 point is already there. It also provides some special moves for
23995 convenience:
23997 - On an affiliated keyword, jump to the first one.
23998 - On a table or a property drawer, move to its beginning.
23999 - On a verse or source block, stop before blank lines."
24000 (interactive)
24001 (when (bobp) (user-error "Cannot move further up"))
24002 (let* ((deactivate-mark nil)
24003 (element (org-element-at-point))
24004 (type (org-element-type element))
24005 (contents-begin (org-element-property :contents-begin element))
24006 (contents-end (org-element-property :contents-end element))
24007 (post-affiliated (org-element-property :post-affiliated element))
24008 (begin (org-element-property :begin element)))
24009 (cond
24010 ((not element) (goto-char (point-min)))
24011 ((= (point) begin)
24012 (backward-char)
24013 (org-backward-paragraph))
24014 ((and post-affiliated (<= (point) post-affiliated)) (goto-char begin))
24015 ((memq type '(node-property table-row))
24016 (goto-char (org-element-property
24017 :post-affiliated (org-element-property :parent element))))
24018 ((memq type '(property-drawer table)) (goto-char begin))
24019 ((memq type '(src-block verse-block))
24020 (when (eq type 'src-block)
24021 (setq contents-begin
24022 (save-excursion (goto-char begin) (forward-line) (point))))
24023 (if (= (point) contents-begin) (goto-char post-affiliated)
24024 ;; Inside a verse block, see blank lines as paragraph
24025 ;; separators.
24026 (let ((origin (point)))
24027 (skip-chars-backward " \r\t\n" contents-begin)
24028 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24029 (skip-chars-forward " \r\t\n" origin)
24030 (if (= (point) origin) (goto-char contents-begin)
24031 (beginning-of-line))))))
24032 ((not contents-begin) (goto-char (or post-affiliated begin)))
24033 ((eq type 'paragraph)
24034 (goto-char contents-begin)
24035 ;; When at first paragraph in an item or a footnote definition,
24036 ;; move directly to beginning of line.
24037 (let ((parent-contents
24038 (org-element-property
24039 :contents-begin (org-element-property :parent element))))
24040 (when (and parent-contents (= parent-contents contents-begin))
24041 (beginning-of-line))))
24042 ;; At the end of a greater element, move to the beginning of the
24043 ;; last element within.
24044 ((>= (point) contents-end)
24045 (goto-char (1- contents-end))
24046 (org-backward-paragraph))
24047 (t (goto-char (or post-affiliated begin))))
24048 ;; Ensure we never leave point invisible.
24049 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
24051 (defun org-forward-element ()
24052 "Move forward by one element.
24053 Move to the next element at the same level, when possible."
24054 (interactive)
24055 (cond ((eobp) (user-error "Cannot move further down"))
24056 ((org-with-limited-levels (org-at-heading-p))
24057 (let ((origin (point)))
24058 (goto-char (org-end-of-subtree nil t))
24059 (unless (org-with-limited-levels (org-at-heading-p))
24060 (goto-char origin)
24061 (user-error "Cannot move further down"))))
24063 (let* ((elem (org-element-at-point))
24064 (end (org-element-property :end elem))
24065 (parent (org-element-property :parent elem)))
24066 (cond ((and parent (= (org-element-property :contents-end parent) end))
24067 (goto-char (org-element-property :end parent)))
24068 ((integer-or-marker-p end) (goto-char end))
24069 (t (message "No element at point")))))))
24071 (defun org-backward-element ()
24072 "Move backward by one element.
24073 Move to the previous element at the same level, when possible."
24074 (interactive)
24075 (cond ((bobp) (user-error "Cannot move further up"))
24076 ((org-with-limited-levels (org-at-heading-p))
24077 ;; At a headline, move to the previous one, if any, or stay
24078 ;; here.
24079 (let ((origin (point)))
24080 (org-with-limited-levels (org-backward-heading-same-level 1))
24081 ;; When current headline has no sibling above, move to its
24082 ;; parent.
24083 (when (= (point) origin)
24084 (or (org-with-limited-levels (org-up-heading-safe))
24085 (progn (goto-char origin)
24086 (user-error "Cannot move further up"))))))
24088 (let* ((elem (org-element-at-point))
24089 (beg (org-element-property :begin elem)))
24090 (cond
24091 ;; Move to beginning of current element if point isn't
24092 ;; there already.
24093 ((null beg) (message "No element at point"))
24094 ((/= (point) beg) (goto-char beg))
24095 (t (goto-char beg)
24096 (skip-chars-backward " \r\t\n")
24097 (unless (bobp)
24098 (let ((prev (org-element-at-point)))
24099 (goto-char (org-element-property :begin prev))
24100 (while (and (setq prev (org-element-property :parent prev))
24101 (<= (org-element-property :end prev) beg))
24102 (goto-char (org-element-property :begin prev)))))))))))
24104 (defun org-up-element ()
24105 "Move to upper element."
24106 (interactive)
24107 (if (org-with-limited-levels (org-at-heading-p))
24108 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24109 (let* ((elem (org-element-at-point))
24110 (parent (org-element-property :parent elem)))
24111 (if parent (goto-char (org-element-property :begin parent))
24112 (if (org-with-limited-levels (org-before-first-heading-p))
24113 (user-error "No surrounding element")
24114 (org-with-limited-levels (org-back-to-heading)))))))
24116 (defvar org-element-greater-elements)
24117 (defun org-down-element ()
24118 "Move to inner element."
24119 (interactive)
24120 (let ((element (org-element-at-point)))
24121 (cond
24122 ((memq (org-element-type element) '(plain-list table))
24123 (goto-char (org-element-property :contents-begin element))
24124 (forward-char))
24125 ((memq (org-element-type element) org-element-greater-elements)
24126 ;; If contents are hidden, first disclose them.
24127 (when (outline-invisible-p (line-end-position)) (org-cycle))
24128 (goto-char (or (org-element-property :contents-begin element)
24129 (user-error "No content for this element"))))
24130 (t (user-error "No inner element")))))
24132 (defun org-drag-element-backward ()
24133 "Move backward element at point."
24134 (interactive)
24135 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
24136 (let* ((elem (org-element-at-point))
24137 (prev-elem
24138 (save-excursion
24139 (goto-char (org-element-property :begin elem))
24140 (skip-chars-backward " \r\t\n")
24141 (unless (bobp)
24142 (let* ((beg (org-element-property :begin elem))
24143 (prev (org-element-at-point))
24144 (up prev))
24145 (while (and (setq up (org-element-property :parent up))
24146 (<= (org-element-property :end prev) beg))
24147 (setq prev up))
24148 prev)))))
24149 ;; Error out if no previous element or previous element is
24150 ;; a parent of the current one.
24151 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24152 (user-error "Cannot drag element backward")
24153 (let ((pos (point)))
24154 (org-element-swap-A-B prev-elem elem)
24155 (goto-char (+ (org-element-property :begin prev-elem)
24156 (- pos (org-element-property :begin elem)))))))))
24158 (defun org-drag-element-forward ()
24159 "Move forward element at point."
24160 (interactive)
24161 (let* ((pos (point))
24162 (elem (org-element-at-point)))
24163 (when (= (point-max) (org-element-property :end elem))
24164 (user-error "Cannot drag element forward"))
24165 (goto-char (org-element-property :end elem))
24166 (let ((next-elem (org-element-at-point)))
24167 (when (or (org-element-nested-p elem next-elem)
24168 (and (eq (org-element-type next-elem) 'headline)
24169 (not (eq (org-element-type elem) 'headline))))
24170 (goto-char pos)
24171 (user-error "Cannot drag element forward"))
24172 ;; Compute new position of point: it's shifted by NEXT-ELEM
24173 ;; body's length (without final blanks) and by the length of
24174 ;; blanks between ELEM and NEXT-ELEM.
24175 (let ((size-next (- (save-excursion
24176 (goto-char (org-element-property :end next-elem))
24177 (skip-chars-backward " \r\t\n")
24178 (forward-line)
24179 ;; Small correction if buffer doesn't end
24180 ;; with a newline character.
24181 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24182 (org-element-property :begin next-elem)))
24183 (size-blank (- (org-element-property :end elem)
24184 (save-excursion
24185 (goto-char (org-element-property :end elem))
24186 (skip-chars-backward " \r\t\n")
24187 (forward-line)
24188 (point)))))
24189 (org-element-swap-A-B elem next-elem)
24190 (goto-char (+ pos size-next size-blank))))))
24192 (defun org-drag-line-forward (arg)
24193 "Drag the line at point ARG lines forward."
24194 (interactive "p")
24195 (dotimes (n (abs arg))
24196 (let ((c (current-column)))
24197 (if (< 0 arg)
24198 (progn
24199 (beginning-of-line 2)
24200 (transpose-lines 1)
24201 (beginning-of-line 0))
24202 (transpose-lines 1)
24203 (beginning-of-line -1))
24204 (org-move-to-column c))))
24206 (defun org-drag-line-backward (arg)
24207 "Drag the line at point ARG lines backward."
24208 (interactive "p")
24209 (org-drag-line-forward (- arg)))
24211 (defun org-mark-element ()
24212 "Put point at beginning of this element, mark at end.
24214 Interactively, if this command is repeated or (in Transient Mark
24215 mode) if the mark is active, it marks the next element after the
24216 ones already marked."
24217 (interactive)
24218 (let (deactivate-mark)
24219 (if (and (org-called-interactively-p 'any)
24220 (or (and (eq last-command this-command) (mark t))
24221 (and transient-mark-mode mark-active)))
24222 (set-mark
24223 (save-excursion
24224 (goto-char (mark))
24225 (goto-char (org-element-property :end (org-element-at-point)))))
24226 (let ((element (org-element-at-point)))
24227 (end-of-line)
24228 (push-mark (org-element-property :end element) t t)
24229 (goto-char (org-element-property :begin element))))))
24231 (defun org-narrow-to-element ()
24232 "Narrow buffer to current element."
24233 (interactive)
24234 (let ((elem (org-element-at-point)))
24235 (cond
24236 ((eq (car elem) 'headline)
24237 (narrow-to-region
24238 (org-element-property :begin elem)
24239 (org-element-property :end elem)))
24240 ((memq (car elem) org-element-greater-elements)
24241 (narrow-to-region
24242 (org-element-property :contents-begin elem)
24243 (org-element-property :contents-end elem)))
24245 (narrow-to-region
24246 (org-element-property :begin elem)
24247 (org-element-property :end elem))))))
24249 (defun org-transpose-element ()
24250 "Transpose current and previous elements, keeping blank lines between.
24251 Point is moved after both elements."
24252 (interactive)
24253 (org-skip-whitespace)
24254 (let ((end (org-element-property :end (org-element-at-point))))
24255 (org-drag-element-backward)
24256 (goto-char end)))
24258 (defun org-unindent-buffer ()
24259 "Un-indent the visible part of the buffer.
24260 Relative indentation (between items, inside blocks, etc.) isn't
24261 modified."
24262 (interactive)
24263 (unless (eq major-mode 'org-mode)
24264 (user-error "Cannot un-indent a buffer not in Org mode"))
24265 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
24266 unindent-tree ; For byte-compiler.
24267 (unindent-tree
24268 (function
24269 (lambda (contents)
24270 (mapc
24271 (lambda (element)
24272 (if (memq (org-element-type element) '(headline section))
24273 (funcall unindent-tree (org-element-contents element))
24274 (save-excursion
24275 (save-restriction
24276 (narrow-to-region
24277 (org-element-property :begin element)
24278 (org-element-property :end element))
24279 (org-do-remove-indentation)))))
24280 (reverse contents))))))
24281 (funcall unindent-tree (org-element-contents parse-tree))))
24283 (defun org-show-subtree ()
24284 "Show everything after this heading at deeper levels."
24285 (interactive)
24286 (outline-flag-region
24287 (point)
24288 (save-excursion
24289 (org-end-of-subtree t t))
24290 nil))
24292 (defun org-show-entry ()
24293 "Show the body directly following this heading.
24294 Show the heading too, if it is currently invisible."
24295 (interactive)
24296 (save-excursion
24297 (ignore-errors
24298 (org-back-to-heading t)
24299 (outline-flag-region
24300 (max (point-min) (1- (point)))
24301 (save-excursion
24302 (if (re-search-forward
24303 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24304 (match-beginning 1)
24305 (point-max)))
24306 nil)
24307 (org-cycle-hide-drawers 'children))))
24309 (defun org-make-options-regexp (kwds &optional extra)
24310 "Make a regular expression for keyword lines."
24311 (concat
24312 "^[ \t]*#\\+\\("
24313 (mapconcat 'regexp-quote kwds "\\|")
24314 (if extra (concat "\\|" extra))
24315 "\\):[ \t]*\\(.*\\)"))
24317 ;; Make isearch reveal the necessary context
24318 (defun org-isearch-end ()
24319 "Reveal context after isearch exits."
24320 (when isearch-success ; only if search was successful
24321 (if (featurep 'xemacs)
24322 ;; Under XEmacs, the hook is run in the correct place,
24323 ;; we directly show the context.
24324 (org-show-context 'isearch)
24325 ;; In Emacs the hook runs *before* restoring the overlays.
24326 ;; So we have to use a one-time post-command-hook to do this.
24327 ;; (Emacs 22 has a special variable, see function `org-mode')
24328 (unless (and (boundp 'isearch-mode-end-hook-quit)
24329 isearch-mode-end-hook-quit)
24330 ;; Only when the isearch was not quitted.
24331 (org-add-hook 'post-command-hook 'org-isearch-post-command
24332 'append 'local)))
24333 (org-fix-ellipsis-at-bol)))
24335 (defun org-isearch-post-command ()
24336 "Remove self from hook, and show context."
24337 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
24338 (org-show-context 'isearch))
24341 ;;;; Integration with and fixes for other packages
24343 ;;; Imenu support
24345 (defvar org-imenu-markers nil
24346 "All markers currently used by Imenu.")
24347 (make-variable-buffer-local 'org-imenu-markers)
24349 (defun org-imenu-new-marker (&optional pos)
24350 "Return a new marker for use by Imenu, and remember the marker."
24351 (let ((m (make-marker)))
24352 (move-marker m (or pos (point)))
24353 (push m org-imenu-markers)
24356 (defun org-imenu-get-tree ()
24357 "Produce the index for Imenu."
24358 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
24359 (setq org-imenu-markers nil)
24360 (let* ((n org-imenu-depth)
24361 (re (concat "^" (org-get-limited-outline-regexp)))
24362 (subs (make-vector (1+ n) nil))
24363 (last-level 0)
24364 m level head0 head)
24365 (save-excursion
24366 (save-restriction
24367 (widen)
24368 (goto-char (point-max))
24369 (while (re-search-backward re nil t)
24370 (setq level (org-reduced-level (funcall outline-level)))
24371 (when (and (<= level n)
24372 (looking-at org-complex-heading-regexp)
24373 (setq head0 (org-match-string-no-properties 4)))
24374 (setq head (org-link-display-format head0)
24375 m (org-imenu-new-marker))
24376 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24377 (if (>= level last-level)
24378 (push (cons head m) (aref subs level))
24379 (push (cons head (aref subs (1+ level))) (aref subs level))
24380 (loop for i from (1+ level) to n do (aset subs i nil)))
24381 (setq last-level level)))))
24382 (aref subs 1)))
24384 (eval-after-load "imenu"
24385 '(progn
24386 (add-hook 'imenu-after-jump-hook
24387 (lambda ()
24388 (if (derived-mode-p 'org-mode)
24389 (org-show-context 'org-goto))))))
24391 (defun org-link-display-format (link)
24392 "Replace a link with its the description.
24393 If there is no description, use the link target."
24394 (save-match-data
24395 (if (string-match org-bracket-link-analytic-regexp link)
24396 (replace-match (if (match-end 5)
24397 (match-string 5 link)
24398 (concat (match-string 1 link)
24399 (match-string 3 link)))
24400 nil t link)
24401 link)))
24403 (defun org-toggle-link-display ()
24404 "Toggle the literal or descriptive display of links."
24405 (interactive)
24406 (if org-descriptive-links
24407 (progn (org-remove-from-invisibility-spec '(org-link))
24408 (org-restart-font-lock)
24409 (setq org-descriptive-links nil))
24410 (progn (add-to-invisibility-spec '(org-link))
24411 (org-restart-font-lock)
24412 (setq org-descriptive-links t))))
24414 ;; Speedbar support
24416 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24417 "Overlay marking the agenda restriction line in speedbar.")
24418 (overlay-put org-speedbar-restriction-lock-overlay
24419 'face 'org-agenda-restriction-lock)
24420 (overlay-put org-speedbar-restriction-lock-overlay
24421 'help-echo "Agendas are currently limited to this item.")
24422 (org-detach-overlay org-speedbar-restriction-lock-overlay)
24424 (defun org-speedbar-set-agenda-restriction ()
24425 "Restrict future agenda commands to the location at point in speedbar.
24426 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
24427 (interactive)
24428 (require 'org-agenda)
24429 (let (p m tp np dir txt)
24430 (cond
24431 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24432 'org-imenu t))
24433 (setq m (get-text-property p 'org-imenu-marker))
24434 (with-current-buffer (marker-buffer m)
24435 (goto-char m)
24436 (org-agenda-set-restriction-lock 'subtree)))
24437 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24438 'speedbar-function 'speedbar-find-file))
24439 (setq tp (previous-single-property-change
24440 (1+ p) 'speedbar-function)
24441 np (next-single-property-change
24442 tp 'speedbar-function)
24443 dir (speedbar-line-directory)
24444 txt (buffer-substring-no-properties (or tp (point-min))
24445 (or np (point-max))))
24446 (with-current-buffer (find-file-noselect
24447 (let ((default-directory dir))
24448 (expand-file-name txt)))
24449 (unless (derived-mode-p 'org-mode)
24450 (user-error "Cannot restrict to non-Org-mode file"))
24451 (org-agenda-set-restriction-lock 'file)))
24452 (t (user-error "Don't know how to restrict Org-mode's agenda")))
24453 (move-overlay org-speedbar-restriction-lock-overlay
24454 (point-at-bol) (point-at-eol))
24455 (setq current-prefix-arg nil)
24456 (org-agenda-maybe-redo)))
24458 (defvar speedbar-file-key-map)
24459 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24460 (eval-after-load "speedbar"
24461 '(progn
24462 (speedbar-add-supported-extension ".org")
24463 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24464 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24465 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24466 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24467 (add-hook 'speedbar-visiting-tag-hook
24468 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24470 ;;; Fixes and Hacks for problems with other packages
24472 (defun org-mode-flyspell-verify ()
24473 "Function used for `flyspell-generic-check-word-predicate'."
24474 (if (org-at-heading-p)
24475 ;; At a headline or an inlinetask, check title only. This is
24476 ;; faster than relying on `org-element-at-point'.
24477 (and (save-excursion (beginning-of-line)
24478 (and (let ((case-fold-search t))
24479 (not (looking-at "\\*+ END[ \t]*$")))
24480 (looking-at org-complex-heading-regexp)))
24481 (match-beginning 4)
24482 (>= (point) (match-beginning 4))
24483 (or (not (match-beginning 5))
24484 (< (point) (match-beginning 5))))
24485 (let* ((element (org-element-at-point))
24486 (post-affiliated (org-element-property :post-affiliated element))
24487 (object-check
24488 (function
24489 ;; Non-nil if checks can be done for object at point.
24490 (lambda ()
24491 (let ((object (save-excursion
24492 (when (org-looking-at-p "\\>") (backward-char))
24493 (org-element-context element))))
24494 (case (org-element-type object)
24495 ;; Prevent checks in links due to keybinding conflict
24496 ;; with Flyspell.
24497 ((code entity export-snippet inline-babel-call
24498 inline-src-block line-break latex-fragment link macro
24499 statistics-cookie target timestamp verbatim)
24500 nil)
24501 (footnote-reference
24502 ;; Only in inline footnotes, within the definition.
24503 (and (eq (org-element-property :type object) 'inline)
24504 (< (save-excursion
24505 (goto-char (org-element-property :begin object))
24506 (search-forward ":" nil t 2))
24507 (point))))
24508 (otherwise t)))))))
24509 (cond
24510 ;; Ignore checks in all affiliated keywords but captions.
24511 ((and post-affiliated (< (point) post-affiliated))
24512 (and (save-excursion
24513 (beginning-of-line)
24514 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
24515 (> (point) (match-end 0))
24516 (funcall object-check)))
24517 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
24518 ((and org-log-into-drawer
24519 (let ((log (or (org-string-nw-p org-log-into-drawer) "LOGBOOK"))
24520 (parent element))
24521 (while (and parent (not (eq (org-element-type parent) 'drawer)))
24522 (setq parent (org-element-property :parent parent)))
24523 (and parent
24524 (eq (compare-strings
24525 log nil nil
24526 (org-element-property :drawer-name parent) nil nil t)
24527 t))))
24528 nil)
24530 (case (org-element-type element)
24531 ((comment quote-section) t)
24532 (comment-block
24533 ;; Allow checks between block markers, not on them.
24534 (and (> (line-beginning-position)
24535 (org-element-property :post-affiliated element))
24536 (save-excursion
24537 (end-of-line)
24538 (skip-chars-forward " \r\t\n")
24539 (< (point) (org-element-property :end element)))))
24540 ;; Arbitrary list of keywords where checks are meaningful.
24541 ;; Make sure point is on the value part of the element.
24542 (keyword
24543 (and (member (org-element-property :key element)
24544 '("DESCRIPTION" "TITLE"))
24545 (< (save-excursion
24546 (beginning-of-line) (search-forward ":") (point))
24547 (point))))
24548 ;; Check is globally allowed in paragraphs verse blocks and
24549 ;; table rows (after affiliated keywords) but some objects
24550 ;; must not be affected.
24551 ((paragraph table-row verse-block)
24552 (and (>= (point) (org-element-property :contents-begin element))
24553 (< (point) (org-element-property :contents-end element))
24554 (funcall object-check)))))))))
24555 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
24557 (defun org-remove-flyspell-overlays-in (beg end)
24558 "Remove flyspell overlays in region."
24559 (and (org-bound-and-true-p flyspell-mode)
24560 (fboundp 'flyspell-delete-region-overlays)
24561 (flyspell-delete-region-overlays beg end)))
24563 (defvar flyspell-delayed-commands)
24564 (eval-after-load "flyspell"
24565 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
24567 ;; Make `bookmark-jump' shows the jump location if it was hidden.
24568 (eval-after-load "bookmark"
24569 '(if (boundp 'bookmark-after-jump-hook)
24570 ;; We can use the hook
24571 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
24572 ;; Hook not available, use advice
24573 (defadvice bookmark-jump (after org-make-visible activate)
24574 "Make the position visible."
24575 (org-bookmark-jump-unhide))))
24577 ;; Make sure saveplace shows the location if it was hidden
24578 (eval-after-load "saveplace"
24579 '(defadvice save-place-find-file-hook (after org-make-visible activate)
24580 "Make the position visible."
24581 (org-bookmark-jump-unhide)))
24583 ;; Make sure ecb shows the location if it was hidden
24584 (eval-after-load "ecb"
24585 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
24586 "Make hierarchy visible when jumping into location from ECB tree buffer."
24587 (if (derived-mode-p 'org-mode)
24588 (org-show-context))))
24590 (defun org-bookmark-jump-unhide ()
24591 "Unhide the current position, to show the bookmark location."
24592 (and (derived-mode-p 'org-mode)
24593 (or (outline-invisible-p)
24594 (save-excursion (goto-char (max (point-min) (1- (point))))
24595 (outline-invisible-p)))
24596 (org-show-context 'bookmark-jump)))
24598 (defun org-mark-jump-unhide ()
24599 "Make the point visible with `org-show-context' after jumping to the mark."
24600 (when (and (derived-mode-p 'org-mode)
24601 (outline-invisible-p))
24602 (org-show-context 'mark-goto)))
24604 (eval-after-load "simple"
24605 '(defadvice pop-to-mark-command (after org-make-visible activate)
24606 "Make the point visible with `org-show-context'."
24607 (org-mark-jump-unhide)))
24609 (eval-after-load "simple"
24610 '(defadvice exchange-point-and-mark (after org-make-visible activate)
24611 "Make the point visible with `org-show-context'."
24612 (org-mark-jump-unhide)))
24614 (eval-after-load "simple"
24615 '(defadvice pop-global-mark (after org-make-visible activate)
24616 "Make the point visible with `org-show-context'."
24617 (org-mark-jump-unhide)))
24619 ;; Make session.el ignore our circular variable
24620 (defvar session-globals-exclude)
24621 (eval-after-load "session"
24622 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24624 ;;;; Finish up
24626 (provide 'org)
24628 (run-hooks 'org-load-hook)
24630 ;;; org.el ends here