Merge branch 'maint'
[org-mode.git] / lisp / org.el
blobe245d6d4b95797b1661ed35cc04ed7d759ad63ae
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 (load "org-loaddefs.el" t t t)
82 (require 'org-macs)
83 (require 'org-compat)
85 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
86 ;; some places -- e.g. see the macro `org-with-limited-levels'.
88 ;; In Org buffers, the value of `outline-regexp' is that of
89 ;; `org-outline-regexp'. The only function still directly relying on
90 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
91 ;; job when `orgstruct-mode' is active.
92 (defvar org-outline-regexp "\\*+ "
93 "Regexp to match Org headlines.")
95 (defvar org-outline-regexp-bol "^\\*+ "
96 "Regexp to match Org headlines.
97 This is similar to `org-outline-regexp' but additionally makes
98 sure that we are at the beginning of the line.")
100 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
101 "Matches a headline, putting stars and text into groups.
102 Stars are put in group 1 and the trimmed body in group 2.")
104 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
105 (unless (boundp 'calendar-view-holidays-initially-flag)
106 (org-defvaralias 'calendar-view-holidays-initially-flag
107 'view-calendar-holidays-initially))
108 (unless (boundp 'calendar-view-diary-initially-flag)
109 (org-defvaralias 'calendar-view-diary-initially-flag
110 'view-diary-entries-initially))
111 (unless (boundp 'diary-fancy-buffer)
112 (org-defvaralias 'diary-fancy-buffer 'fancy-diary-buffer))
114 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
115 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
116 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
117 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
118 (declare-function org-clocktable-shift "org-clock" (dir n))
119 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
120 (declare-function org-clock-update-time-maybe "org-clock" ())
121 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
122 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
123 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
124 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
126 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
127 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body))
128 (declare-function orgtbl-mode "org-table" (&optional arg))
129 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
130 (declare-function org-beamer-mode "ox-beamer" ())
131 (declare-function org-table-blank-field "org-table" ())
132 (declare-function org-table-edit-field "org-table" (arg))
133 (declare-function org-table-insert-row "org-table" (&optional arg))
134 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
135 (declare-function org-table-set-constants "org-table" ())
136 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
137 (declare-function org-id-get-create "org-id" (&optional force))
138 (declare-function org-add-archive-files "org-archive" (files))
139 (declare-function org-id-find-id-file "org-id" (id))
140 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
141 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
142 (declare-function org-agenda-redo "org-agenda" (&optional all))
143 (declare-function org-table-align "org-table" ())
144 (declare-function org-table-begin "org-table" (&optional table-type))
145 (declare-function org-table-end "org-table" (&optional table-type))
146 (declare-function org-table-paste-rectangle "org-table" ())
147 (declare-function org-table-maybe-eval-formula "org-table" ())
148 (declare-function org-table-maybe-recalculate-line "org-table" ())
150 (declare-function org-element--parse-objects "org-element"
151 (beg end acc restriction))
152 (declare-function org-element-at-point "org-element" ())
153 (declare-function org-element-cache-reset "org-element" (&optional all))
154 (declare-function org-element-contents "org-element" (element))
155 (declare-function org-element-context "org-element" (&optional element))
156 (declare-function org-element-interpret-data "org-element"
157 (data &optional parent))
158 (declare-function org-element-map "org-element"
159 (data types fun &optional info first-match no-recursion))
160 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
161 (declare-function org-element-parse-buffer "org-element"
162 (&optional granularity visible-only))
163 (declare-function org-element-property "org-element" (property element))
164 (declare-function org-element-put-property "org-element"
165 (element property value))
166 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
167 (declare-function org-element--parse-objects "org-element"
168 (beg end acc restriction))
169 (declare-function org-element-parse-buffer "org-element"
170 (&optional granularity visible-only))
171 (declare-function org-element-restriction "org-element" (element))
172 (declare-function org-element-type "org-element" (element))
174 (defsubst org-uniquify (list)
175 "Non-destructively remove duplicate elements from LIST."
176 (let ((res (copy-sequence list))) (delete-dups res)))
178 ;; load languages based on value of `org-babel-load-languages'
179 (defvar org-babel-load-languages)
181 ;;;###autoload
182 (defun org-babel-do-load-languages (sym value)
183 "Load the languages defined in `org-babel-load-languages'."
184 (set-default sym value)
185 (mapc (lambda (pair)
186 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
187 (if active
188 (progn
189 (require (intern (concat "ob-" lang))))
190 (progn
191 (funcall 'fmakunbound
192 (intern (concat "org-babel-execute:" lang)))
193 (funcall 'fmakunbound
194 (intern (concat "org-babel-expand-body:" lang)))))))
195 org-babel-load-languages))
197 ;;;###autoload
198 (defun org-babel-load-file (file &optional compile)
199 "Load Emacs Lisp source code blocks in the Org-mode FILE.
200 This function exports the source code using `org-babel-tangle'
201 and then loads the resulting file using `load-file'. With prefix
202 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
203 file to byte-code before it is loaded."
204 (interactive "fFile to load: \nP")
205 (let* ((age (lambda (file)
206 (float-time
207 (time-subtract (current-time)
208 (nth 5 (or (file-attributes (file-truename file))
209 (file-attributes file)))))))
210 (base-name (file-name-sans-extension file))
211 (exported-file (concat base-name ".el")))
212 ;; tangle if the org-mode file is newer than the elisp file
213 (unless (and (file-exists-p exported-file)
214 (> (funcall age file) (funcall age exported-file)))
215 (setq exported-file
216 (car (org-babel-tangle-file file exported-file "emacs-lisp"))))
217 (message "%s %s"
218 (if compile
219 (progn (byte-compile-file exported-file 'load)
220 "Compiled and loaded")
221 (progn (load-file exported-file) "Loaded"))
222 exported-file)))
224 (defcustom org-babel-load-languages '((emacs-lisp . t))
225 "Languages which can be evaluated in Org-mode buffers.
226 This list can be used to load support for any of the languages
227 below, note that each language will depend on a different set of
228 system executables and/or Emacs modes. When a language is
229 \"loaded\", then code blocks in that language can be evaluated
230 with `org-babel-execute-src-block' bound by default to C-c
231 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
232 be set to remove code block evaluation from the C-c C-c
233 keybinding. By default only Emacs Lisp (which has no
234 requirements) is loaded."
235 :group 'org-babel
236 :set 'org-babel-do-load-languages
237 :version "24.1"
238 :type '(alist :tag "Babel Languages"
239 :key-type
240 (choice
241 (const :tag "Awk" awk)
242 (const :tag "C" C)
243 (const :tag "R" R)
244 (const :tag "Asymptote" asymptote)
245 (const :tag "Calc" calc)
246 (const :tag "Clojure" clojure)
247 (const :tag "CSS" css)
248 (const :tag "Ditaa" ditaa)
249 (const :tag "Dot" dot)
250 (const :tag "Emacs Lisp" emacs-lisp)
251 (const :tag "Fortran" fortran)
252 (const :tag "Gnuplot" gnuplot)
253 (const :tag "Haskell" haskell)
254 (const :tag "IO" io)
255 (const :tag "J" J)
256 (const :tag "Java" java)
257 (const :tag "Javascript" js)
258 (const :tag "LaTeX" latex)
259 (const :tag "Ledger" ledger)
260 (const :tag "Lilypond" lilypond)
261 (const :tag "Lisp" lisp)
262 (const :tag "Makefile" makefile)
263 (const :tag "Maxima" maxima)
264 (const :tag "Matlab" matlab)
265 (const :tag "Mscgen" mscgen)
266 (const :tag "Ocaml" ocaml)
267 (const :tag "Octave" octave)
268 (const :tag "Org" org)
269 (const :tag "Perl" perl)
270 (const :tag "Pico Lisp" picolisp)
271 (const :tag "PlantUML" plantuml)
272 (const :tag "Python" python)
273 (const :tag "Ruby" ruby)
274 (const :tag "Sass" sass)
275 (const :tag "Scala" scala)
276 (const :tag "Scheme" scheme)
277 (const :tag "Screen" screen)
278 (const :tag "Shell Script" shell)
279 (const :tag "Shen" shen)
280 (const :tag "Sql" sql)
281 (const :tag "Sqlite" sqlite)
282 (const :tag "ebnf2ps" ebnf2ps))
283 :value-type (boolean :tag "Activate" :value t)))
285 ;;;; Customization variables
286 (defcustom org-clone-delete-id nil
287 "Remove ID property of clones of a subtree.
288 When non-nil, clones of a subtree don't inherit the ID property.
289 Otherwise they inherit the ID property with a new unique
290 identifier."
291 :type 'boolean
292 :version "24.1"
293 :group 'org-id)
295 ;;; Version
296 (org-check-version)
298 ;;;###autoload
299 (defun org-version (&optional here full message)
300 "Show the org-mode version.
301 Interactively, or when MESSAGE is non-nil, show it in echo area.
302 With prefix argument, or when HERE is non-nil, insert it at point.
303 In non-interactive uses, a reduced version string is output unless
304 FULL is given."
305 (interactive (list current-prefix-arg t (not current-prefix-arg)))
306 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
307 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
308 (load-suffixes (list ".el"))
309 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
310 (org-trash (or
311 (and (fboundp 'org-release) (fboundp 'org-git-version))
312 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
313 (load-suffixes save-load-suffixes)
314 (org-version (org-release))
315 (git-version (org-git-version))
316 (version (format "Org-mode version %s (%s @ %s)"
317 org-version
318 git-version
319 (if org-install-dir
320 (if (string= org-dir org-install-dir)
321 org-install-dir
322 (concat "mixed installation! " org-install-dir " and " org-dir))
323 "org-loaddefs.el can not be found!")))
324 (version1 (if full version org-version)))
325 (when here (insert version1))
326 (when message (message "%s" version1))
327 version1))
329 (defconst org-version (org-version))
332 ;;; Syntax Constants
334 ;;;; Block
336 (defconst org-block-regexp
337 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
338 "Regular expression for hiding blocks.")
340 (defconst org-dblock-start-re
341 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
342 "Matches the start line of a dynamic block, with parameters.")
344 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
345 "Matches the end of a dynamic block.")
347 ;;;; Clock and Planning
349 (defconst org-clock-string "CLOCK:"
350 "String used as prefix for timestamps clocking work hours on an item.")
352 (defconst org-closed-string "CLOSED:"
353 "String used as the prefix for timestamps logging closing a TODO entry.")
355 (defconst org-deadline-string "DEADLINE:"
356 "String to mark deadline entries.
357 A deadline is this string, followed by a time stamp. Should be a word,
358 terminated by a colon. You can insert a schedule keyword and
359 a timestamp with \\[org-deadline].")
361 (defconst org-scheduled-string "SCHEDULED:"
362 "String to mark scheduled TODO entries.
363 A schedule is this string, followed by a time stamp. Should be a word,
364 terminated by a colon. You can insert a schedule keyword and
365 a timestamp with \\[org-schedule].")
367 (defconst org-planning-or-clock-line-re
368 (concat "^[ \t]*"
369 (regexp-opt
370 (list org-clock-string org-closed-string org-deadline-string
371 org-scheduled-string)
373 "Matches a line with planning or clock info.
374 Matched keyword is in group 1.")
376 ;;;; Drawer
378 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
379 "Matches first or last line of a hidden block.
380 Group 1 contains drawer's name or \"END\".")
382 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
383 "Regular expression matching the first line of a property drawer.")
385 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
386 "Regular expression matching the last line of a property drawer.")
388 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
389 "Regular expression matching the first line of a clock drawer.")
391 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
392 "Regular expression matching the last line of a clock drawer.")
394 (defconst org-property-drawer-re
395 (concat "\\(" org-property-start-re "\\)[^\000]*?\\("
396 org-property-end-re "\\)\n?")
397 "Matches an entire property drawer.")
399 (defconst org-clock-drawer-re
400 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
401 org-clock-drawer-end-re "\\)\n?")
402 "Matches an entire clock drawer.")
404 ;;;; Headline
406 (defconst org-heading-keyword-regexp-format
407 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
408 "Printf format for a regexp matching a headline with some keyword.
409 This regexp will match the headline of any node which has the
410 exact keyword that is put into the format. The keyword isn't in
411 any group by default, but the stars and the body are.")
413 (defconst org-heading-keyword-maybe-regexp-format
414 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
415 "Printf format for a regexp matching a headline, possibly with some keyword.
416 This regexp can match any headline with the specified keyword, or
417 without a keyword. The keyword isn't in any group by default,
418 but the stars and the body are.")
420 (defconst org-archive-tag "ARCHIVE"
421 "The tag that marks a subtree as archived.
422 An archived subtree does not open during visibility cycling, and does
423 not contribute to the agenda listings.")
425 (defconst org-comment-string "COMMENT"
426 "Entries starting with this keyword will never be exported.
427 An entry can be toggled between COMMENT and normal with
428 \\[org-toggle-comment].")
431 ;;;; LaTeX Environments and Fragments
433 (defconst org-latex-regexps
434 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
435 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
436 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
437 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
438 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
439 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
440 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
441 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
442 "Regular expressions for matching embedded LaTeX.")
444 ;;;; Node Property
446 (defconst org-effort-property "Effort"
447 "The property that is being used to keep track of effort estimates.
448 Effort estimates given in this property need to have the format H:MM.")
450 ;;;; Table
452 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
453 "Detect an org-type or table-type table.")
455 (defconst org-table-line-regexp "^[ \t]*|"
456 "Detect an org-type table line.")
458 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
459 "Detect an org-type table line.")
461 (defconst org-table-hline-regexp "^[ \t]*|-"
462 "Detect an org-type table hline.")
464 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
465 "Detect a table-type table hline.")
467 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
468 "Detect the first line outside a table when searching from within it.
469 This works for both table types.")
471 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
472 "Detect a #+TBLFM line.")
474 ;;;; Timestamp
476 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
477 "Regular expression for fast time stamp matching.")
479 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
480 "Regular expression for fast time stamp matching.")
482 (defconst org-ts-regexp0
483 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
484 "Regular expression matching time strings for analysis.
485 This one does not require the space after the date, so it can be used
486 on a string that terminates immediately after the date.")
488 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
489 "Regular expression matching time strings for analysis.")
491 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
492 "Regular expression matching time stamps, with groups.")
494 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
495 "Regular expression matching time stamps (also [..]), with groups.")
497 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
498 "Regular expression matching a time stamp range.")
500 (defconst org-tr-regexp-both
501 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
502 "Regular expression matching a time stamp range.")
504 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
505 org-ts-regexp "\\)?")
506 "Regular expression matching a time stamp or time stamp range.")
508 (defconst org-tsr-regexp-both
509 (concat org-ts-regexp-both "\\(--?-?"
510 org-ts-regexp-both "\\)?")
511 "Regular expression matching a time stamp or time stamp range.
512 The time stamps may be either active or inactive.")
514 (defconst org-repeat-re
515 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
516 "Regular expression for specifying repeated events.
517 After a match, group 1 contains the repeat expression.")
519 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
520 "Formats for `format-time-string' which are used for time stamps.")
523 ;;; The custom variables
525 (defgroup org nil
526 "Outline-based notes management and organizer."
527 :tag "Org"
528 :group 'outlines
529 :group 'calendar)
531 (defcustom org-mode-hook nil
532 "Mode hook for Org-mode, run after the mode was turned on."
533 :group 'org
534 :type 'hook)
536 (defcustom org-load-hook nil
537 "Hook that is run after org.el has been loaded."
538 :group 'org
539 :type 'hook)
541 (defcustom org-log-buffer-setup-hook nil
542 "Hook that is run after an Org log buffer is created."
543 :group 'org
544 :version "24.1"
545 :type 'hook)
547 (defvar org-modules) ; defined below
548 (defvar org-modules-loaded nil
549 "Have the modules been loaded already?")
551 (defun org-load-modules-maybe (&optional force)
552 "Load all extensions listed in `org-modules'."
553 (when (or force (not org-modules-loaded))
554 (mapc (lambda (ext)
555 (condition-case nil (require ext)
556 (error (message "Problems while trying to load feature `%s'" ext))))
557 org-modules)
558 (setq org-modules-loaded t)))
560 (defun org-set-modules (var value)
561 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
562 (set var value)
563 (when (featurep 'org)
564 (org-load-modules-maybe 'force)
565 (org-element-cache-reset 'all)))
567 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
568 "Modules that should always be loaded together with org.el.
570 If a description starts with <C>, the file is not part of Emacs
571 and loading it will require that you have downloaded and properly
572 installed the Org mode distribution.
574 You can also use this system to load external packages (i.e. neither Org
575 core modules, nor modules from the CONTRIB directory). Just add symbols
576 to the end of the list. If the package is called org-xyz.el, then you need
577 to add the symbol `xyz', and the package must have a call to:
579 \(provide 'org-xyz)
581 For export specific modules, see also `org-export-backends'."
582 :group 'org
583 :set 'org-set-modules
584 :version "24.4"
585 :package-version '(Org . "8.0")
586 :type
587 '(set :greedy t
588 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
589 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
590 (const :tag " crypt: Encryption of subtrees" org-crypt)
591 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
592 (const :tag " docview: Links to doc-view buffers" org-docview)
593 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
594 (const :tag " habit: Track your consistency with habits" org-habit)
595 (const :tag " id: Global IDs for identifying entries" org-id)
596 (const :tag " info: Links to Info nodes" org-info)
597 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
598 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
599 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
600 (const :tag " mouse: Additional mouse support" org-mouse)
601 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
602 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
603 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
605 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
606 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
607 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
608 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
609 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
610 (const :tag "C collector: Collect properties into tables" org-collector)
611 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
612 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
613 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
614 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
615 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
616 (const :tag "C eval: Include command output as text" org-eval)
617 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
618 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
619 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
620 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
621 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
622 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
623 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
624 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
625 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
626 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
627 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
628 (const :tag "C mew: Links to Mew folders/messages" org-mew)
629 (const :tag "C mtags: Support for muse-like tags" org-mtags)
630 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
631 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
632 (const :tag "C registry: A registry for Org-mode links" org-registry)
633 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
634 (const :tag "C secretary: Team management with org-mode" org-secretary)
635 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
636 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
637 (const :tag "C track: Keep up with Org-mode development" org-track)
638 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
639 (const :tag "C vm: Links to VM folders/messages" org-vm)
640 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
641 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
642 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
644 (defvar org-export--registered-backends) ; From ox.el.
645 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
646 (declare-function org-export-backend-name "ox" (backend))
647 (defcustom org-export-backends '(ascii html icalendar latex)
648 "List of export back-ends that should be always available.
650 If a description starts with <C>, the file is not part of Emacs
651 and loading it will require that you have downloaded and properly
652 installed the Org mode distribution.
654 Unlike to `org-modules', libraries in this list will not be
655 loaded along with Org, but only once the export framework is
656 needed.
658 This variable needs to be set before org.el is loaded. If you
659 need to make a change while Emacs is running, use the customize
660 interface or run the following code, where VAL stands for the new
661 value of the variable, after updating it:
663 \(progn
664 \(setq org-export--registered-backends
665 \(org-remove-if-not
666 \(lambda (backend)
667 \(let ((name (org-export-backend-name backend)))
668 \(or (memq name val)
669 \(catch 'parentp
670 \(dolist (b val)
671 \(and (org-export-derived-backend-p b name)
672 \(throw 'parentp t)))))))
673 org-export--registered-backends))
674 \(let ((new-list (mapcar 'org-export-backend-name
675 org-export--registered-backends)))
676 \(dolist (backend val)
677 \(cond
678 \((not (load (format \"ox-%s\" backend) t t))
679 \(message \"Problems while trying to load export back-end `%s'\"
680 backend))
681 \((not (memq backend new-list)) (push backend new-list))))
682 \(set-default 'org-export-backends new-list)))
684 Adding a back-end to this list will also pull the back-end it
685 depends on, if any."
686 :group 'org
687 :group 'org-export
688 :version "24.4"
689 :package-version '(Org . "8.0")
690 :initialize 'custom-initialize-set
691 :set (lambda (var val)
692 (if (not (featurep 'ox)) (set-default var val)
693 ;; Any back-end not required anymore (not present in VAL and not
694 ;; a parent of any back-end in the new value) is removed from the
695 ;; list of registered back-ends.
696 (setq org-export--registered-backends
697 (org-remove-if-not
698 (lambda (backend)
699 (let ((name (org-export-backend-name backend)))
700 (or (memq name val)
701 (catch 'parentp
702 (dolist (b val)
703 (and (org-export-derived-backend-p b name)
704 (throw 'parentp t)))))))
705 org-export--registered-backends))
706 ;; Now build NEW-LIST of both new back-ends and required
707 ;; parents.
708 (let ((new-list (mapcar 'org-export-backend-name
709 org-export--registered-backends)))
710 (dolist (backend val)
711 (cond
712 ((not (load (format "ox-%s" backend) t t))
713 (message "Problems while trying to load export back-end `%s'"
714 backend))
715 ((not (memq backend new-list)) (push backend new-list))))
716 ;; Set VAR to that list with fixed dependencies.
717 (set-default var new-list))))
718 :type '(set :greedy t
719 (const :tag " ascii Export buffer to ASCII format" ascii)
720 (const :tag " beamer Export buffer to Beamer presentation" beamer)
721 (const :tag " html Export buffer to HTML format" html)
722 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
723 (const :tag " latex Export buffer to LaTeX format" latex)
724 (const :tag " man Export buffer to MAN format" man)
725 (const :tag " md Export buffer to Markdown format" md)
726 (const :tag " odt Export buffer to ODT format" odt)
727 (const :tag " org Export buffer to Org format" org)
728 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
729 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
730 (const :tag "C deck Export buffer to deck.js presentations" deck)
731 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
732 (const :tag "C groff Export buffer to Groff format" groff)
733 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
734 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
735 (const :tag "C s5 Export buffer to s5 presentations" s5)
736 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
738 (eval-after-load 'ox
739 '(mapc
740 (lambda (backend)
741 (condition-case nil (require (intern (format "ox-%s" backend)))
742 (error (message "Problems while trying to load export back-end `%s'"
743 backend))))
744 org-export-backends))
746 (defcustom org-support-shift-select nil
747 "Non-nil means make shift-cursor commands select text when possible.
749 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
750 start selecting a region, or enlarge regions started in this way.
751 In Org-mode, in special contexts, these same keys are used for
752 other purposes, important enough to compete with shift selection.
753 Org tries to balance these needs by supporting `shift-select-mode'
754 outside these special contexts, under control of this variable.
756 The default of this variable is nil, to avoid confusing behavior. Shifted
757 cursor keys will then execute Org commands in the following contexts:
758 - on a headline, changing TODO state (left/right) and priority (up/down)
759 - on a time stamp, changing the time
760 - in a plain list item, changing the bullet type
761 - in a property definition line, switching between allowed values
762 - in the BEGIN line of a clock table (changing the time block).
763 Outside these contexts, the commands will throw an error.
765 When this variable is t and the cursor is not in a special
766 context, Org-mode will support shift-selection for making and
767 enlarging regions. To make this more effective, the bullet
768 cycling will no longer happen anywhere in an item line, but only
769 if the cursor is exactly on the bullet.
771 If you set this variable to the symbol `always', then the keys
772 will not be special in headlines, property lines, and item lines,
773 to make shift selection work there as well. If this is what you
774 want, you can use the following alternative commands: `C-c C-t'
775 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
776 can be used to switch TODO sets, `C-c -' to cycle item bullet
777 types, and properties can be edited by hand or in column view.
779 However, when the cursor is on a timestamp, shift-cursor commands
780 will still edit the time stamp - this is just too good to give up.
782 XEmacs user should have this variable set to nil, because
783 `shift-select-mode' is in Emacs 23 or later only."
784 :group 'org
785 :type '(choice
786 (const :tag "Never" nil)
787 (const :tag "When outside special context" t)
788 (const :tag "Everywhere except timestamps" always)))
790 (defcustom org-loop-over-headlines-in-active-region nil
791 "Shall some commands act upon headlines in the active region?
793 When set to `t', some commands will be performed in all headlines
794 within the active region.
796 When set to `start-level', some commands will be performed in all
797 headlines within the active region, provided that these headlines
798 are of the same level than the first one.
800 When set to a string, those commands will be performed on the
801 matching headlines within the active region. Such string must be
802 a tags/property/todo match as it is used in the agenda tags view.
804 The list of commands is: `org-schedule', `org-deadline',
805 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
806 `org-archive-to-archive-sibling'. The archiving commands skip
807 already archived entries."
808 :type '(choice (const :tag "Don't loop" nil)
809 (const :tag "All headlines in active region" t)
810 (const :tag "In active region, headlines at the same level than the first one" start-level)
811 (string :tag "Tags/Property/Todo matcher"))
812 :version "24.1"
813 :group 'org-todo
814 :group 'org-archive)
816 (defgroup org-startup nil
817 "Options concerning startup of Org-mode."
818 :tag "Org Startup"
819 :group 'org)
821 (defcustom org-startup-folded t
822 "Non-nil means entering Org-mode will switch to OVERVIEW.
823 This can also be configured on a per-file basis by adding one of
824 the following lines anywhere in the buffer:
826 #+STARTUP: fold (or `overview', this is equivalent)
827 #+STARTUP: nofold (or `showall', this is equivalent)
828 #+STARTUP: content
829 #+STARTUP: showeverything
831 By default, this option is ignored when Org opens agenda files
832 for the first time. If you want the agenda to honor the startup
833 option, set `org-agenda-inhibit-startup' to nil."
834 :group 'org-startup
835 :type '(choice
836 (const :tag "nofold: show all" nil)
837 (const :tag "fold: overview" t)
838 (const :tag "content: all headlines" content)
839 (const :tag "show everything, even drawers" showeverything)))
841 (defcustom org-startup-truncated t
842 "Non-nil means entering Org-mode will set `truncate-lines'.
843 This is useful since some lines containing links can be very long and
844 uninteresting. Also tables look terrible when wrapped."
845 :group 'org-startup
846 :type 'boolean)
848 (defcustom org-startup-indented nil
849 "Non-nil means turn on `org-indent-mode' on startup.
850 This can also be configured on a per-file basis by adding one of
851 the following lines anywhere in the buffer:
853 #+STARTUP: indent
854 #+STARTUP: noindent"
855 :group 'org-structure
856 :type '(choice
857 (const :tag "Not" nil)
858 (const :tag "Globally (slow on startup in large files)" t)))
860 (defcustom org-use-sub-superscripts t
861 "Non-nil means interpret \"_\" and \"^\" for display.
863 If you want to control how Org exports those characters, see
864 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
865 used to be an alias for `org-export-with-sub-superscripts' in
866 Org <8.0, it is not anymore.
868 When this option is turned on, you can use TeX-like syntax for
869 sub- and superscripts within the buffer. Several characters after
870 \"_\" or \"^\" will be considered as a single item - so grouping
871 with {} is normally not needed. For example, the following things
872 will be parsed as single sub- or superscripts:
874 10^24 or 10^tau several digits will be considered 1 item.
875 10^-12 or 10^-tau a leading sign with digits or a word
876 x^2-y^3 will be read as x^2 - y^3, because items are
877 terminated by almost any nonword/nondigit char.
878 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
880 Still, ambiguity is possible. So when in doubt, use {} to enclose
881 the sub/superscript. If you set this variable to the symbol `{}',
882 the braces are *required* in order to trigger interpretations as
883 sub/superscript. This can be helpful in documents that need \"_\"
884 frequently in plain text."
885 :group 'org-startup
886 :version "24.4"
887 :package-version '(Org . "8.0")
888 :type '(choice
889 (const :tag "Always interpret" t)
890 (const :tag "Only with braces" {})
891 (const :tag "Never interpret" nil)))
893 (defcustom org-startup-with-beamer-mode nil
894 "Non-nil means turn on `org-beamer-mode' on startup.
895 This can also be configured on a per-file basis by adding one of
896 the following lines anywhere in the buffer:
898 #+STARTUP: beamer"
899 :group 'org-startup
900 :version "24.1"
901 :type 'boolean)
903 (defcustom org-startup-align-all-tables nil
904 "Non-nil means align all tables when visiting a file.
905 This is useful when the column width in tables is forced with <N> cookies
906 in table fields. Such tables will look correct only after the first re-align.
907 This can also be configured on a per-file basis by adding one of
908 the following lines anywhere in the buffer:
909 #+STARTUP: align
910 #+STARTUP: noalign"
911 :group 'org-startup
912 :type 'boolean)
914 (defcustom org-startup-with-inline-images nil
915 "Non-nil means show inline images when loading a new Org file.
916 This can also be configured on a per-file basis by adding one of
917 the following lines anywhere in the buffer:
918 #+STARTUP: inlineimages
919 #+STARTUP: noinlineimages"
920 :group 'org-startup
921 :version "24.1"
922 :type 'boolean)
924 (defcustom org-startup-with-latex-preview nil
925 "Non-nil means preview LaTeX fragments when loading a new Org file.
927 This can also be configured on a per-file basis by adding one of
928 the following lines anywhere in the buffer:
929 #+STARTUP: latexpreview
930 #+STARTUP: nolatexpreview"
931 :group 'org-startup
932 :version "24.4"
933 :package-version '(Org . "8.0")
934 :type 'boolean)
936 (defcustom org-insert-mode-line-in-empty-file nil
937 "Non-nil means insert the first line setting Org-mode in empty files.
938 When the function `org-mode' is called interactively in an empty file, this
939 normally means that the file name does not automatically trigger Org-mode.
940 To ensure that the file will always be in Org-mode in the future, a
941 line enforcing Org-mode will be inserted into the buffer, if this option
942 has been set."
943 :group 'org-startup
944 :type 'boolean)
946 (defcustom org-replace-disputed-keys nil
947 "Non-nil means use alternative key bindings for some keys.
948 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
949 These keys are also used by other packages like shift-selection-mode'
950 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
951 If you want to use Org-mode together with one of these other modes,
952 or more generally if you would like to move some Org-mode commands to
953 other keys, set this variable and configure the keys with the variable
954 `org-disputed-keys'.
956 This option is only relevant at load-time of Org-mode, and must be set
957 *before* org.el is loaded. Changing it requires a restart of Emacs to
958 become effective."
959 :group 'org-startup
960 :type 'boolean)
962 (defcustom org-use-extra-keys nil
963 "Non-nil means use extra key sequence definitions for certain commands.
964 This happens automatically if you run XEmacs or if `window-system'
965 is nil. This variable lets you do the same manually. You must
966 set it before loading org.
968 Example: on Carbon Emacs 22 running graphically, with an external
969 keyboard on a Powerbook, the default way of setting M-left might
970 not work for either Alt or ESC. Setting this variable will make
971 it work for ESC."
972 :group 'org-startup
973 :type 'boolean)
975 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
977 (defcustom org-disputed-keys
978 '(([(shift up)] . [(meta p)])
979 ([(shift down)] . [(meta n)])
980 ([(shift left)] . [(meta -)])
981 ([(shift right)] . [(meta +)])
982 ([(control shift right)] . [(meta shift +)])
983 ([(control shift left)] . [(meta shift -)]))
984 "Keys for which Org-mode and other modes compete.
985 This is an alist, cars are the default keys, second element specifies
986 the alternative to use when `org-replace-disputed-keys' is t.
988 Keys can be specified in any syntax supported by `define-key'.
989 The value of this option takes effect only at Org-mode's startup,
990 therefore you'll have to restart Emacs to apply it after changing."
991 :group 'org-startup
992 :type 'alist)
994 (defun org-key (key)
995 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
996 Or return the original if not disputed.
997 Also apply the translations defined in `org-xemacs-key-equivalents'."
998 (when org-replace-disputed-keys
999 (let* ((nkey (key-description key))
1000 (x (org-find-if (lambda (x)
1001 (equal (key-description (car x)) nkey))
1002 org-disputed-keys)))
1003 (setq key (if x (cdr x) key))))
1004 (when (featurep 'xemacs)
1005 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
1006 key)
1008 (defun org-find-if (predicate seq)
1009 (catch 'exit
1010 (while seq
1011 (if (funcall predicate (car seq))
1012 (throw 'exit (car seq))
1013 (pop seq)))))
1015 (defun org-defkey (keymap key def)
1016 "Define a key, possibly translated, as returned by `org-key'."
1017 (define-key keymap (org-key key) def))
1019 (defcustom org-ellipsis nil
1020 "The ellipsis to use in the Org-mode outline.
1021 When nil, just use the standard three dots.
1022 When a string, use that string instead.
1023 When a face, use the standard 3 dots, but with the specified face.
1024 The change affects only Org-mode (which will then use its own display table).
1025 Changing this requires executing `M-x org-mode RET' in a buffer to become
1026 effective."
1027 :group 'org-startup
1028 :type '(choice (const :tag "Default" nil)
1029 (face :tag "Face" :value org-warning)
1030 (string :tag "String" :value "...#")))
1032 (defvar org-display-table nil
1033 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
1035 (defgroup org-keywords nil
1036 "Keywords in Org-mode."
1037 :tag "Org Keywords"
1038 :group 'org)
1040 (defcustom org-closed-keep-when-no-todo nil
1041 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1042 :group 'org-todo
1043 :group 'org-keywords
1044 :version "24.4"
1045 :package-version '(Org . "8.0")
1046 :type 'boolean)
1048 (defgroup org-structure nil
1049 "Options concerning the general structure of Org-mode files."
1050 :tag "Org Structure"
1051 :group 'org)
1053 (defgroup org-reveal-location nil
1054 "Options about how to make context of a location visible."
1055 :tag "Org Reveal Location"
1056 :group 'org-structure)
1058 (defconst org-context-choice
1059 '(choice
1060 (const :tag "Always" t)
1061 (const :tag "Never" nil)
1062 (repeat :greedy t :tag "Individual contexts"
1063 (cons
1064 (choice :tag "Context"
1065 (const agenda)
1066 (const org-goto)
1067 (const occur-tree)
1068 (const tags-tree)
1069 (const link-search)
1070 (const mark-goto)
1071 (const bookmark-jump)
1072 (const isearch)
1073 (const default))
1074 (boolean))))
1075 "Contexts for the reveal options.")
1077 (defcustom org-show-hierarchy-above '((default . t))
1078 "Non-nil means show full hierarchy when revealing a location.
1079 Org-mode often shows locations in an org-mode file which might have
1080 been invisible before. When this is set, the hierarchy of headings
1081 above the exposed location is shown.
1082 Turning this off for example for sparse trees makes them very compact.
1083 Instead of t, this can also be an alist specifying this option for different
1084 contexts. Valid contexts are
1085 agenda when exposing an entry from the agenda
1086 org-goto when using the command `org-goto' on key C-c C-j
1087 occur-tree when using the command `org-occur' on key C-c /
1088 tags-tree when constructing a sparse tree based on tags matches
1089 link-search when exposing search matches associated with a link
1090 mark-goto when exposing the jump goal of a mark
1091 bookmark-jump when exposing a bookmark location
1092 isearch when exiting from an incremental search
1093 default default for all contexts not set explicitly"
1094 :group 'org-reveal-location
1095 :type org-context-choice)
1097 (defcustom org-show-following-heading '((default . nil))
1098 "Non-nil means show following heading when revealing a location.
1099 Org-mode often shows locations in an org-mode file which might have
1100 been invisible before. When this is set, the heading following the
1101 match is shown.
1102 Turning this off for example for sparse trees makes them very compact,
1103 but makes it harder to edit the location of the match. In such a case,
1104 use the command \\[org-reveal] to show more context.
1105 Instead of t, this can also be an alist specifying this option for different
1106 contexts. See `org-show-hierarchy-above' for valid contexts."
1107 :group 'org-reveal-location
1108 :type org-context-choice)
1110 (defcustom org-show-siblings '((default . nil) (isearch t) (bookmark-jump t))
1111 "Non-nil means show all sibling heading when revealing a location.
1112 Org-mode often shows locations in an org-mode file which might have
1113 been invisible before. When this is set, the sibling of the current entry
1114 heading are all made visible. If `org-show-hierarchy-above' is t,
1115 the same happens on each level of the hierarchy above the current entry.
1117 By default this is on for the isearch context, off for all other contexts.
1118 Turning this off for example for sparse trees makes them very compact,
1119 but makes it harder to edit the location of the match. In such a case,
1120 use the command \\[org-reveal] to show more context.
1121 Instead of t, this can also be an alist specifying this option for different
1122 contexts. See `org-show-hierarchy-above' for valid contexts."
1123 :group 'org-reveal-location
1124 :type org-context-choice
1125 :version "24.4"
1126 :package-version '(Org . "8.0"))
1128 (defcustom org-show-entry-below '((default . nil))
1129 "Non-nil means show the entry below a headline when revealing a location.
1130 Org-mode often shows locations in an org-mode file which might have
1131 been invisible before. When this is set, the text below the headline that is
1132 exposed is also shown.
1134 By default this is off for all contexts.
1135 Instead of t, this can also be an alist specifying this option for different
1136 contexts. See `org-show-hierarchy-above' for valid contexts."
1137 :group 'org-reveal-location
1138 :type org-context-choice)
1140 (defcustom org-indirect-buffer-display 'other-window
1141 "How should indirect tree buffers be displayed?
1142 This applies to indirect buffers created with the commands
1143 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
1144 Valid values are:
1145 current-window Display in the current window
1146 other-window Just display in another window.
1147 dedicated-frame Create one new frame, and re-use it each time.
1148 new-frame Make a new frame each time. Note that in this case
1149 previously-made indirect buffers are kept, and you need to
1150 kill these buffers yourself."
1151 :group 'org-structure
1152 :group 'org-agenda-windows
1153 :type '(choice
1154 (const :tag "In current window" current-window)
1155 (const :tag "In current frame, other window" other-window)
1156 (const :tag "Each time a new frame" new-frame)
1157 (const :tag "One dedicated frame" dedicated-frame)))
1159 (defcustom org-use-speed-commands nil
1160 "Non-nil means activate single letter commands at beginning of a headline.
1161 This may also be a function to test for appropriate locations where speed
1162 commands should be active.
1164 For example, to activate speed commands when the point is on any
1165 star at the beginning of the headline, you can do this:
1167 (setq org-use-speed-commands
1168 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1169 :group 'org-structure
1170 :type '(choice
1171 (const :tag "Never" nil)
1172 (const :tag "At beginning of headline stars" t)
1173 (function)))
1175 (defcustom org-speed-commands-user nil
1176 "Alist of additional speed commands.
1177 This list will be checked before `org-speed-commands-default'
1178 when the variable `org-use-speed-commands' is non-nil
1179 and when the cursor is at the beginning of a headline.
1180 The car if each entry is a string with a single letter, which must
1181 be assigned to `self-insert-command' in the global map.
1182 The cdr is either a command to be called interactively, a function
1183 to be called, or a form to be evaluated.
1184 An entry that is just a list with a single string will be interpreted
1185 as a descriptive headline that will be added when listing the speed
1186 commands in the Help buffer using the `?' speed command."
1187 :group 'org-structure
1188 :type '(repeat :value ("k" . ignore)
1189 (choice :value ("k" . ignore)
1190 (list :tag "Descriptive Headline" (string :tag "Headline"))
1191 (cons :tag "Letter and Command"
1192 (string :tag "Command letter")
1193 (choice
1194 (function)
1195 (sexp))))))
1197 (defcustom org-bookmark-names-plist
1198 '(:last-capture "org-capture-last-stored"
1199 :last-refile "org-refile-last-stored"
1200 :last-capture-marker "org-capture-last-stored-marker")
1201 "Names for bookmarks automatically set by some Org commands.
1202 This can provide strings as names for a number of bookmarks Org sets
1203 automatically. The following keys are currently implemented:
1204 :last-capture
1205 :last-capture-marker
1206 :last-refile
1207 When a key does not show up in the property list, the corresponding bookmark
1208 is not set."
1209 :group 'org-structure
1210 :type 'plist)
1212 (defgroup org-cycle nil
1213 "Options concerning visibility cycling in Org-mode."
1214 :tag "Org Cycle"
1215 :group 'org-structure)
1217 (defcustom org-cycle-skip-children-state-if-no-children t
1218 "Non-nil means skip CHILDREN state in entries that don't have any."
1219 :group 'org-cycle
1220 :type 'boolean)
1222 (defcustom org-cycle-max-level nil
1223 "Maximum level which should still be subject to visibility cycling.
1224 Levels higher than this will, for cycling, be treated as text, not a headline.
1225 When `org-odd-levels-only' is set, a value of N in this variable actually
1226 means 2N-1 stars as the limiting headline.
1227 When nil, cycle all levels.
1228 Note that the limiting level of cycling is also influenced by
1229 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1230 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1231 than its value."
1232 :group 'org-cycle
1233 :type '(choice
1234 (const :tag "No limit" nil)
1235 (integer :tag "Maximum level")))
1237 (defcustom org-hide-block-startup nil
1238 "Non-nil means entering Org-mode will fold all blocks.
1239 This can also be set in on a per-file basis with
1241 #+STARTUP: hideblocks
1242 #+STARTUP: showblocks"
1243 :group 'org-startup
1244 :group 'org-cycle
1245 :type 'boolean)
1247 (defcustom org-cycle-global-at-bob nil
1248 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1249 This makes it possible to do global cycling without having to use S-TAB or
1250 \\[universal-argument] TAB. For this special case to work, the first line
1251 of the buffer must not be a headline -- it may be empty or some other text.
1252 When used in this way, `org-cycle-hook' is disabled temporarily to make
1253 sure the cursor stays at the beginning of the buffer. When this option is
1254 nil, don't do anything special at the beginning of the buffer."
1255 :group 'org-cycle
1256 :type 'boolean)
1258 (defcustom org-cycle-level-after-item/entry-creation t
1259 "Non-nil means cycle entry level or item indentation in new empty entries.
1261 When the cursor is at the end of an empty headline, i.e., with only stars
1262 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1263 and then all possible ancestor states, before returning to the original state.
1264 This makes data entry extremely fast: M-RET to create a new headline,
1265 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1267 When the cursor is at the end of an empty plain list item, one TAB will
1268 make it a subitem, two or more tabs will back up to make this an item
1269 higher up in the item hierarchy."
1270 :group 'org-cycle
1271 :type 'boolean)
1273 (defcustom org-cycle-emulate-tab t
1274 "Where should `org-cycle' emulate TAB.
1275 nil Never
1276 white Only in completely white lines
1277 whitestart Only at the beginning of lines, before the first non-white char
1278 t Everywhere except in headlines
1279 exc-hl-bol Everywhere except at the start of a headline
1280 If TAB is used in a place where it does not emulate TAB, the current subtree
1281 visibility is cycled."
1282 :group 'org-cycle
1283 :type '(choice (const :tag "Never" nil)
1284 (const :tag "Only in completely white lines" white)
1285 (const :tag "Before first char in a line" whitestart)
1286 (const :tag "Everywhere except in headlines" t)
1287 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1289 (defcustom org-cycle-separator-lines 2
1290 "Number of empty lines needed to keep an empty line between collapsed trees.
1291 If you leave an empty line between the end of a subtree and the following
1292 headline, this empty line is hidden when the subtree is folded.
1293 Org-mode will leave (exactly) one empty line visible if the number of
1294 empty lines is equal or larger to the number given in this variable.
1295 So the default 2 means at least 2 empty lines after the end of a subtree
1296 are needed to produce free space between a collapsed subtree and the
1297 following headline.
1299 If the number is negative, and the number of empty lines is at least -N,
1300 all empty lines are shown.
1302 Special case: when 0, never leave empty lines in collapsed view."
1303 :group 'org-cycle
1304 :type 'integer)
1305 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1307 (defcustom org-pre-cycle-hook nil
1308 "Hook that is run before visibility cycling is happening.
1309 The function(s) in this hook must accept a single argument which indicates
1310 the new state that will be set right after running this hook. The
1311 argument is a symbol. Before a global state change, it can have the values
1312 `overview', `content', or `all'. Before a local state change, it can have
1313 the values `folded', `children', or `subtree'."
1314 :group 'org-cycle
1315 :type 'hook)
1317 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1318 org-cycle-hide-drawers
1319 org-cycle-hide-inline-tasks
1320 org-cycle-show-empty-lines
1321 org-optimize-window-after-visibility-change)
1322 "Hook that is run after `org-cycle' has changed the buffer visibility.
1323 The function(s) in this hook must accept a single argument which indicates
1324 the new state that was set by the most recent `org-cycle' command. The
1325 argument is a symbol. After a global state change, it can have the values
1326 `overview', `contents', or `all'. After a local state change, it can have
1327 the values `folded', `children', or `subtree'."
1328 :group 'org-cycle
1329 :type 'hook)
1331 (defgroup org-edit-structure nil
1332 "Options concerning structure editing in Org-mode."
1333 :tag "Org Edit Structure"
1334 :group 'org-structure)
1336 (defcustom org-odd-levels-only nil
1337 "Non-nil means skip even levels and only use odd levels for the outline.
1338 This has the effect that two stars are being added/taken away in
1339 promotion/demotion commands. It also influences how levels are
1340 handled by the exporters.
1341 Changing it requires restart of `font-lock-mode' to become effective
1342 for fontification also in regions already fontified.
1343 You may also set this on a per-file basis by adding one of the following
1344 lines to the buffer:
1346 #+STARTUP: odd
1347 #+STARTUP: oddeven"
1348 :group 'org-edit-structure
1349 :group 'org-appearance
1350 :type 'boolean)
1352 (defcustom org-adapt-indentation t
1353 "Non-nil means adapt indentation to outline node level.
1355 When this variable is set, Org assumes that you write outlines by
1356 indenting text in each node to align with the headline (after the stars).
1357 The following issues are influenced by this variable:
1359 - When this is set and the *entire* text in an entry is indented, the
1360 indentation is increased by one space in a demotion command, and
1361 decreased by one in a promotion command. If any line in the entry
1362 body starts with text at column 0, indentation is not changed at all.
1364 - Property drawers and planning information is inserted indented when
1365 this variable s set. When nil, they will not be indented.
1367 - TAB indents a line relative to context. The lines below a headline
1368 will be indented when this variable is set.
1370 Note that this is all about true indentation, by adding and removing
1371 space characters. See also `org-indent.el' which does level-dependent
1372 indentation in a virtual way, i.e. at display time in Emacs."
1373 :group 'org-edit-structure
1374 :type 'boolean)
1376 (defcustom org-special-ctrl-a/e nil
1377 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1379 When t, `C-a' will bring back the cursor to the beginning of the
1380 headline text, i.e. after the stars and after a possible TODO
1381 keyword. In an item, this will be the position after bullet and
1382 check-box, if any. When the cursor is already at that position,
1383 another `C-a' will bring it to the beginning of the line.
1385 `C-e' will jump to the end of the headline, ignoring the presence
1386 of tags in the headline. A second `C-e' will then jump to the
1387 true end of the line, after any tags. This also means that, when
1388 this variable is non-nil, `C-e' also will never jump beyond the
1389 end of the heading of a folded section, i.e. not after the
1390 ellipses.
1392 When set to the symbol `reversed', the first `C-a' or `C-e' works
1393 normally, going to the true line boundary first. Only a directly
1394 following, identical keypress will bring the cursor to the
1395 special positions.
1397 This may also be a cons cell where the behavior for `C-a' and
1398 `C-e' is set separately."
1399 :group 'org-edit-structure
1400 :type '(choice
1401 (const :tag "off" nil)
1402 (const :tag "on: after stars/bullet and before tags first" t)
1403 (const :tag "reversed: true line boundary first" reversed)
1404 (cons :tag "Set C-a and C-e separately"
1405 (choice :tag "Special C-a"
1406 (const :tag "off" nil)
1407 (const :tag "on: after stars/bullet first" t)
1408 (const :tag "reversed: before stars/bullet first" reversed))
1409 (choice :tag "Special C-e"
1410 (const :tag "off" nil)
1411 (const :tag "on: before tags first" t)
1412 (const :tag "reversed: after tags first" reversed)))))
1413 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1415 (defcustom org-special-ctrl-k nil
1416 "Non-nil means `C-k' will behave specially in headlines.
1417 When nil, `C-k' will call the default `kill-line' command.
1418 When t, the following will happen while the cursor is in the headline:
1420 - When the cursor is at the beginning of a headline, kill the entire
1421 line and possible the folded subtree below the line.
1422 - When in the middle of the headline text, kill the headline up to the tags.
1423 - When after the headline text, kill the tags."
1424 :group 'org-edit-structure
1425 :type 'boolean)
1427 (defcustom org-ctrl-k-protect-subtree nil
1428 "Non-nil means, do not delete a hidden subtree with C-k.
1429 When set to the symbol `error', simply throw an error when C-k is
1430 used to kill (part-of) a headline that has hidden text behind it.
1431 Any other non-nil value will result in a query to the user, if it is
1432 OK to kill that hidden subtree. When nil, kill without remorse."
1433 :group 'org-edit-structure
1434 :version "24.1"
1435 :type '(choice
1436 (const :tag "Do not protect hidden subtrees" nil)
1437 (const :tag "Protect hidden subtrees with a security query" t)
1438 (const :tag "Never kill a hidden subtree with C-k" error)))
1440 (defcustom org-special-ctrl-o t
1441 "Non-nil means, make `C-o' insert a row in tables."
1442 :group 'org-edit-structure
1443 :type 'boolean)
1445 (defcustom org-catch-invisible-edits nil
1446 "Check if in invisible region before inserting or deleting a character.
1447 Valid values are:
1449 nil Do not check, so just do invisible edits.
1450 error Throw an error and do nothing.
1451 show Make point visible, and do the requested edit.
1452 show-and-error Make point visible, then throw an error and abort the edit.
1453 smart Make point visible, and do insertion/deletion if it is
1454 adjacent to visible text and the change feels predictable.
1455 Never delete a previously invisible character or add in the
1456 middle or right after an invisible region. Basically, this
1457 allows insertion and backward-delete right before ellipses.
1458 FIXME: maybe in this case we should not even show?"
1459 :group 'org-edit-structure
1460 :version "24.1"
1461 :type '(choice
1462 (const :tag "Do not check" nil)
1463 (const :tag "Throw error when trying to edit" error)
1464 (const :tag "Unhide, but do not do the edit" show-and-error)
1465 (const :tag "Show invisible part and do the edit" show)
1466 (const :tag "Be smart and do the right thing" smart)))
1468 (defcustom org-yank-folded-subtrees t
1469 "Non-nil means when yanking subtrees, fold them.
1470 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1471 it starts with a heading and all other headings in it are either children
1472 or siblings, then fold all the subtrees. However, do this only if no
1473 text after the yank would be swallowed into a folded tree by this action."
1474 :group 'org-edit-structure
1475 :type 'boolean)
1477 (defcustom org-yank-adjusted-subtrees nil
1478 "Non-nil means when yanking subtrees, adjust the level.
1479 With this setting, `org-paste-subtree' is used to insert the subtree, see
1480 this function for details."
1481 :group 'org-edit-structure
1482 :type 'boolean)
1484 (defcustom org-M-RET-may-split-line '((default . t))
1485 "Non-nil means M-RET will split the line at the cursor position.
1486 When nil, it will go to the end of the line before making a
1487 new line.
1488 You may also set this option in a different way for different
1489 contexts. Valid contexts are:
1491 headline when creating a new headline
1492 item when creating a new item
1493 table in a table field
1494 default the value to be used for all contexts not explicitly
1495 customized"
1496 :group 'org-structure
1497 :group 'org-table
1498 :type '(choice
1499 (const :tag "Always" t)
1500 (const :tag "Never" nil)
1501 (repeat :greedy t :tag "Individual contexts"
1502 (cons
1503 (choice :tag "Context"
1504 (const headline)
1505 (const item)
1506 (const table)
1507 (const default))
1508 (boolean)))))
1511 (defcustom org-insert-heading-respect-content nil
1512 "Non-nil means insert new headings after the current subtree.
1513 When nil, the new heading is created directly after the current line.
1514 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1515 this variable on for the duration of the command."
1516 :group 'org-structure
1517 :type 'boolean)
1519 (defcustom org-blank-before-new-entry '((heading . auto)
1520 (plain-list-item . auto))
1521 "Should `org-insert-heading' leave a blank line before new heading/item?
1522 The value is an alist, with `heading' and `plain-list-item' as CAR,
1523 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1524 which case Org will look at the surrounding headings/items and try to
1525 make an intelligent decision whether to insert a blank line or not.
1527 For plain lists, if `org-list-empty-line-terminates-plain-lists' is set,
1528 the setting here is ignored and no empty line is inserted to avoid breaking
1529 the list structure."
1530 :group 'org-edit-structure
1531 :type '(list
1532 (cons (const heading)
1533 (choice (const :tag "Never" nil)
1534 (const :tag "Always" t)
1535 (const :tag "Auto" auto)))
1536 (cons (const plain-list-item)
1537 (choice (const :tag "Never" nil)
1538 (const :tag "Always" t)
1539 (const :tag "Auto" auto)))))
1541 (defcustom org-insert-heading-hook nil
1542 "Hook being run after inserting a new heading."
1543 :group 'org-edit-structure
1544 :type 'hook)
1546 (defcustom org-enable-fixed-width-editor t
1547 "Non-nil means lines starting with \":\" are treated as fixed-width.
1548 This currently only means they are never auto-wrapped.
1549 When nil, such lines will be treated like ordinary lines."
1550 :group 'org-edit-structure
1551 :type 'boolean)
1553 (defcustom org-goto-auto-isearch t
1554 "Non-nil means typing characters in `org-goto' starts incremental search.
1555 When nil, you can use these keybindings to navigate the buffer:
1557 q Quit the org-goto interface
1558 n Go to the next visible heading
1559 p Go to the previous visible heading
1560 f Go one heading forward on same level
1561 b Go one heading backward on same level
1562 u Go one heading up"
1563 :group 'org-edit-structure
1564 :type 'boolean)
1566 (defgroup org-sparse-trees nil
1567 "Options concerning sparse trees in Org-mode."
1568 :tag "Org Sparse Trees"
1569 :group 'org-structure)
1571 (defcustom org-highlight-sparse-tree-matches t
1572 "Non-nil means highlight all matches that define a sparse tree.
1573 The highlights will automatically disappear the next time the buffer is
1574 changed by an edit command."
1575 :group 'org-sparse-trees
1576 :type 'boolean)
1578 (defcustom org-remove-highlights-with-change t
1579 "Non-nil means any change to the buffer will remove temporary highlights.
1580 Such highlights are created by `org-occur' and `org-clock-display'.
1581 When nil, `C-c C-c needs to be used to get rid of the highlights.
1582 The highlights created by `org-preview-latex-fragment' always need
1583 `C-c C-c' to be removed."
1584 :group 'org-sparse-trees
1585 :group 'org-time
1586 :type 'boolean)
1589 (defcustom org-occur-hook '(org-first-headline-recenter)
1590 "Hook that is run after `org-occur' has constructed a sparse tree.
1591 This can be used to recenter the window to show as much of the structure
1592 as possible."
1593 :group 'org-sparse-trees
1594 :type 'hook)
1596 (defgroup org-imenu-and-speedbar nil
1597 "Options concerning imenu and speedbar in Org-mode."
1598 :tag "Org Imenu and Speedbar"
1599 :group 'org-structure)
1601 (defcustom org-imenu-depth 2
1602 "The maximum level for Imenu access to Org-mode headlines.
1603 This also applied for speedbar access."
1604 :group 'org-imenu-and-speedbar
1605 :type 'integer)
1607 (defgroup org-table nil
1608 "Options concerning tables in Org-mode."
1609 :tag "Org Table"
1610 :group 'org)
1612 (defcustom org-enable-table-editor 'optimized
1613 "Non-nil means lines starting with \"|\" are handled by the table editor.
1614 When nil, such lines will be treated like ordinary lines.
1616 When equal to the symbol `optimized', the table editor will be optimized to
1617 do the following:
1618 - Automatic overwrite mode in front of whitespace in table fields.
1619 This makes the structure of the table stay in tact as long as the edited
1620 field does not exceed the column width.
1621 - Minimize the number of realigns. Normally, the table is aligned each time
1622 TAB or RET are pressed to move to another field. With optimization this
1623 happens only if changes to a field might have changed the column width.
1624 Optimization requires replacing the functions `self-insert-command',
1625 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1626 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1627 very good at guessing when a re-align will be necessary, but you can always
1628 force one with \\[org-ctrl-c-ctrl-c].
1630 If you would like to use the optimized version in Org-mode, but the
1631 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1633 This variable can be used to turn on and off the table editor during a session,
1634 but in order to toggle optimization, a restart is required.
1636 See also the variable `org-table-auto-blank-field'."
1637 :group 'org-table
1638 :type '(choice
1639 (const :tag "off" nil)
1640 (const :tag "on" t)
1641 (const :tag "on, optimized" optimized)))
1643 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1644 (version<= emacs-version "24.1"))
1645 "Non-nil means cluster self-insert commands for undo when possible.
1646 If this is set, then, like in the Emacs command loop, 20 consecutive
1647 characters will be undone together.
1648 This is configurable, because there is some impact on typing performance."
1649 :group 'org-table
1650 :type 'boolean)
1652 (defcustom org-table-tab-recognizes-table.el t
1653 "Non-nil means TAB will automatically notice a table.el table.
1654 When it sees such a table, it moves point into it and - if necessary -
1655 calls `table-recognize-table'."
1656 :group 'org-table-editing
1657 :type 'boolean)
1659 (defgroup org-link nil
1660 "Options concerning links in Org-mode."
1661 :tag "Org Link"
1662 :group 'org)
1664 (defvar org-link-abbrev-alist-local nil
1665 "Buffer-local version of `org-link-abbrev-alist', which see.
1666 The value of this is taken from the #+LINK lines.")
1667 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1669 (defcustom org-link-abbrev-alist nil
1670 "Alist of link abbreviations.
1671 The car of each element is a string, to be replaced at the start of a link.
1672 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1673 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1675 [[linkkey:tag][description]]
1677 The 'linkkey' must be a word word, starting with a letter, followed
1678 by letters, numbers, '-' or '_'.
1680 If REPLACE is a string, the tag will simply be appended to create the link.
1681 If the string contains \"%s\", the tag will be inserted there. If the string
1682 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1683 at that point (see the function `url-hexify-string'). If the string contains
1684 the specifier \"%(my-function)\", then the custom function `my-function' will
1685 be invoked: this function takes the tag as its only argument and must return
1686 a string.
1688 REPLACE may also be a function that will be called with the tag as the
1689 only argument to create the link, which should be returned as a string.
1691 See the manual for examples."
1692 :group 'org-link
1693 :type '(repeat
1694 (cons
1695 (string :tag "Protocol")
1696 (choice
1697 (string :tag "Format")
1698 (function)))))
1700 (defcustom org-descriptive-links t
1701 "Non-nil means Org will display descriptive links.
1702 E.g. [[http://orgmode.org][Org website]] will be displayed as
1703 \"Org Website\", hiding the link itself and just displaying its
1704 description. When set to `nil', Org will display the full links
1705 literally.
1707 You can interactively set the value of this variable by calling
1708 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1709 :group 'org-link
1710 :type 'boolean)
1712 (defcustom org-link-file-path-type 'adaptive
1713 "How the path name in file links should be stored.
1714 Valid values are:
1716 relative Relative to the current directory, i.e. the directory of the file
1717 into which the link is being inserted.
1718 absolute Absolute path, if possible with ~ for home directory.
1719 noabbrev Absolute path, no abbreviation of home directory.
1720 adaptive Use relative path for files in the current directory and sub-
1721 directories of it. For other files, use an absolute path."
1722 :group 'org-link
1723 :type '(choice
1724 (const relative)
1725 (const absolute)
1726 (const noabbrev)
1727 (const adaptive)))
1729 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1730 "Types of links that should be activated in Org-mode files.
1731 This is a list of symbols, each leading to the activation of a certain link
1732 type. In principle, it does not hurt to turn on most link types - there may
1733 be a small gain when turning off unused link types. The types are:
1735 bracket The recommended [[link][description]] or [[link]] links with hiding.
1736 angle Links in angular brackets that may contain whitespace like
1737 <bbdb:Carsten Dominik>.
1738 plain Plain links in normal text, no whitespace, like http://google.com.
1739 radio Text that is matched by a radio target, see manual for details.
1740 tag Tag settings in a headline (link to tag search).
1741 date Time stamps (link to calendar).
1742 footnote Footnote labels.
1744 Changing this variable requires a restart of Emacs to become effective."
1745 :group 'org-link
1746 :type '(set :greedy t
1747 (const :tag "Double bracket links" bracket)
1748 (const :tag "Angular bracket links" angle)
1749 (const :tag "Plain text links" plain)
1750 (const :tag "Radio target matches" radio)
1751 (const :tag "Tags" tag)
1752 (const :tag "Timestamps" date)
1753 (const :tag "Footnotes" footnote)))
1755 (defcustom org-make-link-description-function nil
1756 "Function to use for generating link descriptions from links.
1757 When nil, the link location will be used. This function must take
1758 two parameters: the first one is the link, the second one is the
1759 description generated by `org-insert-link'. The function should
1760 return the description to use."
1761 :group 'org-link
1762 :type '(choice (const nil) (function)))
1764 (defgroup org-link-store nil
1765 "Options concerning storing links in Org-mode."
1766 :tag "Org Store Link"
1767 :group 'org-link)
1769 (defcustom org-url-hexify-p t
1770 "When non-nil, hexify URL when creating a link."
1771 :type 'boolean
1772 :version "24.3"
1773 :group 'org-link-store)
1775 (defcustom org-email-link-description-format "Email %c: %.30s"
1776 "Format of the description part of a link to an email or usenet message.
1777 The following %-escapes will be replaced by corresponding information:
1779 %F full \"From\" field
1780 %f name, taken from \"From\" field, address if no name
1781 %T full \"To\" field
1782 %t first name in \"To\" field, address if no name
1783 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1784 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1785 %s subject
1786 %d date
1787 %m message-id.
1789 You may use normal field width specification between the % and the letter.
1790 This is for example useful to limit the length of the subject.
1792 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1793 :group 'org-link-store
1794 :type 'string)
1796 (defcustom org-from-is-user-regexp
1797 (let (r1 r2)
1798 (when (and user-mail-address (not (string= user-mail-address "")))
1799 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1800 (when (and user-full-name (not (string= user-full-name "")))
1801 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1802 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1803 "Regexp matched against the \"From:\" header of an email or usenet message.
1804 It should match if the message is from the user him/herself."
1805 :group 'org-link-store
1806 :type 'regexp)
1808 (defcustom org-context-in-file-links t
1809 "Non-nil means file links from `org-store-link' contain context.
1810 A search string will be added to the file name with :: as separator and
1811 used to find the context when the link is activated by the command
1812 `org-open-at-point'. When this option is t, the entire active region
1813 will be placed in the search string of the file link. If set to a
1814 positive integer, only the first n lines of context will be stored.
1816 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1817 negates this setting for the duration of the command."
1818 :group 'org-link-store
1819 :type '(choice boolean integer))
1821 (defcustom org-keep-stored-link-after-insertion nil
1822 "Non-nil means keep link in list for entire session.
1824 The command `org-store-link' adds a link pointing to the current
1825 location to an internal list. These links accumulate during a session.
1826 The command `org-insert-link' can be used to insert links into any
1827 Org-mode file (offering completion for all stored links). When this
1828 option is nil, every link which has been inserted once using \\[org-insert-link]
1829 will be removed from the list, to make completing the unused links
1830 more efficient."
1831 :group 'org-link-store
1832 :type 'boolean)
1834 (defgroup org-link-follow nil
1835 "Options concerning following links in Org-mode."
1836 :tag "Org Follow Link"
1837 :group 'org-link)
1839 (defcustom org-link-translation-function nil
1840 "Function to translate links with different syntax to Org syntax.
1841 This can be used to translate links created for example by the Planner
1842 or emacs-wiki packages to Org syntax.
1843 The function must accept two parameters, a TYPE containing the link
1844 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1845 which is everything after the link protocol. It should return a cons
1846 with possibly modified values of type and path.
1847 Org contains a function for this, so if you set this variable to
1848 `org-translate-link-from-planner', you should be able follow many
1849 links created by planner."
1850 :group 'org-link-follow
1851 :type '(choice (const nil) (function)))
1853 (defcustom org-follow-link-hook nil
1854 "Hook that is run after a link has been followed."
1855 :group 'org-link-follow
1856 :type 'hook)
1858 (defcustom org-tab-follows-link nil
1859 "Non-nil means on links TAB will follow the link.
1860 Needs to be set before org.el is loaded.
1861 This really should not be used, it does not make sense, and the
1862 implementation is bad."
1863 :group 'org-link-follow
1864 :type 'boolean)
1866 (defcustom org-return-follows-link nil
1867 "Non-nil means on links RET will follow the link.
1868 In tables, the special behavior of RET has precedence."
1869 :group 'org-link-follow
1870 :type 'boolean)
1872 (defcustom org-mouse-1-follows-link
1873 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1874 "Non-nil means mouse-1 on a link will follow the link.
1875 A longer mouse click will still set point. Does not work on XEmacs.
1876 Needs to be set before org.el is loaded."
1877 :group 'org-link-follow
1878 :version "24.4"
1879 :package-version '(Org . "8.3")
1880 :type '(choice
1881 (const :tag "A double click follows the link" double)
1882 (const :tag "Unconditionally follow the link with mouse-1" t)
1883 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
1885 (defcustom org-mark-ring-length 4
1886 "Number of different positions to be recorded in the ring.
1887 Changing this requires a restart of Emacs to work correctly."
1888 :group 'org-link-follow
1889 :type 'integer)
1891 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1892 "Non-nil means internal links in Org files must exactly match a headline.
1893 When nil, the link search tries to match a phrase with all words
1894 in the search text."
1895 :group 'org-link-follow
1896 :version "24.1"
1897 :type '(choice
1898 (const :tag "Use fuzzy text search" nil)
1899 (const :tag "Match only exact headline" t)
1900 (const :tag "Match exact headline or query to create it"
1901 query-to-create)))
1903 (defcustom org-link-frame-setup
1904 '((vm . vm-visit-folder-other-frame)
1905 (vm-imap . vm-visit-imap-folder-other-frame)
1906 (gnus . org-gnus-no-new-news)
1907 (file . find-file-other-window)
1908 (wl . wl-other-frame))
1909 "Setup the frame configuration for following links.
1910 When following a link with Emacs, it may often be useful to display
1911 this link in another window or frame. This variable can be used to
1912 set this up for the different types of links.
1913 For VM, use any of
1914 `vm-visit-folder'
1915 `vm-visit-folder-other-window'
1916 `vm-visit-folder-other-frame'
1917 For Gnus, use any of
1918 `gnus'
1919 `gnus-other-frame'
1920 `org-gnus-no-new-news'
1921 For FILE, use any of
1922 `find-file'
1923 `find-file-other-window'
1924 `find-file-other-frame'
1925 For Wanderlust use any of
1926 `wl'
1927 `wl-other-frame'
1928 For the calendar, use the variable `calendar-setup'.
1929 For BBDB, it is currently only possible to display the matches in
1930 another window."
1931 :group 'org-link-follow
1932 :type '(list
1933 (cons (const vm)
1934 (choice
1935 (const vm-visit-folder)
1936 (const vm-visit-folder-other-window)
1937 (const vm-visit-folder-other-frame)))
1938 (cons (const vm-imap)
1939 (choice
1940 (const vm-visit-imap-folder)
1941 (const vm-visit-imap-folder-other-window)
1942 (const vm-visit-imap-folder-other-frame)))
1943 (cons (const gnus)
1944 (choice
1945 (const gnus)
1946 (const gnus-other-frame)
1947 (const org-gnus-no-new-news)))
1948 (cons (const file)
1949 (choice
1950 (const find-file)
1951 (const find-file-other-window)
1952 (const find-file-other-frame)))
1953 (cons (const wl)
1954 (choice
1955 (const wl)
1956 (const wl-other-frame)))))
1958 (defcustom org-display-internal-link-with-indirect-buffer nil
1959 "Non-nil means use indirect buffer to display infile links.
1960 Activating internal links (from one location in a file to another location
1961 in the same file) normally just jumps to the location. When the link is
1962 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1963 is displayed in
1964 another window. When this option is set, the other window actually displays
1965 an indirect buffer clone of the current buffer, to avoid any visibility
1966 changes to the current buffer."
1967 :group 'org-link-follow
1968 :type 'boolean)
1970 (defcustom org-open-non-existing-files nil
1971 "Non-nil means `org-open-file' will open non-existing files.
1972 When nil, an error will be generated.
1973 This variable applies only to external applications because they
1974 might choke on non-existing files. If the link is to a file that
1975 will be opened in Emacs, the variable is ignored."
1976 :group 'org-link-follow
1977 :type 'boolean)
1979 (defcustom org-open-directory-means-index-dot-org nil
1980 "Non-nil means a link to a directory really means to index.org.
1981 When nil, following a directory link will run dired or open a finder/explorer
1982 window on that directory."
1983 :group 'org-link-follow
1984 :type 'boolean)
1986 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1987 "Function and arguments to call for following mailto links.
1988 This is a list with the first element being a Lisp function, and the
1989 remaining elements being arguments to the function. In string arguments,
1990 %a will be replaced by the address, and %s will be replaced by the subject
1991 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1992 :group 'org-link-follow
1993 :type '(choice
1994 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1995 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1996 (const :tag "message-mail" (message-mail "%a" "%s"))
1997 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1999 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2000 "Non-nil means ask for confirmation before executing shell links.
2001 Shell links can be dangerous: just think about a link
2003 [[shell:rm -rf ~/*][Google Search]]
2005 This link would show up in your Org-mode document as \"Google Search\",
2006 but really it would remove your entire home directory.
2007 Therefore we advise against setting this variable to nil.
2008 Just change it to `y-or-n-p' if you want to confirm with a
2009 single keystroke rather than having to type \"yes\"."
2010 :group 'org-link-follow
2011 :type '(choice
2012 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2013 (const :tag "with y-or-n (faster)" y-or-n-p)
2014 (const :tag "no confirmation (dangerous)" nil)))
2015 (put 'org-confirm-shell-link-function
2016 'safe-local-variable
2017 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2019 (defcustom org-confirm-shell-link-not-regexp ""
2020 "A regexp to skip confirmation for shell links."
2021 :group 'org-link-follow
2022 :version "24.1"
2023 :type 'regexp)
2025 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2026 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2027 Elisp links can be dangerous: just think about a link
2029 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2031 This link would show up in your Org-mode document as \"Google Search\",
2032 but really it would remove your entire home directory.
2033 Therefore we advise against setting this variable to nil.
2034 Just change it to `y-or-n-p' if you want to confirm with a
2035 single keystroke rather than having to type \"yes\"."
2036 :group 'org-link-follow
2037 :type '(choice
2038 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2039 (const :tag "with y-or-n (faster)" y-or-n-p)
2040 (const :tag "no confirmation (dangerous)" nil)))
2041 (put 'org-confirm-shell-link-function
2042 'safe-local-variable
2043 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2045 (defcustom org-confirm-elisp-link-not-regexp ""
2046 "A regexp to skip confirmation for Elisp links."
2047 :group 'org-link-follow
2048 :version "24.1"
2049 :type 'regexp)
2051 (defconst org-file-apps-defaults-gnu
2052 '((remote . emacs)
2053 (system . mailcap)
2054 (t . mailcap))
2055 "Default file applications on a UNIX or GNU/Linux system.
2056 See `org-file-apps'.")
2058 (defconst org-file-apps-defaults-macosx
2059 '((remote . emacs)
2060 (t . "open %s")
2061 (system . "open %s")
2062 ("ps.gz" . "gv %s")
2063 ("eps.gz" . "gv %s")
2064 ("dvi" . "xdvi %s")
2065 ("fig" . "xfig %s"))
2066 "Default file applications on a MacOS X system.
2067 The system \"open\" is known as a default, but we use X11 applications
2068 for some files for which the OS does not have a good default.
2069 See `org-file-apps'.")
2071 (defconst org-file-apps-defaults-windowsnt
2072 (list
2073 '(remote . emacs)
2074 (cons t
2075 (list (if (featurep 'xemacs)
2076 'mswindows-shell-execute
2077 'w32-shell-execute)
2078 "open" 'file))
2079 (cons 'system
2080 (list (if (featurep 'xemacs)
2081 'mswindows-shell-execute
2082 'w32-shell-execute)
2083 "open" 'file)))
2084 "Default file applications on a Windows NT system.
2085 The system \"open\" is used for most files.
2086 See `org-file-apps'.")
2088 (defcustom org-file-apps
2089 '((auto-mode . emacs)
2090 ("\\.mm\\'" . default)
2091 ("\\.x?html?\\'" . default)
2092 ("\\.pdf\\'" . default))
2093 "External applications for opening `file:path' items in a document.
2094 Org-mode uses system defaults for different file types, but
2095 you can use this variable to set the application for a given file
2096 extension. The entries in this list are cons cells where the car identifies
2097 files and the cdr the corresponding command. Possible values for the
2098 file identifier are
2099 \"string\" A string as a file identifier can be interpreted in different
2100 ways, depending on its contents:
2102 - Alphanumeric characters only:
2103 Match links with this file extension.
2104 Example: (\"pdf\" . \"evince %s\")
2105 to open PDFs with evince.
2107 - Regular expression: Match links where the
2108 filename matches the regexp. If you want to
2109 use groups here, use shy groups.
2111 Example: (\"\\.x?html\\'\" . \"firefox %s\")
2112 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
2113 to open *.html and *.xhtml with firefox.
2115 - Regular expression which contains (non-shy) groups:
2116 Match links where the whole link, including \"::\", and
2117 anything after that, matches the regexp.
2118 In a custom command string, %1, %2, etc. are replaced with
2119 the parts of the link that were matched by the groups.
2120 For backwards compatibility, if a command string is given
2121 that does not use any of the group matches, this case is
2122 handled identically to the second one (i.e. match against
2123 file name only).
2124 In a custom lisp form, you can access the group matches with
2125 (match-string n link).
2127 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
2128 to open [[file:document.pdf::5]] with evince at page 5.
2130 `directory' Matches a directory
2131 `remote' Matches a remote file, accessible through tramp or efs.
2132 Remote files most likely should be visited through Emacs
2133 because external applications cannot handle such paths.
2134 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2135 so all files Emacs knows how to handle. Using this with
2136 command `emacs' will open most files in Emacs. Beware that this
2137 will also open html files inside Emacs, unless you add
2138 (\"html\" . default) to the list as well.
2139 t Default for files not matched by any of the other options.
2140 `system' The system command to open files, like `open' on Windows
2141 and Mac OS X, and mailcap under GNU/Linux. This is the command
2142 that will be selected if you call `C-c C-o' with a double
2143 \\[universal-argument] \\[universal-argument] prefix.
2145 Possible values for the command are:
2146 `emacs' The file will be visited by the current Emacs process.
2147 `default' Use the default application for this file type, which is the
2148 association for t in the list, most likely in the system-specific
2149 part.
2150 This can be used to overrule an unwanted setting in the
2151 system-specific variable.
2152 `system' Use the system command for opening files, like \"open\".
2153 This command is specified by the entry whose car is `system'.
2154 Most likely, the system-specific version of this variable
2155 does define this command, but you can overrule/replace it
2156 here.
2157 string A command to be executed by a shell; %s will be replaced
2158 by the path to the file.
2159 sexp A Lisp form which will be evaluated. The file path will
2160 be available in the Lisp variable `file'.
2161 For more examples, see the system specific constants
2162 `org-file-apps-defaults-macosx'
2163 `org-file-apps-defaults-windowsnt'
2164 `org-file-apps-defaults-gnu'."
2165 :group 'org-link-follow
2166 :type '(repeat
2167 (cons (choice :value ""
2168 (string :tag "Extension")
2169 (const :tag "System command to open files" system)
2170 (const :tag "Default for unrecognized files" t)
2171 (const :tag "Remote file" remote)
2172 (const :tag "Links to a directory" directory)
2173 (const :tag "Any files that have Emacs modes"
2174 auto-mode))
2175 (choice :value ""
2176 (const :tag "Visit with Emacs" emacs)
2177 (const :tag "Use default" default)
2178 (const :tag "Use the system command" system)
2179 (string :tag "Command")
2180 (sexp :tag "Lisp form")))))
2182 (defcustom org-doi-server-url "http://dx.doi.org/"
2183 "The URL of the DOI server."
2184 :type 'string
2185 :version "24.3"
2186 :group 'org-link-follow)
2188 (defgroup org-refile nil
2189 "Options concerning refiling entries in Org-mode."
2190 :tag "Org Refile"
2191 :group 'org)
2193 (defcustom org-directory "~/org"
2194 "Directory with org files.
2195 This is just a default location to look for Org files. There is no need
2196 at all to put your files into this directory. It is only used in the
2197 following situations:
2199 1. When a capture template specifies a target file that is not an
2200 absolute path. The path will then be interpreted relative to
2201 `org-directory'
2202 2. When a capture note is filed away in an interactive way (when exiting the
2203 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2204 with `org-directory' as the default path."
2205 :group 'org-refile
2206 :group 'org-capture
2207 :type 'directory)
2209 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2210 "Default target for storing notes.
2211 Used as a fall back file for org-capture.el, for templates that
2212 do not specify a target file."
2213 :group 'org-refile
2214 :group 'org-capture
2215 :type '(choice
2216 (const :tag "Default from remember-data-file" nil)
2217 file))
2219 (defcustom org-goto-interface 'outline
2220 "The default interface to be used for `org-goto'.
2221 Allowed values are:
2222 outline The interface shows an outline of the relevant file
2223 and the correct heading is found by moving through
2224 the outline or by searching with incremental search.
2225 outline-path-completion Headlines in the current buffer are offered via
2226 completion. This is the interface also used by
2227 the refile command."
2228 :group 'org-refile
2229 :type '(choice
2230 (const :tag "Outline" outline)
2231 (const :tag "Outline-path-completion" outline-path-completion)))
2233 (defcustom org-goto-max-level 5
2234 "Maximum target level when running `org-goto' with refile interface."
2235 :group 'org-refile
2236 :type 'integer)
2238 (defcustom org-reverse-note-order nil
2239 "Non-nil means store new notes at the beginning of a file or entry.
2240 When nil, new notes will be filed to the end of a file or entry.
2241 This can also be a list with cons cells of regular expressions that
2242 are matched against file names, and values."
2243 :group 'org-capture
2244 :group 'org-refile
2245 :type '(choice
2246 (const :tag "Reverse always" t)
2247 (const :tag "Reverse never" nil)
2248 (repeat :tag "By file name regexp"
2249 (cons regexp boolean))))
2251 (defcustom org-log-refile nil
2252 "Information to record when a task is refiled.
2254 Possible values are:
2256 nil Don't add anything
2257 time Add a time stamp to the task
2258 note Prompt for a note and add it with template `org-log-note-headings'
2260 This option can also be set with on a per-file-basis with
2262 #+STARTUP: nologrefile
2263 #+STARTUP: logrefile
2264 #+STARTUP: lognoterefile
2266 You can have local logging settings for a subtree by setting the LOGGING
2267 property to one or more of these keywords.
2269 When bulk-refiling from the agenda, the value `note' is forbidden and
2270 will temporarily be changed to `time'."
2271 :group 'org-refile
2272 :group 'org-progress
2273 :version "24.1"
2274 :type '(choice
2275 (const :tag "No logging" nil)
2276 (const :tag "Record timestamp" time)
2277 (const :tag "Record timestamp with note." note)))
2279 (defcustom org-refile-targets nil
2280 "Targets for refiling entries with \\[org-refile].
2281 This is a list of cons cells. Each cell contains:
2282 - a specification of the files to be considered, either a list of files,
2283 or a symbol whose function or variable value will be used to retrieve
2284 a file name or a list of file names. If you use `org-agenda-files' for
2285 that, all agenda files will be scanned for targets. Nil means consider
2286 headings in the current buffer.
2287 - A specification of how to find candidate refile targets. This may be
2288 any of:
2289 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2290 This tag has to be present in all target headlines, inheritance will
2291 not be considered.
2292 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2293 todo keyword.
2294 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2295 headlines that are refiling targets.
2296 - a cons cell (:level . N). Any headline of level N is considered a target.
2297 Note that, when `org-odd-levels-only' is set, level corresponds to
2298 order in hierarchy, not to the number of stars.
2299 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2300 Note that, when `org-odd-levels-only' is set, level corresponds to
2301 order in hierarchy, not to the number of stars.
2303 Each element of this list generates a set of possible targets.
2304 The union of these sets is presented (with completion) to
2305 the user by `org-refile'.
2307 You can set the variable `org-refile-target-verify-function' to a function
2308 to verify each headline found by the simple criteria above.
2310 When this variable is nil, all top-level headlines in the current buffer
2311 are used, equivalent to the value `((nil . (:level . 1))'."
2312 :group 'org-refile
2313 :type '(repeat
2314 (cons
2315 (choice :value org-agenda-files
2316 (const :tag "All agenda files" org-agenda-files)
2317 (const :tag "Current buffer" nil)
2318 (function) (variable) (file))
2319 (choice :tag "Identify target headline by"
2320 (cons :tag "Specific tag" (const :value :tag) (string))
2321 (cons :tag "TODO keyword" (const :value :todo) (string))
2322 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2323 (cons :tag "Level number" (const :value :level) (integer))
2324 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2326 (defcustom org-refile-target-verify-function nil
2327 "Function to verify if the headline at point should be a refile target.
2328 The function will be called without arguments, with point at the
2329 beginning of the headline. It should return t and leave point
2330 where it is if the headline is a valid target for refiling.
2332 If the target should not be selected, the function must return nil.
2333 In addition to this, it may move point to a place from where the search
2334 should be continued. For example, the function may decide that the entire
2335 subtree of the current entry should be excluded and move point to the end
2336 of the subtree."
2337 :group 'org-refile
2338 :type '(choice
2339 (const nil)
2340 (function)))
2342 (defcustom org-refile-use-cache nil
2343 "Non-nil means cache refile targets to speed up the process.
2344 The cache for a particular file will be updated automatically when
2345 the buffer has been killed, or when any of the marker used for flagging
2346 refile targets no longer points at a live buffer.
2347 If you have added new entries to a buffer that might themselves be targets,
2348 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2349 find that easier, `C-u C-u C-u C-c C-w'."
2350 :group 'org-refile
2351 :version "24.1"
2352 :type 'boolean)
2354 (defcustom org-refile-use-outline-path nil
2355 "Non-nil means provide refile targets as paths.
2356 So a level 3 headline will be available as level1/level2/level3.
2358 When the value is `file', also include the file name (without directory)
2359 into the path. In this case, you can also stop the completion after
2360 the file name, to get entries inserted as top level in the file.
2362 When `full-file-path', include the full file path."
2363 :group 'org-refile
2364 :type '(choice
2365 (const :tag "Not" nil)
2366 (const :tag "Yes" t)
2367 (const :tag "Start with file name" file)
2368 (const :tag "Start with full file path" full-file-path)))
2370 (defcustom org-outline-path-complete-in-steps t
2371 "Non-nil means complete the outline path in hierarchical steps.
2372 When Org-mode uses the refile interface to select an outline path
2373 \(see variable `org-refile-use-outline-path'), the completion of
2374 the path can be done is a single go, or if can be done in steps down
2375 the headline hierarchy. Going in steps is probably the best if you
2376 do not use a special completion package like `ido' or `icicles'.
2377 However, when using these packages, going in one step can be very
2378 fast, while still showing the whole path to the entry."
2379 :group 'org-refile
2380 :type 'boolean)
2382 (defcustom org-refile-allow-creating-parent-nodes nil
2383 "Non-nil means allow to create new nodes as refile targets.
2384 New nodes are then created by adding \"/new node name\" to the completion
2385 of an existing node. When the value of this variable is `confirm',
2386 new node creation must be confirmed by the user (recommended).
2387 When nil, the completion must match an existing entry.
2389 Note that, if the new heading is not seen by the criteria
2390 listed in `org-refile-targets', multiple instances of the same
2391 heading would be created by trying again to file under the new
2392 heading."
2393 :group 'org-refile
2394 :type '(choice
2395 (const :tag "Never" nil)
2396 (const :tag "Always" t)
2397 (const :tag "Prompt for confirmation" confirm)))
2399 (defcustom org-refile-active-region-within-subtree nil
2400 "Non-nil means also refile active region within a subtree.
2402 By default `org-refile' doesn't allow refiling regions if they
2403 don't contain a set of subtrees, but it might be convenient to
2404 do so sometimes: in that case, the first line of the region is
2405 converted to a headline before refiling."
2406 :group 'org-refile
2407 :version "24.1"
2408 :type 'boolean)
2410 (defgroup org-todo nil
2411 "Options concerning TODO items in Org-mode."
2412 :tag "Org TODO"
2413 :group 'org)
2415 (defgroup org-progress nil
2416 "Options concerning Progress logging in Org-mode."
2417 :tag "Org Progress"
2418 :group 'org-time)
2420 (defvar org-todo-interpretation-widgets
2421 '((:tag "Sequence (cycling hits every state)" sequence)
2422 (:tag "Type (cycling directly to DONE)" type))
2423 "The available interpretation symbols for customizing `org-todo-keywords'.
2424 Interested libraries should add to this list.")
2426 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2427 "List of TODO entry keyword sequences and their interpretation.
2428 \\<org-mode-map>This is a list of sequences.
2430 Each sequence starts with a symbol, either `sequence' or `type',
2431 indicating if the keywords should be interpreted as a sequence of
2432 action steps, or as different types of TODO items. The first
2433 keywords are states requiring action - these states will select a headline
2434 for inclusion into the global TODO list Org-mode produces. If one of
2435 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2436 signify that no further action is necessary. If \"|\" is not found,
2437 the last keyword is treated as the only DONE state of the sequence.
2439 The command \\[org-todo] cycles an entry through these states, and one
2440 additional state where no keyword is present. For details about this
2441 cycling, see the manual.
2443 TODO keywords and interpretation can also be set on a per-file basis with
2444 the special #+SEQ_TODO and #+TYP_TODO lines.
2446 Each keyword can optionally specify a character for fast state selection
2447 \(in combination with the variable `org-use-fast-todo-selection')
2448 and specifiers for state change logging, using the same syntax that
2449 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2450 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2451 indicates to record a time stamp each time this state is selected.
2453 Each keyword may also specify if a timestamp or a note should be
2454 recorded when entering or leaving the state, by adding additional
2455 characters in the parenthesis after the keyword. This looks like this:
2456 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2457 record only the time of the state change. With X and Y being either
2458 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2459 Y when leaving the state if and only if the *target* state does not
2460 define X. You may omit any of the fast-selection key or X or /Y,
2461 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2463 For backward compatibility, this variable may also be just a list
2464 of keywords. In this case the interpretation (sequence or type) will be
2465 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2466 :group 'org-todo
2467 :group 'org-keywords
2468 :type '(choice
2469 (repeat :tag "Old syntax, just keywords"
2470 (string :tag "Keyword"))
2471 (repeat :tag "New syntax"
2472 (cons
2473 (choice
2474 :tag "Interpretation"
2475 ;;Quick and dirty way to see
2476 ;;`org-todo-interpretations'. This takes the
2477 ;;place of item arguments
2478 :convert-widget
2479 (lambda (widget)
2480 (widget-put widget
2481 :args (mapcar
2482 #'(lambda (x)
2483 (widget-convert
2484 (cons 'const x)))
2485 org-todo-interpretation-widgets))
2486 widget))
2487 (repeat
2488 (string :tag "Keyword"))))))
2490 (defvar org-todo-keywords-1 nil
2491 "All TODO and DONE keywords active in a buffer.")
2492 (make-variable-buffer-local 'org-todo-keywords-1)
2493 (defvar org-todo-keywords-for-agenda nil)
2494 (defvar org-done-keywords-for-agenda nil)
2495 (defvar org-todo-keyword-alist-for-agenda nil)
2496 (defvar org-tag-alist-for-agenda nil
2497 "Alist of all tags from all agenda files.")
2498 (defvar org-tag-groups-alist-for-agenda nil
2499 "Alist of all groups tags from all current agenda files.")
2500 (defvar org-tag-groups-alist nil)
2501 (make-variable-buffer-local 'org-tag-groups-alist)
2502 (defvar org-agenda-contributing-files nil)
2503 (defvar org-not-done-keywords nil)
2504 (make-variable-buffer-local 'org-not-done-keywords)
2505 (defvar org-done-keywords nil)
2506 (make-variable-buffer-local 'org-done-keywords)
2507 (defvar org-todo-heads nil)
2508 (make-variable-buffer-local 'org-todo-heads)
2509 (defvar org-todo-sets nil)
2510 (make-variable-buffer-local 'org-todo-sets)
2511 (defvar org-todo-log-states nil)
2512 (make-variable-buffer-local 'org-todo-log-states)
2513 (defvar org-todo-kwd-alist nil)
2514 (make-variable-buffer-local 'org-todo-kwd-alist)
2515 (defvar org-todo-key-alist nil)
2516 (make-variable-buffer-local 'org-todo-key-alist)
2517 (defvar org-todo-key-trigger nil)
2518 (make-variable-buffer-local 'org-todo-key-trigger)
2520 (defcustom org-todo-interpretation 'sequence
2521 "Controls how TODO keywords are interpreted.
2522 This variable is in principle obsolete and is only used for
2523 backward compatibility, if the interpretation of todo keywords is
2524 not given already in `org-todo-keywords'. See that variable for
2525 more information."
2526 :group 'org-todo
2527 :group 'org-keywords
2528 :type '(choice (const sequence)
2529 (const type)))
2531 (defcustom org-use-fast-todo-selection t
2532 "Non-nil means use the fast todo selection scheme with C-c C-t.
2533 This variable describes if and under what circumstances the cycling
2534 mechanism for TODO keywords will be replaced by a single-key, direct
2535 selection scheme.
2537 When nil, fast selection is never used.
2539 When the symbol `prefix', it will be used when `org-todo' is called
2540 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2541 `C-u t' in an agenda buffer.
2543 When t, fast selection is used by default. In this case, the prefix
2544 argument forces cycling instead.
2546 In all cases, the special interface is only used if access keys have
2547 actually been assigned by the user, i.e. if keywords in the configuration
2548 are followed by a letter in parenthesis, like TODO(t)."
2549 :group 'org-todo
2550 :type '(choice
2551 (const :tag "Never" nil)
2552 (const :tag "By default" t)
2553 (const :tag "Only with C-u C-c C-t" prefix)))
2555 (defcustom org-provide-todo-statistics t
2556 "Non-nil means update todo statistics after insert and toggle.
2557 ALL-HEADLINES means update todo statistics by including headlines
2558 with no TODO keyword as well, counting them as not done.
2559 A list of TODO keywords means the same, but skip keywords that are
2560 not in this list.
2561 When set to a list of two lists, the first list contains keywords
2562 to consider as TODO keywords, the second list contains keywords
2563 to consider as DONE keywords.
2565 When this is set, todo statistics is updated in the parent of the
2566 current entry each time a todo state is changed."
2567 :group 'org-todo
2568 :type '(choice
2569 (const :tag "Yes, only for TODO entries" t)
2570 (const :tag "Yes, including all entries" all-headlines)
2571 (repeat :tag "Yes, for TODOs in this list"
2572 (string :tag "TODO keyword"))
2573 (list :tag "Yes, for TODOs and DONEs in these lists"
2574 (repeat (string :tag "TODO keyword"))
2575 (repeat (string :tag "DONE keyword")))
2576 (other :tag "No TODO statistics" nil)))
2578 (defcustom org-hierarchical-todo-statistics t
2579 "Non-nil means TODO statistics covers just direct children.
2580 When nil, all entries in the subtree are considered.
2581 This has only an effect if `org-provide-todo-statistics' is set.
2582 To set this to nil for only a single subtree, use a COOKIE_DATA
2583 property and include the word \"recursive\" into the value."
2584 :group 'org-todo
2585 :type 'boolean)
2587 (defcustom org-after-todo-state-change-hook nil
2588 "Hook which is run after the state of a TODO item was changed.
2589 The new state (a string with a TODO keyword, or nil) is available in the
2590 Lisp variable `org-state'."
2591 :group 'org-todo
2592 :type 'hook)
2594 (defvar org-blocker-hook nil
2595 "Hook for functions that are allowed to block a state change.
2597 Functions in this hook should not modify the buffer.
2598 Each function gets as its single argument a property list,
2599 see `org-trigger-hook' for more information about this list.
2601 If any of the functions in this hook returns nil, the state change
2602 is blocked.")
2604 (defvar org-trigger-hook nil
2605 "Hook for functions that are triggered by a state change.
2607 Each function gets as its single argument a property list with at
2608 least the following elements:
2610 (:type type-of-change :position pos-at-entry-start
2611 :from old-state :to new-state)
2613 Depending on the type, more properties may be present.
2615 This mechanism is currently implemented for:
2617 TODO state changes
2618 ------------------
2619 :type todo-state-change
2620 :from previous state (keyword as a string), or nil, or a symbol
2621 'todo' or 'done', to indicate the general type of state.
2622 :to new state, like in :from")
2624 (defcustom org-enforce-todo-dependencies nil
2625 "Non-nil means undone TODO entries will block switching the parent to DONE.
2626 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2627 be blocked if any prior sibling is not yet done.
2628 Finally, if the parent is blocked because of ordered siblings of its own,
2629 the child will also be blocked."
2630 :set (lambda (var val)
2631 (set var val)
2632 (if val
2633 (add-hook 'org-blocker-hook
2634 'org-block-todo-from-children-or-siblings-or-parent)
2635 (remove-hook 'org-blocker-hook
2636 'org-block-todo-from-children-or-siblings-or-parent)))
2637 :group 'org-todo
2638 :type 'boolean)
2640 (defcustom org-enforce-todo-checkbox-dependencies nil
2641 "Non-nil means unchecked boxes will block switching the parent to DONE.
2642 When this is nil, checkboxes have no influence on switching TODO states.
2643 When non-nil, you first need to check off all check boxes before the TODO
2644 entry can be switched to DONE.
2645 This variable needs to be set before org.el is loaded, and you need to
2646 restart Emacs after a change to make the change effective. The only way
2647 to change is while Emacs is running is through the customize interface."
2648 :set (lambda (var val)
2649 (set var val)
2650 (if val
2651 (add-hook 'org-blocker-hook
2652 'org-block-todo-from-checkboxes)
2653 (remove-hook 'org-blocker-hook
2654 'org-block-todo-from-checkboxes)))
2655 :group 'org-todo
2656 :type 'boolean)
2658 (defcustom org-treat-insert-todo-heading-as-state-change nil
2659 "Non-nil means inserting a TODO heading is treated as state change.
2660 So when the command \\[org-insert-todo-heading] is used, state change
2661 logging will apply if appropriate. When nil, the new TODO item will
2662 be inserted directly, and no logging will take place."
2663 :group 'org-todo
2664 :type 'boolean)
2666 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2667 "Non-nil means switching TODO states with S-cursor counts as state change.
2668 This is the default behavior. However, setting this to nil allows a
2669 convenient way to select a TODO state and bypass any logging associated
2670 with that."
2671 :group 'org-todo
2672 :type 'boolean)
2674 (defcustom org-todo-state-tags-triggers nil
2675 "Tag changes that should be triggered by TODO state changes.
2676 This is a list. Each entry is
2678 (state-change (tag . flag) .......)
2680 State-change can be a string with a state, and empty string to indicate the
2681 state that has no TODO keyword, or it can be one of the symbols `todo'
2682 or `done', meaning any not-done or done state, respectively."
2683 :group 'org-todo
2684 :group 'org-tags
2685 :type '(repeat
2686 (cons (choice :tag "When changing to"
2687 (const :tag "Not-done state" todo)
2688 (const :tag "Done state" done)
2689 (string :tag "State"))
2690 (repeat
2691 (cons :tag "Tag action"
2692 (string :tag "Tag")
2693 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2695 (defcustom org-log-done nil
2696 "Information to record when a task moves to the DONE state.
2698 Possible values are:
2700 nil Don't add anything, just change the keyword
2701 time Add a time stamp to the task
2702 note Prompt for a note and add it with template `org-log-note-headings'
2704 This option can also be set with on a per-file-basis with
2706 #+STARTUP: nologdone
2707 #+STARTUP: logdone
2708 #+STARTUP: lognotedone
2710 You can have local logging settings for a subtree by setting the LOGGING
2711 property to one or more of these keywords."
2712 :group 'org-todo
2713 :group 'org-progress
2714 :type '(choice
2715 (const :tag "No logging" nil)
2716 (const :tag "Record CLOSED timestamp" time)
2717 (const :tag "Record CLOSED timestamp with note." note)))
2719 ;; Normalize old uses of org-log-done.
2720 (cond
2721 ((eq org-log-done t) (setq org-log-done 'time))
2722 ((and (listp org-log-done) (memq 'done org-log-done))
2723 (setq org-log-done 'note)))
2725 (defcustom org-log-reschedule nil
2726 "Information to record when the scheduling date of a tasks is modified.
2728 Possible values are:
2730 nil Don't add anything, just change the date
2731 time Add a time stamp to the task
2732 note Prompt for a note and add it with template `org-log-note-headings'
2734 This option can also be set with on a per-file-basis with
2736 #+STARTUP: nologreschedule
2737 #+STARTUP: logreschedule
2738 #+STARTUP: lognotereschedule"
2739 :group 'org-todo
2740 :group 'org-progress
2741 :type '(choice
2742 (const :tag "No logging" nil)
2743 (const :tag "Record timestamp" time)
2744 (const :tag "Record timestamp with note." note)))
2746 (defcustom org-log-redeadline nil
2747 "Information to record when the deadline date of a tasks is modified.
2749 Possible values are:
2751 nil Don't add anything, just change the date
2752 time Add a time stamp to the task
2753 note Prompt for a note and add it with template `org-log-note-headings'
2755 This option can also be set with on a per-file-basis with
2757 #+STARTUP: nologredeadline
2758 #+STARTUP: logredeadline
2759 #+STARTUP: lognoteredeadline
2761 You can have local logging settings for a subtree by setting the LOGGING
2762 property to one or more of these keywords."
2763 :group 'org-todo
2764 :group 'org-progress
2765 :type '(choice
2766 (const :tag "No logging" nil)
2767 (const :tag "Record timestamp" time)
2768 (const :tag "Record timestamp with note." note)))
2770 (defcustom org-log-note-clock-out nil
2771 "Non-nil means record a note when clocking out of an item.
2772 This can also be configured on a per-file basis by adding one of
2773 the following lines anywhere in the buffer:
2775 #+STARTUP: lognoteclock-out
2776 #+STARTUP: nolognoteclock-out"
2777 :group 'org-todo
2778 :group 'org-progress
2779 :type 'boolean)
2781 (defcustom org-log-done-with-time t
2782 "Non-nil means the CLOSED time stamp will contain date and time.
2783 When nil, only the date will be recorded."
2784 :group 'org-progress
2785 :type 'boolean)
2787 (defcustom org-log-note-headings
2788 '((done . "CLOSING NOTE %t")
2789 (state . "State %-12s from %-12S %t")
2790 (note . "Note taken on %t")
2791 (reschedule . "Rescheduled from %S on %t")
2792 (delschedule . "Not scheduled, was %S on %t")
2793 (redeadline . "New deadline from %S on %t")
2794 (deldeadline . "Removed deadline, was %S on %t")
2795 (refile . "Refiled on %t")
2796 (clock-out . ""))
2797 "Headings for notes added to entries.
2798 The value is an alist, with the car being a symbol indicating the note
2799 context, and the cdr is the heading to be used. The heading may also be the
2800 empty string.
2801 %t in the heading will be replaced by a time stamp.
2802 %T will be an active time stamp instead the default inactive one
2803 %d will be replaced by a short-format time stamp.
2804 %D will be replaced by an active short-format time stamp.
2805 %s will be replaced by the new TODO state, in double quotes.
2806 %S will be replaced by the old TODO state, in double quotes.
2807 %u will be replaced by the user name.
2808 %U will be replaced by the full user name.
2810 In fact, it is not a good idea to change the `state' entry, because
2811 agenda log mode depends on the format of these entries."
2812 :group 'org-todo
2813 :group 'org-progress
2814 :type '(list :greedy t
2815 (cons (const :tag "Heading when closing an item" done) string)
2816 (cons (const :tag
2817 "Heading when changing todo state (todo sequence only)"
2818 state) string)
2819 (cons (const :tag "Heading when just taking a note" note) string)
2820 (cons (const :tag "Heading when rescheduling" reschedule) string)
2821 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2822 (cons (const :tag "Heading when changing deadline" redeadline) string)
2823 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2824 (cons (const :tag "Heading when refiling" refile) string)
2825 (cons (const :tag "Heading when clocking out" clock-out) string)))
2827 (unless (assq 'note org-log-note-headings)
2828 (push '(note . "%t") org-log-note-headings))
2830 (defcustom org-log-into-drawer nil
2831 "Non-nil means insert state change notes and time stamps into a drawer.
2832 When nil, state changes notes will be inserted after the headline and
2833 any scheduling and clock lines, but not inside a drawer.
2835 The value of this variable should be the name of the drawer to use.
2836 LOGBOOK is proposed as the default drawer for this purpose, you can
2837 also set this to a string to define the drawer of your choice.
2839 A value of t is also allowed, representing \"LOGBOOK\".
2841 A value of t or nil can also be set with on a per-file-basis with
2843 #+STARTUP: logdrawer
2844 #+STARTUP: nologdrawer
2846 If this variable is set, `org-log-state-notes-insert-after-drawers'
2847 will be ignored.
2849 You can set the property LOG_INTO_DRAWER to overrule this setting for
2850 a subtree."
2851 :group 'org-todo
2852 :group 'org-progress
2853 :type '(choice
2854 (const :tag "Not into a drawer" nil)
2855 (const :tag "LOGBOOK" t)
2856 (string :tag "Other")))
2858 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2860 (defun org-log-into-drawer ()
2861 "Return the value of `org-log-into-drawer', but let properties overrule.
2862 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2863 used instead of the default value."
2864 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2865 (cond
2866 ((not p) org-log-into-drawer)
2867 ((equal p "nil") nil)
2868 ((equal p "t") "LOGBOOK")
2869 (t p))))
2871 (defcustom org-log-state-notes-insert-after-drawers nil
2872 "Non-nil means insert state change notes after any drawers in entry.
2873 Only the drawers that *immediately* follow the headline and the
2874 deadline/scheduled line are skipped.
2875 When nil, insert notes right after the heading and perhaps the line
2876 with deadline/scheduling if present.
2878 This variable will have no effect if `org-log-into-drawer' is
2879 set."
2880 :group 'org-todo
2881 :group 'org-progress
2882 :type 'boolean)
2884 (defcustom org-log-states-order-reversed t
2885 "Non-nil means the latest state note will be directly after heading.
2886 When nil, the state change notes will be ordered according to time.
2888 This option can also be set with on a per-file-basis with
2890 #+STARTUP: logstatesreversed
2891 #+STARTUP: nologstatesreversed"
2892 :group 'org-todo
2893 :group 'org-progress
2894 :type 'boolean)
2896 (defcustom org-todo-repeat-to-state nil
2897 "The TODO state to which a repeater should return the repeating task.
2898 By default this is the first task in a TODO sequence, or the previous state
2899 in a TODO_TYP set. But you can specify another task here.
2900 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2901 :group 'org-todo
2902 :version "24.1"
2903 :type '(choice (const :tag "Head of sequence" nil)
2904 (string :tag "Specific state")))
2906 (defcustom org-log-repeat 'time
2907 "Non-nil means record moving through the DONE state when triggering repeat.
2908 An auto-repeating task is immediately switched back to TODO when
2909 marked DONE. If you are not logging state changes (by adding \"@\"
2910 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2911 record a closing note, there will be no record of the task moving
2912 through DONE. This variable forces taking a note anyway.
2914 nil Don't force a record
2915 time Record a time stamp
2916 note Prompt for a note and add it with template `org-log-note-headings'
2918 This option can also be set with on a per-file-basis with
2920 #+STARTUP: nologrepeat
2921 #+STARTUP: logrepeat
2922 #+STARTUP: lognoterepeat
2924 You can have local logging settings for a subtree by setting the LOGGING
2925 property to one or more of these keywords."
2926 :group 'org-todo
2927 :group 'org-progress
2928 :type '(choice
2929 (const :tag "Don't force a record" nil)
2930 (const :tag "Force recording the DONE state" time)
2931 (const :tag "Force recording a note with the DONE state" note)))
2934 (defgroup org-priorities nil
2935 "Priorities in Org-mode."
2936 :tag "Org Priorities"
2937 :group 'org-todo)
2939 (defcustom org-enable-priority-commands t
2940 "Non-nil means priority commands are active.
2941 When nil, these commands will be disabled, so that you never accidentally
2942 set a priority."
2943 :group 'org-priorities
2944 :type 'boolean)
2946 (defcustom org-highest-priority ?A
2947 "The highest priority of TODO items. A character like ?A, ?B etc.
2948 Must have a smaller ASCII number than `org-lowest-priority'."
2949 :group 'org-priorities
2950 :type 'character)
2952 (defcustom org-lowest-priority ?C
2953 "The lowest priority of TODO items. A character like ?A, ?B etc.
2954 Must have a larger ASCII number than `org-highest-priority'."
2955 :group 'org-priorities
2956 :type 'character)
2958 (defcustom org-default-priority ?B
2959 "The default priority of TODO items.
2960 This is the priority an item gets if no explicit priority is given.
2961 When starting to cycle on an empty priority the first step in the cycle
2962 depends on `org-priority-start-cycle-with-default'. The resulting first
2963 step priority must not exceed the range from `org-highest-priority' to
2964 `org-lowest-priority' which means that `org-default-priority' has to be
2965 in this range exclusive or inclusive the range boundaries. Else the
2966 first step refuses to set the default and the second will fall back
2967 to (depending on the command used) the highest or lowest priority."
2968 :group 'org-priorities
2969 :type 'character)
2971 (defcustom org-priority-start-cycle-with-default t
2972 "Non-nil means start with default priority when starting to cycle.
2973 When this is nil, the first step in the cycle will be (depending on the
2974 command used) one higher or lower than the default priority.
2975 See also `org-default-priority'."
2976 :group 'org-priorities
2977 :type 'boolean)
2979 (defcustom org-get-priority-function nil
2980 "Function to extract the priority from a string.
2981 The string is normally the headline. If this is nil Org computes the
2982 priority from the priority cookie like [#A] in the headline. It returns
2983 an integer, increasing by 1000 for each priority level.
2984 The user can set a different function here, which should take a string
2985 as an argument and return the numeric priority."
2986 :group 'org-priorities
2987 :version "24.1"
2988 :type '(choice
2989 (const nil)
2990 (function)))
2992 (defgroup org-time nil
2993 "Options concerning time stamps and deadlines in Org-mode."
2994 :tag "Org Time"
2995 :group 'org)
2997 (defcustom org-insert-labeled-timestamps-at-point nil
2998 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2999 When nil, these labeled time stamps are forces into the second line of an
3000 entry, just after the headline. When scheduling from the global TODO list,
3001 the time stamp will always be forced into the second line."
3002 :group 'org-time
3003 :type 'boolean)
3005 (defcustom org-time-stamp-rounding-minutes '(0 5)
3006 "Number of minutes to round time stamps to.
3007 These are two values, the first applies when first creating a time stamp.
3008 The second applies when changing it with the commands `S-up' and `S-down'.
3009 When changing the time stamp, this means that it will change in steps
3010 of N minutes, as given by the second value.
3012 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3013 numbers should be factors of 60, so for example 5, 10, 15.
3015 When this is larger than 1, you can still force an exact time stamp by using
3016 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
3017 and by using a prefix arg to `S-up/down' to specify the exact number
3018 of minutes to shift."
3019 :group 'org-time
3020 :get #'(lambda (var) ; Make sure both elements are there
3021 (if (integerp (default-value var))
3022 (list (default-value var) 5)
3023 (default-value var)))
3024 :type '(list
3025 (integer :tag "when inserting times")
3026 (integer :tag "when modifying times")))
3028 ;; Normalize old customizations of this variable.
3029 (when (integerp org-time-stamp-rounding-minutes)
3030 (setq org-time-stamp-rounding-minutes
3031 (list org-time-stamp-rounding-minutes
3032 org-time-stamp-rounding-minutes)))
3034 (defcustom org-display-custom-times nil
3035 "Non-nil means overlay custom formats over all time stamps.
3036 The formats are defined through the variable `org-time-stamp-custom-formats'.
3037 To turn this on on a per-file basis, insert anywhere in the file:
3038 #+STARTUP: customtime"
3039 :group 'org-time
3040 :set 'set-default
3041 :type 'sexp)
3042 (make-variable-buffer-local 'org-display-custom-times)
3044 (defcustom org-time-stamp-custom-formats
3045 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3046 "Custom formats for time stamps. See `format-time-string' for the syntax.
3047 These are overlaid over the default ISO format if the variable
3048 `org-display-custom-times' is set. Time like %H:%M should be at the
3049 end of the second format. The custom formats are also honored by export
3050 commands, if custom time display is turned on at the time of export."
3051 :group 'org-time
3052 :type 'sexp)
3054 (defun org-time-stamp-format (&optional long inactive)
3055 "Get the right format for a time string."
3056 (let ((f (if long (cdr org-time-stamp-formats)
3057 (car org-time-stamp-formats))))
3058 (if inactive
3059 (concat "[" (substring f 1 -1) "]")
3060 f)))
3062 (defcustom org-time-clocksum-format
3063 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
3064 "The format string used when creating CLOCKSUM lines.
3065 This is also used when Org mode generates a time duration.
3067 The value can be a single format string containing two
3068 %-sequences, which will be filled with the number of hours and
3069 minutes in that order.
3071 Alternatively, the value can be a plist associating any of the
3072 keys :years, :months, :weeks, :days, :hours or :minutes with
3073 format strings. The time duration is formatted using only the
3074 time components that are needed and concatenating the results.
3075 If a time unit in absent, it falls back to the next smallest
3076 unit.
3078 The keys :require-years, :require-months, :require-days,
3079 :require-weeks, :require-hours, :require-minutes are also
3080 meaningful. A non-nil value for these keys indicates that the
3081 corresponding time component should always be included, even if
3082 its value is 0.
3085 For example,
3087 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
3088 :require-minutes t)
3090 means durations longer than a day will be expressed in days,
3091 hours and minutes, and durations less than a day will always be
3092 expressed in hours and minutes (even for durations less than an
3093 hour).
3095 The value
3097 \(:days \"%dd\" :minutes \"%dm\")
3099 means durations longer than a day will be expressed in days and
3100 minutes, and durations less than a day will be expressed entirely
3101 in minutes (even for durations longer than an hour)."
3102 :group 'org-time
3103 :group 'org-clock
3104 :version "24.4"
3105 :package-version '(Org . "8.0")
3106 :type '(choice (string :tag "Format string")
3107 (set :tag "Plist"
3108 (group :inline t (const :tag "Years" :years)
3109 (string :tag "Format string"))
3110 (group :inline t
3111 (const :tag "Always show years" :require-years)
3112 (const t))
3113 (group :inline t (const :tag "Months" :months)
3114 (string :tag "Format string"))
3115 (group :inline t
3116 (const :tag "Always show months" :require-months)
3117 (const t))
3118 (group :inline t (const :tag "Weeks" :weeks)
3119 (string :tag "Format string"))
3120 (group :inline t
3121 (const :tag "Always show weeks" :require-weeks)
3122 (const t))
3123 (group :inline t (const :tag "Days" :days)
3124 (string :tag "Format string"))
3125 (group :inline t
3126 (const :tag "Always show days" :require-days)
3127 (const t))
3128 (group :inline t (const :tag "Hours" :hours)
3129 (string :tag "Format string"))
3130 (group :inline t
3131 (const :tag "Always show hours" :require-hours)
3132 (const t))
3133 (group :inline t (const :tag "Minutes" :minutes)
3134 (string :tag "Format string"))
3135 (group :inline t
3136 (const :tag "Always show minutes" :require-minutes)
3137 (const t)))))
3139 (defcustom org-time-clocksum-use-fractional nil
3140 "When non-nil, \\[org-clock-display] uses fractional times.
3141 See `org-time-clocksum-format' for more on time clock formats."
3142 :group 'org-time
3143 :group 'org-clock
3144 :version "24.3"
3145 :type 'boolean)
3147 (defcustom org-time-clocksum-use-effort-durations nil
3148 "When non-nil, \\[org-clock-display] uses effort durations.
3149 E.g. by default, one day is considered to be a 8 hours effort,
3150 so a task that has been clocked for 16 hours will be displayed
3151 as during 2 days in the clock display or in the clocktable.
3153 See `org-effort-durations' on how to set effort durations
3154 and `org-time-clocksum-format' for more on time clock formats."
3155 :group 'org-time
3156 :group 'org-clock
3157 :version "24.4"
3158 :package-version '(Org . "8.0")
3159 :type 'boolean)
3161 (defcustom org-time-clocksum-fractional-format "%.2f"
3162 "The format string used when creating CLOCKSUM lines,
3163 or when Org mode generates a time duration, if
3164 `org-time-clocksum-use-fractional' is enabled.
3166 The value can be a single format string containing one
3167 %-sequence, which will be filled with the number of hours as
3168 a float.
3170 Alternatively, the value can be a plist associating any of the
3171 keys :years, :months, :weeks, :days, :hours or :minutes with
3172 a format string. The time duration is formatted using the
3173 largest time unit which gives a non-zero integer part. If all
3174 specified formats have zero integer part, the smallest time unit
3175 is used."
3176 :group 'org-time
3177 :type '(choice (string :tag "Format string")
3178 (set (group :inline t (const :tag "Years" :years)
3179 (string :tag "Format string"))
3180 (group :inline t (const :tag "Months" :months)
3181 (string :tag "Format string"))
3182 (group :inline t (const :tag "Weeks" :weeks)
3183 (string :tag "Format string"))
3184 (group :inline t (const :tag "Days" :days)
3185 (string :tag "Format string"))
3186 (group :inline t (const :tag "Hours" :hours)
3187 (string :tag "Format string"))
3188 (group :inline t (const :tag "Minutes" :minutes)
3189 (string :tag "Format string")))))
3191 (defcustom org-deadline-warning-days 14
3192 "Number of days before expiration during which a deadline becomes active.
3193 This variable governs the display in sparse trees and in the agenda.
3194 When 0 or negative, it means use this number (the absolute value of it)
3195 even if a deadline has a different individual lead time specified.
3197 Custom commands can set this variable in the options section."
3198 :group 'org-time
3199 :group 'org-agenda-daily/weekly
3200 :type 'integer)
3202 (defcustom org-scheduled-delay-days 0
3203 "Number of days before a scheduled item becomes active.
3204 This variable governs the display in sparse trees and in the agenda.
3205 The default value (i.e. 0) means: don't delay scheduled item.
3206 When negative, it means use this number (the absolute value of it)
3207 even if a scheduled item has a different individual delay time
3208 specified.
3210 Custom commands can set this variable in the options section."
3211 :group 'org-time
3212 :group 'org-agenda-daily/weekly
3213 :version "24.4"
3214 :package-version '(Org . "8.0")
3215 :type 'integer)
3217 (defcustom org-read-date-prefer-future t
3218 "Non-nil means assume future for incomplete date input from user.
3219 This affects the following situations:
3220 1. The user gives a month but not a year.
3221 For example, if it is April and you enter \"feb 2\", this will be read
3222 as Feb 2, *next* year. \"May 5\", however, will be this year.
3223 2. The user gives a day, but no month.
3224 For example, if today is the 15th, and you enter \"3\", Org-mode will
3225 read this as the third of *next* month. However, if you enter \"17\",
3226 it will be considered as *this* month.
3228 If you set this variable to the symbol `time', then also the following
3229 will work:
3231 3. If the user gives a time.
3232 If the time is before now, it will be interpreted as tomorrow.
3234 Currently none of this works for ISO week specifications.
3236 When this option is nil, the current day, month and year will always be
3237 used as defaults.
3239 See also `org-agenda-jump-prefer-future'."
3240 :group 'org-time
3241 :type '(choice
3242 (const :tag "Never" nil)
3243 (const :tag "Check month and day" t)
3244 (const :tag "Check month, day, and time" time)))
3246 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3247 "Should the agenda jump command prefer the future for incomplete dates?
3248 The default is to do the same as configured in `org-read-date-prefer-future'.
3249 But you can also set a deviating value here.
3250 This may t or nil, or the symbol `org-read-date-prefer-future'."
3251 :group 'org-agenda
3252 :group 'org-time
3253 :version "24.1"
3254 :type '(choice
3255 (const :tag "Use org-read-date-prefer-future"
3256 org-read-date-prefer-future)
3257 (const :tag "Never" nil)
3258 (const :tag "Always" t)))
3260 (defcustom org-read-date-force-compatible-dates t
3261 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3263 Depending on the system Emacs is running on, certain dates cannot
3264 be represented with the type used internally to represent time.
3265 Dates between 1970-1-1 and 2038-1-1 can always be represented
3266 correctly. Some systems allow for earlier dates, some for later,
3267 some for both. One way to find out it to insert any date into an
3268 Org buffer, putting the cursor on the year and hitting S-up and
3269 S-down to test the range.
3271 When this variable is set to t, the date/time prompt will not let
3272 you specify dates outside the 1970-2037 range, so it is certain that
3273 these dates will work in whatever version of Emacs you are
3274 running, and also that you can move a file from one Emacs implementation
3275 to another. WHenever Org is forcing the year for you, it will display
3276 a message and beep.
3278 When this variable is nil, Org will check if the date is
3279 representable in the specific Emacs implementation you are using.
3280 If not, it will force a year, usually the current year, and beep
3281 to remind you. Currently this setting is not recommended because
3282 the likelihood that you will open your Org files in an Emacs that
3283 has limited date range is not negligible.
3285 A workaround for this problem is to use diary sexp dates for time
3286 stamps outside of this range."
3287 :group 'org-time
3288 :version "24.1"
3289 :type 'boolean)
3291 (defcustom org-read-date-display-live t
3292 "Non-nil means display current interpretation of date prompt live.
3293 This display will be in an overlay, in the minibuffer."
3294 :group 'org-time
3295 :type 'boolean)
3297 (defcustom org-read-date-popup-calendar t
3298 "Non-nil means pop up a calendar when prompting for a date.
3299 In the calendar, the date can be selected with mouse-1. However, the
3300 minibuffer will also be active, and you can simply enter the date as well.
3301 When nil, only the minibuffer will be available."
3302 :group 'org-time
3303 :type 'boolean)
3304 (org-defvaralias 'org-popup-calendar-for-date-prompt
3305 'org-read-date-popup-calendar)
3307 (make-obsolete-variable
3308 'org-read-date-minibuffer-setup-hook
3309 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3310 (defcustom org-read-date-minibuffer-setup-hook nil
3311 "Hook to be used to set up keys for the date/time interface.
3312 Add key definitions to `minibuffer-local-map', which will be a
3313 temporary copy.
3315 WARNING: This option is obsolete, you should use
3316 `org-read-date-minibuffer-local-map' to set up keys."
3317 :group 'org-time
3318 :type 'hook)
3320 (defcustom org-extend-today-until 0
3321 "The hour when your day really ends. Must be an integer.
3322 This has influence for the following applications:
3323 - When switching the agenda to \"today\". It it is still earlier than
3324 the time given here, the day recognized as TODAY is actually yesterday.
3325 - When a date is read from the user and it is still before the time given
3326 here, the current date and time will be assumed to be yesterday, 23:59.
3327 Also, timestamps inserted in capture templates follow this rule.
3329 IMPORTANT: This is a feature whose implementation is and likely will
3330 remain incomplete. Really, it is only here because past midnight seems to
3331 be the favorite working time of John Wiegley :-)"
3332 :group 'org-time
3333 :type 'integer)
3335 (defcustom org-use-effective-time nil
3336 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3337 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3338 \"effective time\" of any timestamps between midnight and 8am will be
3339 23:59 of the previous day."
3340 :group 'org-time
3341 :version "24.1"
3342 :type 'boolean)
3344 (defcustom org-use-last-clock-out-time-as-effective-time nil
3345 "When non-nil, use the last clock out time for `org-todo'.
3346 Note that this option has precedence over the combined use of
3347 `org-use-effective-time' and `org-extend-today-until'."
3348 :group 'org-time
3349 :version "24.4"
3350 :package-version '(Org . "8.0")
3351 :type 'boolean)
3353 (defcustom org-edit-timestamp-down-means-later nil
3354 "Non-nil means S-down will increase the time in a time stamp.
3355 When nil, S-up will increase."
3356 :group 'org-time
3357 :type 'boolean)
3359 (defcustom org-calendar-follow-timestamp-change t
3360 "Non-nil means make the calendar window follow timestamp changes.
3361 When a timestamp is modified and the calendar window is visible, it will be
3362 moved to the new date."
3363 :group 'org-time
3364 :type 'boolean)
3366 (defgroup org-tags nil
3367 "Options concerning tags in Org-mode."
3368 :tag "Org Tags"
3369 :group 'org)
3371 (defcustom org-tag-alist nil
3372 "List of tags allowed in Org-mode files.
3373 When this list is nil, Org-mode will base TAG input on what is already in the
3374 buffer.
3375 The value of this variable is an alist, the car of each entry must be a
3376 keyword as a string, the cdr may be a character that is used to select
3377 that tag through the fast-tag-selection interface.
3378 See the manual for details."
3379 :group 'org-tags
3380 :type '(repeat
3381 (choice
3382 (cons (string :tag "Tag name")
3383 (character :tag "Access char"))
3384 (list :tag "Start radio group"
3385 (const :startgroup)
3386 (option (string :tag "Group description")))
3387 (list :tag "Group tags delimiter"
3388 (const :grouptags))
3389 (list :tag "End radio group"
3390 (const :endgroup)
3391 (option (string :tag "Group description")))
3392 (const :tag "New line" (:newline)))))
3394 (defcustom org-tag-persistent-alist nil
3395 "List of tags that will always appear in all Org-mode files.
3396 This is in addition to any in buffer settings or customizations
3397 of `org-tag-alist'.
3398 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3399 The value of this variable is an alist, the car of each entry must be a
3400 keyword as a string, the cdr may be a character that is used to select
3401 that tag through the fast-tag-selection interface.
3402 See the manual for details.
3403 To disable these tags on a per-file basis, insert anywhere in the file:
3404 #+STARTUP: noptag"
3405 :group 'org-tags
3406 :type '(repeat
3407 (choice
3408 (cons (string :tag "Tag name")
3409 (character :tag "Access char"))
3410 (const :tag "Start radio group" (:startgroup))
3411 (const :tag "Group tags delimiter" (:grouptags))
3412 (const :tag "End radio group" (:endgroup))
3413 (const :tag "New line" (:newline)))))
3415 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3416 "If non-nil, always offer completion for all tags of all agenda files.
3417 Instead of customizing this variable directly, you might want to
3418 set it locally for capture buffers, because there no list of
3419 tags in that file can be created dynamically (there are none).
3421 (add-hook 'org-capture-mode-hook
3422 (lambda ()
3423 (set (make-local-variable
3424 'org-complete-tags-always-offer-all-agenda-tags)
3425 t)))"
3426 :group 'org-tags
3427 :version "24.1"
3428 :type 'boolean)
3430 (defvar org-file-tags nil
3431 "List of tags that can be inherited by all entries in the file.
3432 The tags will be inherited if the variable `org-use-tag-inheritance'
3433 says they should be.
3434 This variable is populated from #+FILETAGS lines.")
3436 (defcustom org-use-fast-tag-selection 'auto
3437 "Non-nil means use fast tag selection scheme.
3438 This is a special interface to select and deselect tags with single keys.
3439 When nil, fast selection is never used.
3440 When the symbol `auto', fast selection is used if and only if selection
3441 characters for tags have been configured, either through the variable
3442 `org-tag-alist' or through a #+TAGS line in the buffer.
3443 When t, fast selection is always used and selection keys are assigned
3444 automatically if necessary."
3445 :group 'org-tags
3446 :type '(choice
3447 (const :tag "Always" t)
3448 (const :tag "Never" nil)
3449 (const :tag "When selection characters are configured" auto)))
3451 (defcustom org-fast-tag-selection-single-key nil
3452 "Non-nil means fast tag selection exits after first change.
3453 When nil, you have to press RET to exit it.
3454 During fast tag selection, you can toggle this flag with `C-c'.
3455 This variable can also have the value `expert'. In this case, the window
3456 displaying the tags menu is not even shown, until you press C-c again."
3457 :group 'org-tags
3458 :type '(choice
3459 (const :tag "No" nil)
3460 (const :tag "Yes" t)
3461 (const :tag "Expert" expert)))
3463 (defvar org-fast-tag-selection-include-todo nil
3464 "Non-nil means fast tags selection interface will also offer TODO states.
3465 This is an undocumented feature, you should not rely on it.")
3467 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3468 "The column to which tags should be indented in a headline.
3469 If this number is positive, it specifies the column. If it is negative,
3470 it means that the tags should be flushright to that column. For example,
3471 -80 works well for a normal 80 character screen.
3472 When 0, place tags directly after headline text, with only one space in
3473 between."
3474 :group 'org-tags
3475 :type 'integer)
3477 (defcustom org-auto-align-tags t
3478 "Non-nil keeps tags aligned when modifying headlines.
3479 Some operations (i.e. demoting) change the length of a headline and
3480 therefore shift the tags around. With this option turned on, after
3481 each such operation the tags are again aligned to `org-tags-column'."
3482 :group 'org-tags
3483 :type 'boolean)
3485 (defcustom org-use-tag-inheritance t
3486 "Non-nil means tags in levels apply also for sublevels.
3487 When nil, only the tags directly given in a specific line apply there.
3488 This may also be a list of tags that should be inherited, or a regexp that
3489 matches tags that should be inherited. Additional control is possible
3490 with the variable `org-tags-exclude-from-inheritance' which gives an
3491 explicit list of tags to be excluded from inheritance, even if the value of
3492 `org-use-tag-inheritance' would select it for inheritance.
3494 If this option is t, a match early-on in a tree can lead to a large
3495 number of matches in the subtree when constructing the agenda or creating
3496 a sparse tree. If you only want to see the first match in a tree during
3497 a search, check out the variable `org-tags-match-list-sublevels'."
3498 :group 'org-tags
3499 :type '(choice
3500 (const :tag "Not" nil)
3501 (const :tag "Always" t)
3502 (repeat :tag "Specific tags" (string :tag "Tag"))
3503 (regexp :tag "Tags matched by regexp")))
3505 (defcustom org-tags-exclude-from-inheritance nil
3506 "List of tags that should never be inherited.
3507 This is a way to exclude a few tags from inheritance. For way to do
3508 the opposite, to actively allow inheritance for selected tags,
3509 see the variable `org-use-tag-inheritance'."
3510 :group 'org-tags
3511 :type '(repeat (string :tag "Tag")))
3513 (defun org-tag-inherit-p (tag)
3514 "Check if TAG is one that should be inherited."
3515 (cond
3516 ((member tag org-tags-exclude-from-inheritance) nil)
3517 ((eq org-use-tag-inheritance t) t)
3518 ((not org-use-tag-inheritance) nil)
3519 ((stringp org-use-tag-inheritance)
3520 (string-match org-use-tag-inheritance tag))
3521 ((listp org-use-tag-inheritance)
3522 (member tag org-use-tag-inheritance))
3523 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3525 (defcustom org-tags-match-list-sublevels t
3526 "Non-nil means list also sublevels of headlines matching a search.
3527 This variable applies to tags/property searches, and also to stuck
3528 projects because this search is based on a tags match as well.
3530 When set to the symbol `indented', sublevels are indented with
3531 leading dots.
3533 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3534 the sublevels of a headline matching a tag search often also match
3535 the same search. Listing all of them can create very long lists.
3536 Setting this variable to nil causes subtrees of a match to be skipped.
3538 This variable is semi-obsolete and probably should always be true. It
3539 is better to limit inheritance to certain tags using the variables
3540 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3541 :group 'org-tags
3542 :type '(choice
3543 (const :tag "No, don't list them" nil)
3544 (const :tag "Yes, do list them" t)
3545 (const :tag "List them, indented with leading dots" indented)))
3547 (defcustom org-tags-sort-function nil
3548 "When set, tags are sorted using this function as a comparator."
3549 :group 'org-tags
3550 :type '(choice
3551 (const :tag "No sorting" nil)
3552 (const :tag "Alphabetical" string<)
3553 (const :tag "Reverse alphabetical" string>)
3554 (function :tag "Custom function" nil)))
3556 (defvar org-tags-history nil
3557 "History of minibuffer reads for tags.")
3558 (defvar org-last-tags-completion-table nil
3559 "The last used completion table for tags.")
3560 (defvar org-after-tags-change-hook nil
3561 "Hook that is run after the tags in a line have changed.")
3563 (defgroup org-properties nil
3564 "Options concerning properties in Org-mode."
3565 :tag "Org Properties"
3566 :group 'org)
3568 (defcustom org-property-format "%-10s %s"
3569 "How property key/value pairs should be formatted by `indent-line'.
3570 When `indent-line' hits a property definition, it will format the line
3571 according to this format, mainly to make sure that the values are
3572 lined-up with respect to each other."
3573 :group 'org-properties
3574 :type 'string)
3576 (defcustom org-properties-postprocess-alist nil
3577 "Alist of properties and functions to adjust inserted values.
3578 Elements of this alist must be of the form
3580 ([string] [function])
3582 where [string] must be a property name and [function] must be a
3583 lambda expression: this lambda expression must take one argument,
3584 the value to adjust, and return the new value as a string.
3586 For example, this element will allow the property \"Remaining\"
3587 to be updated wrt the relation between the \"Effort\" property
3588 and the clock summary:
3590 ((\"Remaining\" (lambda(value)
3591 (let ((clocksum (org-clock-sum-current-item))
3592 (effort (org-duration-string-to-minutes
3593 (org-entry-get (point) \"Effort\"))))
3594 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3595 :group 'org-properties
3596 :version "24.1"
3597 :type '(alist :key-type (string :tag "Property")
3598 :value-type (function :tag "Function")))
3600 (defcustom org-use-property-inheritance nil
3601 "Non-nil means properties apply also for sublevels.
3603 This setting is chiefly used during property searches. Turning it on can
3604 cause significant overhead when doing a search, which is why it is not
3605 on by default.
3607 When nil, only the properties directly given in the current entry count.
3608 When t, every property is inherited. The value may also be a list of
3609 properties that should have inheritance, or a regular expression matching
3610 properties that should be inherited.
3612 However, note that some special properties use inheritance under special
3613 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3614 and the properties ending in \"_ALL\" when they are used as descriptor
3615 for valid values of a property.
3617 Note for programmers:
3618 When querying an entry with `org-entry-get', you can control if inheritance
3619 should be used. By default, `org-entry-get' looks only at the local
3620 properties. You can request inheritance by setting the inherit argument
3621 to t (to force inheritance) or to `selective' (to respect the setting
3622 in this variable)."
3623 :group 'org-properties
3624 :type '(choice
3625 (const :tag "Not" nil)
3626 (const :tag "Always" t)
3627 (repeat :tag "Specific properties" (string :tag "Property"))
3628 (regexp :tag "Properties matched by regexp")))
3630 (defun org-property-inherit-p (property)
3631 "Check if PROPERTY is one that should be inherited."
3632 (cond
3633 ((eq org-use-property-inheritance t) t)
3634 ((not org-use-property-inheritance) nil)
3635 ((stringp org-use-property-inheritance)
3636 (string-match org-use-property-inheritance property))
3637 ((listp org-use-property-inheritance)
3638 (member property org-use-property-inheritance))
3639 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3641 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3642 "The default column format, if no other format has been defined.
3643 This variable can be set on the per-file basis by inserting a line
3645 #+COLUMNS: %25ITEM ....."
3646 :group 'org-properties
3647 :type 'string)
3649 (defcustom org-columns-ellipses ".."
3650 "The ellipses to be used when a field in column view is truncated.
3651 When this is the empty string, as many characters as possible are shown,
3652 but then there will be no visual indication that the field has been truncated.
3653 When this is a string of length N, the last N characters of a truncated
3654 field are replaced by this string. If the column is narrower than the
3655 ellipses string, only part of the ellipses string will be shown."
3656 :group 'org-properties
3657 :type 'string)
3659 (defcustom org-columns-modify-value-for-display-function nil
3660 "Function that modifies values for display in column view.
3661 For example, it can be used to cut out a certain part from a time stamp.
3662 The function must take 2 arguments:
3664 column-title The title of the column (*not* the property name)
3665 value The value that should be modified.
3667 The function should return the value that should be displayed,
3668 or nil if the normal value should be used."
3669 :group 'org-properties
3670 :type '(choice (const nil) (function)))
3672 (defconst org-global-properties-fixed
3673 '(("VISIBILITY_ALL" . "folded children content all")
3674 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3675 "List of property/value pairs that can be inherited by any entry.
3677 These are fixed values, for the preset properties. The user variable
3678 that can be used to add to this list is `org-global-properties'.
3680 The entries in this list are cons cells where the car is a property
3681 name and cdr is a string with the value. If the value represents
3682 multiple items like an \"_ALL\" property, separate the items by
3683 spaces.")
3685 (defcustom org-global-properties nil
3686 "List of property/value pairs that can be inherited by any entry.
3688 This list will be combined with the constant `org-global-properties-fixed'.
3690 The entries in this list are cons cells where the car is a property
3691 name and cdr is a string with the value.
3693 You can set buffer-local values for the same purpose in the variable
3694 `org-file-properties' this by adding lines like
3696 #+PROPERTY: NAME VALUE"
3697 :group 'org-properties
3698 :type '(repeat
3699 (cons (string :tag "Property")
3700 (string :tag "Value"))))
3702 (defvar org-file-properties nil
3703 "List of property/value pairs that can be inherited by any entry.
3704 Valid for the current buffer.
3705 This variable is populated from #+PROPERTY lines.")
3706 (make-variable-buffer-local 'org-file-properties)
3708 (defgroup org-agenda nil
3709 "Options concerning agenda views in Org-mode."
3710 :tag "Org Agenda"
3711 :group 'org)
3713 (defvar org-category nil
3714 "Variable used by org files to set a category for agenda display.
3715 Such files should use a file variable to set it, for example
3717 # -*- mode: org; org-category: \"ELisp\"
3719 or contain a special line
3721 #+CATEGORY: ELisp
3723 If the file does not specify a category, then file's base name
3724 is used instead.")
3725 (make-variable-buffer-local 'org-category)
3726 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3728 (defcustom org-agenda-files nil
3729 "The files to be used for agenda display.
3730 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3731 \\[org-remove-file]. You can also use customize to edit the list.
3733 If an entry is a directory, all files in that directory that are matched by
3734 `org-agenda-file-regexp' will be part of the file list.
3736 If the value of the variable is not a list but a single file name, then
3737 the list of agenda files is actually stored and maintained in that file, one
3738 agenda file per line. In this file paths can be given relative to
3739 `org-directory'. Tilde expansion and environment variable substitution
3740 are also made."
3741 :group 'org-agenda
3742 :type '(choice
3743 (repeat :tag "List of files and directories" file)
3744 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3746 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3747 "Regular expression to match files for `org-agenda-files'.
3748 If any element in the list in that variable contains a directory instead
3749 of a normal file, all files in that directory that are matched by this
3750 regular expression will be included."
3751 :group 'org-agenda
3752 :type 'regexp)
3754 (defcustom org-agenda-text-search-extra-files nil
3755 "List of extra files to be searched by text search commands.
3756 These files will be searched in addition to the agenda files by the
3757 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3758 Note that these files will only be searched for text search commands,
3759 not for the other agenda views like todo lists, tag searches or the weekly
3760 agenda. This variable is intended to list notes and possibly archive files
3761 that should also be searched by these two commands.
3762 In fact, if the first element in the list is the symbol `agenda-archives',
3763 then all archive files of all agenda files will be added to the search
3764 scope."
3765 :group 'org-agenda
3766 :type '(set :greedy t
3767 (const :tag "Agenda Archives" agenda-archives)
3768 (repeat :inline t (file))))
3770 (org-defvaralias 'org-agenda-multi-occur-extra-files
3771 'org-agenda-text-search-extra-files)
3773 (defcustom org-agenda-skip-unavailable-files nil
3774 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3775 A nil value means to remove them, after a query, from the list."
3776 :group 'org-agenda
3777 :type 'boolean)
3779 (defcustom org-calendar-to-agenda-key [?c]
3780 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3781 The command `org-calendar-goto-agenda' will be bound to this key. The
3782 default is the character `c' because then `c' can be used to switch back and
3783 forth between agenda and calendar."
3784 :group 'org-agenda
3785 :type 'sexp)
3787 (defcustom org-calendar-insert-diary-entry-key [?i]
3788 "The key to be installed in `calendar-mode-map' for adding diary entries.
3789 This option is irrelevant until `org-agenda-diary-file' has been configured
3790 to point to an Org-mode file. When that is the case, the command
3791 `org-agenda-diary-entry' will be bound to the key given here, by default
3792 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3793 if you want to continue doing this, you need to change this to a different
3794 key."
3795 :group 'org-agenda
3796 :type 'sexp)
3798 (defcustom org-agenda-diary-file 'diary-file
3799 "File to which to add new entries with the `i' key in agenda and calendar.
3800 When this is the symbol `diary-file', the functionality in the Emacs
3801 calendar will be used to add entries to the `diary-file'. But when this
3802 points to a file, `org-agenda-diary-entry' will be used instead."
3803 :group 'org-agenda
3804 :type '(choice
3805 (const :tag "The standard Emacs diary file" diary-file)
3806 (file :tag "Special Org file diary entries")))
3808 (eval-after-load "calendar"
3809 '(progn
3810 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3811 'org-calendar-goto-agenda)
3812 (add-hook 'calendar-mode-hook
3813 (lambda ()
3814 (unless (eq org-agenda-diary-file 'diary-file)
3815 (define-key calendar-mode-map
3816 org-calendar-insert-diary-entry-key
3817 'org-agenda-diary-entry))))))
3819 (defgroup org-latex nil
3820 "Options for embedding LaTeX code into Org-mode."
3821 :tag "Org LaTeX"
3822 :group 'org)
3824 (defcustom org-format-latex-options
3825 '(:foreground default :background default :scale 1.0
3826 :html-foreground "Black" :html-background "Transparent"
3827 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3828 "Options for creating images from LaTeX fragments.
3829 This is a property list with the following properties:
3830 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3831 `default' means use the foreground of the default face.
3832 `auto' means use the foreground from the text face.
3833 :background the background color, or \"Transparent\".
3834 `default' means use the background of the default face.
3835 `auto' means use the background from the text face.
3836 :scale a scaling factor for the size of the images, to get more pixels
3837 :html-foreground, :html-background, :html-scale
3838 the same numbers for HTML export.
3839 :matchers a list indicating which matchers should be used to
3840 find LaTeX fragments. Valid members of this list are:
3841 \"begin\" find environments
3842 \"$1\" find single characters surrounded by $.$
3843 \"$\" find math expressions surrounded by $...$
3844 \"$$\" find math expressions surrounded by $$....$$
3845 \"\\(\" find math expressions surrounded by \\(...\\)
3846 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3847 :group 'org-latex
3848 :type 'plist)
3850 (defcustom org-format-latex-signal-error t
3851 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3852 When nil, just push out a message."
3853 :group 'org-latex
3854 :version "24.1"
3855 :type 'boolean)
3857 (defcustom org-latex-to-mathml-jar-file nil
3858 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3859 Use this to specify additional executable file say a jar file.
3861 When using MathToWeb as the converter, specify the full-path to
3862 your mathtoweb.jar file."
3863 :group 'org-latex
3864 :version "24.1"
3865 :type '(choice
3866 (const :tag "None" nil)
3867 (file :tag "JAR file" :must-match t)))
3869 (defcustom org-latex-to-mathml-convert-command nil
3870 "Command to convert LaTeX fragments to MathML.
3871 Replace format-specifiers in the command as noted below and use
3872 `shell-command' to convert LaTeX to MathML.
3873 %j: Executable file in fully expanded form as specified by
3874 `org-latex-to-mathml-jar-file'.
3875 %I: Input LaTeX file in fully expanded form
3876 %o: Output MathML file
3877 This command is used by `org-create-math-formula'.
3879 When using MathToWeb as the converter, set this to
3880 \"java -jar %j -unicode -force -df %o %I\"."
3881 :group 'org-latex
3882 :version "24.1"
3883 :type '(choice
3884 (const :tag "None" nil)
3885 (string :tag "\nShell command")))
3887 (defcustom org-latex-create-formula-image-program 'dvipng
3888 "Program to convert LaTeX fragments with.
3890 dvipng Process the LaTeX fragments to dvi file, then convert
3891 dvi files to png files using dvipng.
3892 This will also include processing of non-math environments.
3893 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3894 to convert pdf files to png files"
3895 :group 'org-latex
3896 :version "24.1"
3897 :type '(choice
3898 (const :tag "dvipng" dvipng)
3899 (const :tag "imagemagick" imagemagick)))
3901 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3902 "Path to store latex preview images.
3903 A relative path here creates many directories relative to the
3904 processed org files paths. An absolute path puts all preview
3905 images at the same place."
3906 :group 'org-latex
3907 :version "24.3"
3908 :type 'string)
3910 (defun org-format-latex-mathml-available-p ()
3911 "Return t if `org-latex-to-mathml-convert-command' is usable."
3912 (save-match-data
3913 (when (and (boundp 'org-latex-to-mathml-convert-command)
3914 org-latex-to-mathml-convert-command)
3915 (let ((executable (car (split-string
3916 org-latex-to-mathml-convert-command))))
3917 (when (executable-find executable)
3918 (if (string-match
3919 "%j" org-latex-to-mathml-convert-command)
3920 (file-readable-p org-latex-to-mathml-jar-file)
3921 t))))))
3923 (defcustom org-format-latex-header "\\documentclass{article}
3924 \\usepackage[usenames]{color}
3925 \[PACKAGES]
3926 \[DEFAULT-PACKAGES]
3927 \\pagestyle{empty} % do not remove
3928 % The settings below are copied from fullpage.sty
3929 \\setlength{\\textwidth}{\\paperwidth}
3930 \\addtolength{\\textwidth}{-3cm}
3931 \\setlength{\\oddsidemargin}{1.5cm}
3932 \\addtolength{\\oddsidemargin}{-2.54cm}
3933 \\setlength{\\evensidemargin}{\\oddsidemargin}
3934 \\setlength{\\textheight}{\\paperheight}
3935 \\addtolength{\\textheight}{-\\headheight}
3936 \\addtolength{\\textheight}{-\\headsep}
3937 \\addtolength{\\textheight}{-\\footskip}
3938 \\addtolength{\\textheight}{-3cm}
3939 \\setlength{\\topmargin}{1.5cm}
3940 \\addtolength{\\topmargin}{-2.54cm}"
3941 "The document header used for processing LaTeX fragments.
3942 It is imperative that this header make sure that no page number
3943 appears on the page. The package defined in the variables
3944 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3945 will either replace the placeholder \"[PACKAGES]\" in this
3946 header, or they will be appended."
3947 :group 'org-latex
3948 :type 'string)
3950 (defun org-set-packages-alist (var val)
3951 "Set the packages alist and make sure it has 3 elements per entry."
3952 (set var (mapcar (lambda (x)
3953 (if (and (consp x) (= (length x) 2))
3954 (list (car x) (nth 1 x) t)
3956 val)))
3958 (defun org-get-packages-alist (var)
3959 "Get the packages alist and make sure it has 3 elements per entry."
3960 (mapcar (lambda (x)
3961 (if (and (consp x) (= (length x) 2))
3962 (list (car x) (nth 1 x) t)
3964 (default-value var)))
3966 (defcustom org-latex-default-packages-alist
3967 '(("AUTO" "inputenc" t)
3968 ("T1" "fontenc" t)
3969 ("" "fixltx2e" nil)
3970 ("" "graphicx" t)
3971 ("" "longtable" nil)
3972 ("" "float" nil)
3973 ("" "wrapfig" nil)
3974 ("" "rotating" nil)
3975 ("normalem" "ulem" t)
3976 ("" "amsmath" t)
3977 ("" "textcomp" t)
3978 ("" "marvosym" t)
3979 ("" "wasysym" t)
3980 ("" "amssymb" t)
3981 ("" "hyperref" nil)
3982 "\\tolerance=1000")
3983 "Alist of default packages to be inserted in the header.
3985 Change this only if one of the packages here causes an
3986 incompatibility with another package you are using.
3988 The packages in this list are needed by one part or another of
3989 Org mode to function properly:
3991 - inputenc, fontenc: for basic font and character selection
3992 - fixltx2e: Important patches of LaTeX itself
3993 - graphicx: for including images
3994 - longtable: For multipage tables
3995 - float, wrapfig: for figure placement
3996 - rotating: for sideways figures and tables
3997 - ulem: for underline and strike-through
3998 - amsmath: for subscript and superscript and math environments
3999 - textcomp, marvosymb, wasysym, amssymb: for various symbols used
4000 for interpreting the entities in `org-entities'. You can skip
4001 some of these packages if you don't use any of their symbols.
4002 - hyperref: for cross references
4004 Therefore you should not modify this variable unless you know
4005 what you are doing. The one reason to change it anyway is that
4006 you might be loading some other package that conflicts with one
4007 of the default packages. Each element is either a cell or
4008 a string.
4010 A cell is of the format:
4012 \( \"options\" \"package\" SNIPPET-FLAG).
4014 If SNIPPET-FLAG is non-nil, the package also needs to be included
4015 when compiling LaTeX snippets into images for inclusion into
4016 non-LaTeX output.
4018 A string will be inserted as-is in the header of the document."
4019 :group 'org-latex
4020 :group 'org-export-latex
4021 :set 'org-set-packages-alist
4022 :get 'org-get-packages-alist
4023 :version "24.1"
4024 :type '(repeat
4025 (choice
4026 (list :tag "options/package pair"
4027 (string :tag "options")
4028 (string :tag "package")
4029 (boolean :tag "Snippet"))
4030 (string :tag "A line of LaTeX"))))
4032 (defcustom org-latex-packages-alist nil
4033 "Alist of packages to be inserted in every LaTeX header.
4035 These will be inserted after `org-latex-default-packages-alist'.
4036 Each element is either a cell or a string.
4038 A cell is of the format:
4040 \(\"options\" \"package\" SNIPPET-FLAG)
4042 SNIPPET-FLAG, when non-nil, indicates that this package is also
4043 needed when turning LaTeX snippets into images for inclusion into
4044 non-LaTeX output.
4046 A string will be inserted as-is in the header of the document.
4048 Make sure that you only list packages here which:
4050 - you want in every file;
4051 - do not conflict with the setup in `org-format-latex-header';
4052 - do not conflict with the default packages in
4053 `org-latex-default-packages-alist'."
4054 :group 'org-latex
4055 :group 'org-export-latex
4056 :set 'org-set-packages-alist
4057 :get 'org-get-packages-alist
4058 :type '(repeat
4059 (choice
4060 (list :tag "options/package pair"
4061 (string :tag "options")
4062 (string :tag "package")
4063 (boolean :tag "Snippet"))
4064 (string :tag "A line of LaTeX"))))
4066 (defgroup org-appearance nil
4067 "Settings for Org-mode appearance."
4068 :tag "Org Appearance"
4069 :group 'org)
4071 (defcustom org-level-color-stars-only nil
4072 "Non-nil means fontify only the stars in each headline.
4073 When nil, the entire headline is fontified.
4074 Changing it requires restart of `font-lock-mode' to become effective
4075 also in regions already fontified."
4076 :group 'org-appearance
4077 :type 'boolean)
4079 (defcustom org-hide-leading-stars nil
4080 "Non-nil means hide the first N-1 stars in a headline.
4081 This works by using the face `org-hide' for these stars. This
4082 face is white for a light background, and black for a dark
4083 background. You may have to customize the face `org-hide' to
4084 make this work.
4085 Changing it requires restart of `font-lock-mode' to become effective
4086 also in regions already fontified.
4087 You may also set this on a per-file basis by adding one of the following
4088 lines to the buffer:
4090 #+STARTUP: hidestars
4091 #+STARTUP: showstars"
4092 :group 'org-appearance
4093 :type 'boolean)
4095 (defcustom org-hidden-keywords nil
4096 "List of symbols corresponding to keywords to be hidden the org buffer.
4097 For example, a value '(title) for this list will make the document's title
4098 appear in the buffer without the initial #+TITLE: keyword."
4099 :group 'org-appearance
4100 :version "24.1"
4101 :type '(set (const :tag "#+AUTHOR" author)
4102 (const :tag "#+DATE" date)
4103 (const :tag "#+EMAIL" email)
4104 (const :tag "#+TITLE" title)))
4106 (defcustom org-custom-properties nil
4107 "List of properties (as strings) with a special meaning.
4108 The default use of these custom properties is to let the user
4109 hide them with `org-toggle-custom-properties-visibility'."
4110 :group 'org-properties
4111 :group 'org-appearance
4112 :version "24.3"
4113 :type '(repeat (string :tag "Property Name")))
4115 (defcustom org-fontify-done-headline nil
4116 "Non-nil means change the face of a headline if it is marked DONE.
4117 Normally, only the TODO/DONE keyword indicates the state of a headline.
4118 When this is non-nil, the headline after the keyword is set to the
4119 `org-headline-done' as an additional indication."
4120 :group 'org-appearance
4121 :type 'boolean)
4123 (defcustom org-fontify-emphasized-text t
4124 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4125 Changing this variable requires a restart of Emacs to take effect."
4126 :group 'org-appearance
4127 :type 'boolean)
4129 (defcustom org-fontify-whole-heading-line nil
4130 "Non-nil means fontify the whole line for headings.
4131 This is useful when setting a background color for the
4132 org-level-* faces."
4133 :group 'org-appearance
4134 :type 'boolean)
4136 (defcustom org-highlight-latex-and-related nil
4137 "Non-nil means highlight LaTeX related syntax in the buffer.
4138 When non nil, the value should be a list containing any of the
4139 following symbols:
4140 `latex' Highlight LaTeX snippets and environments.
4141 `script' Highlight subscript and superscript.
4142 `entities' Highlight entities."
4143 :group 'org-appearance
4144 :version "24.4"
4145 :package-version '(Org . "8.0")
4146 :type '(choice
4147 (const :tag "No highlighting" nil)
4148 (set :greedy t :tag "Highlight"
4149 (const :tag "LaTeX snippets and environments" latex)
4150 (const :tag "Subscript and superscript" script)
4151 (const :tag "Entities" entities))))
4153 (defcustom org-hide-emphasis-markers nil
4154 "Non-nil mean font-lock should hide the emphasis marker characters."
4155 :group 'org-appearance
4156 :type 'boolean)
4158 (defcustom org-hide-macro-markers nil
4159 "Non-nil mean font-lock should hide the brackets marking macro calls."
4160 :group 'org-appearance
4161 :type 'boolean)
4163 (defcustom org-pretty-entities nil
4164 "Non-nil means show entities as UTF8 characters.
4165 When nil, the \\name form remains in the buffer."
4166 :group 'org-appearance
4167 :version "24.1"
4168 :type 'boolean)
4170 (defcustom org-pretty-entities-include-sub-superscripts t
4171 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4172 :group 'org-appearance
4173 :version "24.1"
4174 :type 'boolean)
4176 (defvar org-emph-re nil
4177 "Regular expression for matching emphasis.
4178 After a match, the match groups contain these elements:
4179 0 The match of the full regular expression, including the characters
4180 before and after the proper match
4181 1 The character before the proper match, or empty at beginning of line
4182 2 The proper match, including the leading and trailing markers
4183 3 The leading marker like * or /, indicating the type of highlighting
4184 4 The text between the emphasis markers, not including the markers
4185 5 The character after the match, empty at the end of a line")
4186 (defvar org-verbatim-re nil
4187 "Regular expression for matching verbatim text.")
4188 (defvar org-emphasis-regexp-components) ; defined just below
4189 (defvar org-emphasis-alist) ; defined just below
4190 (defun org-set-emph-re (var val)
4191 "Set variable and compute the emphasis regular expression."
4192 (set var val)
4193 (when (and (boundp 'org-emphasis-alist)
4194 (boundp 'org-emphasis-regexp-components)
4195 org-emphasis-alist org-emphasis-regexp-components)
4196 (let* ((e org-emphasis-regexp-components)
4197 (pre (car e))
4198 (post (nth 1 e))
4199 (border (nth 2 e))
4200 (body (nth 3 e))
4201 (nl (nth 4 e))
4202 (body1 (concat body "*?"))
4203 (markers (mapconcat 'car org-emphasis-alist ""))
4204 (vmarkers (mapconcat
4205 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4206 org-emphasis-alist "")))
4207 ;; make sure special characters appear at the right position in the class
4208 (if (string-match "\\^" markers)
4209 (setq markers (concat (replace-match "" t t markers) "^")))
4210 (if (string-match "-" markers)
4211 (setq markers (concat (replace-match "" t t markers) "-")))
4212 (if (string-match "\\^" vmarkers)
4213 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4214 (if (string-match "-" vmarkers)
4215 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4216 (if (> nl 0)
4217 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4218 (int-to-string nl) "\\}")))
4219 ;; Make the regexp
4220 (setq org-emph-re
4221 (concat "\\([" pre "]\\|^\\)"
4222 "\\("
4223 "\\([" markers "]\\)"
4224 "\\("
4225 "[^" border "]\\|"
4226 "[^" border "]"
4227 body1
4228 "[^" border "]"
4229 "\\)"
4230 "\\3\\)"
4231 "\\([" post "]\\|$\\)"))
4232 (setq org-verbatim-re
4233 (concat "\\([" pre "]\\|^\\)"
4234 "\\("
4235 "\\([" vmarkers "]\\)"
4236 "\\("
4237 "[^" border "]\\|"
4238 "[^" border "]"
4239 body1
4240 "[^" border "]"
4241 "\\)"
4242 "\\3\\)"
4243 "\\([" post "]\\|$\\)")))))
4245 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4246 ;; set this option proved cumbersome. See this message/thread:
4247 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4248 (defvar org-emphasis-regexp-components
4249 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4250 "Components used to build the regular expression for emphasis.
4251 This is a list with five entries. Terminology: In an emphasis string
4252 like \" *strong word* \", we call the initial space PREMATCH, the final
4253 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4254 and \"trong wor\" is the body. The different components in this variable
4255 specify what is allowed/forbidden in each part:
4257 pre Chars allowed as prematch. Beginning of line will be allowed too.
4258 post Chars allowed as postmatch. End of line will be allowed too.
4259 border The chars *forbidden* as border characters.
4260 body-regexp A regexp like \".\" to match a body character. Don't use
4261 non-shy groups here, and don't allow newline here.
4262 newline The maximum number of newlines allowed in an emphasis exp.
4264 You need to reload Org or to restart Emacs after customizing this.")
4266 (defcustom org-emphasis-alist
4267 `(("*" bold)
4268 ("/" italic)
4269 ("_" underline)
4270 ("=" org-verbatim verbatim)
4271 ("~" org-code verbatim)
4272 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4273 "Alist of characters and faces to emphasize text.
4274 Text starting and ending with a special character will be emphasized,
4275 for example *bold*, _underlined_ and /italic/. This variable sets the
4276 marker characters and the face to be used by font-lock for highlighting
4277 in Org-mode Emacs buffers.
4279 You need to reload Org or to restart Emacs after customizing this."
4280 :group 'org-appearance
4281 :set 'org-set-emph-re
4282 :version "24.4"
4283 :package-version '(Org . "8.0")
4284 :type '(repeat
4285 (list
4286 (string :tag "Marker character")
4287 (choice
4288 (face :tag "Font-lock-face")
4289 (plist :tag "Face property list"))
4290 (option (const verbatim)))))
4292 (defvar org-protecting-blocks
4293 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4294 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4295 This is needed for font-lock setup.")
4297 ;;; Miscellaneous options
4299 (defgroup org-completion nil
4300 "Completion in Org-mode."
4301 :tag "Org Completion"
4302 :group 'org)
4304 (defcustom org-completion-use-ido nil
4305 "Non-nil means use ido completion wherever possible.
4306 Note that `ido-mode' must be active for this variable to be relevant.
4307 If you decide to turn this variable on, you might well want to turn off
4308 `org-outline-path-complete-in-steps'.
4309 See also `org-completion-use-iswitchb'."
4310 :group 'org-completion
4311 :type 'boolean)
4313 (defcustom org-completion-use-iswitchb nil
4314 "Non-nil means use iswitchb completion wherever possible.
4315 Note that `iswitchb-mode' must be active for this variable to be relevant.
4316 If you decide to turn this variable on, you might well want to turn off
4317 `org-outline-path-complete-in-steps'.
4318 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4319 :group 'org-completion
4320 :type 'boolean)
4322 (defcustom org-completion-fallback-command 'hippie-expand
4323 "The expansion command called by \\[pcomplete] in normal context.
4324 Normal means, no org-mode-specific context."
4325 :group 'org-completion
4326 :type 'function)
4328 ;;; Functions and variables from their packages
4329 ;; Declared here to avoid compiler warnings
4331 ;; XEmacs only
4332 (defvar outline-mode-menu-heading)
4333 (defvar outline-mode-menu-show)
4334 (defvar outline-mode-menu-hide)
4335 (defvar zmacs-regions) ; XEmacs regions
4337 ;; Emacs only
4338 (defvar mark-active)
4340 ;; Various packages
4341 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4342 (declare-function calendar-forward-day "cal-move" (arg))
4343 (declare-function calendar-goto-date "cal-move" (date))
4344 (declare-function calendar-goto-today "cal-move" ())
4345 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4346 (defvar calc-embedded-close-formula)
4347 (defvar calc-embedded-open-formula)
4348 (declare-function cdlatex-tab "ext:cdlatex" ())
4349 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4350 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4351 (defvar font-lock-unfontify-region-function)
4352 (declare-function iswitchb-read-buffer "iswitchb"
4353 (prompt &optional default require-match start matches-set))
4354 (defvar iswitchb-temp-buflist)
4355 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4356 (defvar org-agenda-tags-todo-honor-ignore-options)
4357 (declare-function org-agenda-skip "org-agenda" ())
4358 (declare-function
4359 org-agenda-format-item "org-agenda"
4360 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4361 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4362 (declare-function org-agenda-change-all-lines "org-agenda"
4363 (newhead hdmarker &optional fixface just-this))
4364 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4365 (declare-function org-agenda-maybe-redo "org-agenda" ())
4366 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4367 (beg end))
4368 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4369 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4370 "org-agenda" (&optional end))
4371 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4372 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4373 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4374 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4375 (declare-function org-indent-mode "org-indent" (&optional arg))
4376 (declare-function parse-time-string "parse-time" (string))
4377 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4378 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4379 (defvar remember-data-file)
4380 (defvar texmathp-why)
4381 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4382 (declare-function table--at-cell-p "table" (position &optional object at-column))
4384 ;;;###autoload
4385 (defun turn-on-orgtbl ()
4386 "Unconditionally turn on `orgtbl-mode'."
4387 (require 'org-table)
4388 (orgtbl-mode 1))
4390 (defun org-at-table-p (&optional table-type)
4391 "Return t if the cursor is inside an org-type table.
4392 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4393 (if org-enable-table-editor
4394 (save-excursion
4395 (beginning-of-line 1)
4396 (looking-at (if table-type org-table-any-line-regexp
4397 org-table-line-regexp)))
4398 nil))
4399 (defsubst org-table-p () (org-at-table-p))
4401 (defun org-at-table.el-p ()
4402 "Return t if and only if we are at a table.el table."
4403 (and (org-at-table-p 'any)
4404 (save-excursion
4405 (goto-char (org-table-begin 'any))
4406 (looking-at org-table1-hline-regexp))))
4408 (defun org-table-recognize-table.el ()
4409 "If there is a table.el table nearby, recognize it and move into it."
4410 (if org-table-tab-recognizes-table.el
4411 (if (org-at-table.el-p)
4412 (progn
4413 (beginning-of-line 1)
4414 (if (looking-at org-table-dataline-regexp)
4416 (if (looking-at org-table1-hline-regexp)
4417 (progn
4418 (beginning-of-line 2)
4419 (if (looking-at org-table-any-border-regexp)
4420 (beginning-of-line -1)))))
4421 (if (re-search-forward "|" (org-table-end t) t)
4422 (progn
4423 (require 'table)
4424 (if (table--at-cell-p (point))
4426 (message "recognizing table.el table...")
4427 (table-recognize-table)
4428 (message "recognizing table.el table...done")))
4429 (error "This should not happen"))
4431 nil)
4432 nil))
4434 (defun org-at-table-hline-p ()
4435 "Return t if the cursor is inside a hline in a table."
4436 (if org-enable-table-editor
4437 (save-excursion
4438 (beginning-of-line 1)
4439 (looking-at org-table-hline-regexp))
4440 nil))
4442 (defun org-table-map-tables (function &optional quietly)
4443 "Apply FUNCTION to the start of all tables in the buffer."
4444 (save-excursion
4445 (save-restriction
4446 (widen)
4447 (goto-char (point-min))
4448 (while (re-search-forward org-table-any-line-regexp nil t)
4449 (unless quietly
4450 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4451 (beginning-of-line 1)
4452 (when (and (looking-at org-table-line-regexp)
4453 ;; Exclude tables in src/example/verbatim/clocktable blocks
4454 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4455 (save-excursion (funcall function))
4456 (or (looking-at org-table-line-regexp)
4457 (forward-char 1)))
4458 (re-search-forward org-table-any-border-regexp nil 1))))
4459 (unless quietly (message "Mapping tables: done")))
4461 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4462 (declare-function org-clock-update-mode-line "org-clock" ())
4463 (declare-function org-resolve-clocks "org-clock"
4464 (&optional also-non-dangling-p prompt last-valid))
4466 (defun org-at-TBLFM-p (&optional pos)
4467 "Return t when point (or POS) is in #+TBLFM line."
4468 (save-excursion
4469 (let ((pos pos)))
4470 (goto-char (or pos (point)))
4471 (beginning-of-line 1)
4472 (looking-at org-TBLFM-regexp)))
4474 (defvar org-clock-start-time)
4475 (defvar org-clock-marker (make-marker)
4476 "Marker recording the last clock-in.")
4477 (defvar org-clock-hd-marker (make-marker)
4478 "Marker recording the last clock-in, but the headline position.")
4479 (defvar org-clock-heading ""
4480 "The heading of the current clock entry.")
4481 (defun org-clock-is-active ()
4482 "Return the buffer where the clock is currently running.
4483 Return nil if no clock is running."
4484 (marker-buffer org-clock-marker))
4486 (defun org-check-running-clock ()
4487 "Check if the current buffer contains the running clock.
4488 If yes, offer to stop it and to save the buffer with the changes."
4489 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4490 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4491 (buffer-name))))
4492 (org-clock-out)
4493 (when (y-or-n-p "Save changed buffer?")
4494 (save-buffer))))
4496 (defun org-clocktable-try-shift (dir n)
4497 "Check if this line starts a clock table, if yes, shift the time block."
4498 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4499 (org-clocktable-shift dir n)))
4501 ;;;###autoload
4502 (defun org-clock-persistence-insinuate ()
4503 "Set up hooks for clock persistence."
4504 (require 'org-clock)
4505 (add-hook 'org-mode-hook 'org-clock-load)
4506 (add-hook 'kill-emacs-hook 'org-clock-save))
4508 (defgroup org-archive nil
4509 "Options concerning archiving in Org-mode."
4510 :tag "Org Archive"
4511 :group 'org-structure)
4513 (defcustom org-archive-location "%s_archive::"
4514 "The location where subtrees should be archived.
4516 The value of this variable is a string, consisting of two parts,
4517 separated by a double-colon. The first part is a filename and
4518 the second part is a headline.
4520 When the filename is omitted, archiving happens in the same file.
4521 %s in the filename will be replaced by the current file
4522 name (without the directory part). Archiving to a different file
4523 is useful to keep archived entries from contributing to the
4524 Org-mode Agenda.
4526 The archived entries will be filed as subtrees of the specified
4527 headline. When the headline is omitted, the subtrees are simply
4528 filed away at the end of the file, as top-level entries. Also in
4529 the heading you can use %s to represent the file name, this can be
4530 useful when using the same archive for a number of different files.
4532 Here are a few examples:
4533 \"%s_archive::\"
4534 If the current file is Projects.org, archive in file
4535 Projects.org_archive, as top-level trees. This is the default.
4537 \"::* Archived Tasks\"
4538 Archive in the current file, under the top-level headline
4539 \"* Archived Tasks\".
4541 \"~/org/archive.org::\"
4542 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4544 \"~/org/archive.org::* From %s\"
4545 Archive in file ~/org/archive.org (absolute path), under headlines
4546 \"From FILENAME\" where file name is the current file name.
4548 \"~/org/datetree.org::datetree/* Finished Tasks\"
4549 The \"datetree/\" string is special, signifying to archive
4550 items to the datetree. Items are placed in either the CLOSED
4551 date of the item, or the current date if there is no CLOSED date.
4552 The heading will be a subentry to the current date. There doesn't
4553 need to be a heading, but there always needs to be a slash after
4554 datetree. For example, to store archived items directly in the
4555 datetree, use \"~/org/datetree.org::datetree/\".
4557 \"basement::** Finished Tasks\"
4558 Archive in file ./basement (relative path), as level 3 trees
4559 below the level 2 heading \"** Finished Tasks\".
4561 You may set this option on a per-file basis by adding to the buffer a
4562 line like
4564 #+ARCHIVE: basement::** Finished Tasks
4566 You may also define it locally for a subtree by setting an ARCHIVE property
4567 in the entry. If such a property is found in an entry, or anywhere up
4568 the hierarchy, it will be used."
4569 :group 'org-archive
4570 :type 'string)
4572 (defcustom org-agenda-skip-archived-trees t
4573 "Non-nil means the agenda will skip any items located in archived trees.
4574 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4575 variable is no longer recommended, you should leave it at the value t.
4576 Instead, use the key `v' to cycle the archives-mode in the agenda."
4577 :group 'org-archive
4578 :group 'org-agenda-skip
4579 :type 'boolean)
4581 (defcustom org-columns-skip-archived-trees t
4582 "Non-nil means ignore archived trees when creating column view."
4583 :group 'org-archive
4584 :group 'org-properties
4585 :type 'boolean)
4587 (defcustom org-cycle-open-archived-trees nil
4588 "Non-nil means `org-cycle' will open archived trees.
4589 An archived tree is a tree marked with the tag ARCHIVE.
4590 When nil, archived trees will stay folded. You can still open them with
4591 normal outline commands like `show-all', but not with the cycling commands."
4592 :group 'org-archive
4593 :group 'org-cycle
4594 :type 'boolean)
4596 (defcustom org-sparse-tree-open-archived-trees nil
4597 "Non-nil means sparse tree construction shows matches in archived trees.
4598 When nil, matches in these trees are highlighted, but the trees are kept in
4599 collapsed state."
4600 :group 'org-archive
4601 :group 'org-sparse-trees
4602 :type 'boolean)
4604 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4605 "The default date type when building a sparse tree.
4606 When this is nil, a date is a scheduled or a deadline timestamp.
4607 Otherwise, these types are allowed:
4609 all: all timestamps
4610 active: only active timestamps (<...>)
4611 inactive: only inactive timestamps (<...)
4612 scheduled: only scheduled timestamps
4613 deadline: only deadline timestamps"
4614 :type '(choice (const :tag "Scheduled or deadline" scheduled-or-deadline)
4615 (const :tag "All timestamps" all)
4616 (const :tag "Only active timestamps" active)
4617 (const :tag "Only inactive timestamps" inactive)
4618 (const :tag "Only scheduled timestamps" scheduled)
4619 (const :tag "Only deadline timestamps" deadline)
4620 (const :tag "Only closed timestamps" closed))
4621 :version "24.3"
4622 :group 'org-sparse-trees)
4624 (defun org-cycle-hide-archived-subtrees (state)
4625 "Re-hide all archived subtrees after a visibility state change."
4626 (when (and (not org-cycle-open-archived-trees)
4627 (not (memq state '(overview folded))))
4628 (save-excursion
4629 (let* ((globalp (memq state '(contents all)))
4630 (beg (if globalp (point-min) (point)))
4631 (end (if globalp (point-max) (org-end-of-subtree t))))
4632 (org-hide-archived-subtrees beg end)
4633 (goto-char beg)
4634 (if (looking-at (concat ".*:" org-archive-tag ":"))
4635 (message "%s" (substitute-command-keys
4636 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4638 (defun org-force-cycle-archived ()
4639 "Cycle subtree even if it is archived."
4640 (interactive)
4641 (setq this-command 'org-cycle)
4642 (let ((org-cycle-open-archived-trees t))
4643 (call-interactively 'org-cycle)))
4645 (defun org-hide-archived-subtrees (beg end)
4646 "Re-hide all archived subtrees after a visibility state change."
4647 (save-excursion
4648 (let* ((re (concat ":" org-archive-tag ":")))
4649 (goto-char beg)
4650 (while (re-search-forward re end t)
4651 (when (org-at-heading-p)
4652 (org-flag-subtree t)
4653 (org-end-of-subtree t))))))
4655 (declare-function outline-end-of-heading "outline" ())
4656 (declare-function outline-flag-region "outline" (from to flag))
4657 (defun org-flag-subtree (flag)
4658 (save-excursion
4659 (org-back-to-heading t)
4660 (outline-end-of-heading)
4661 (outline-flag-region (point)
4662 (progn (org-end-of-subtree t) (point))
4663 flag)))
4665 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4667 ;; Declare Column View Code
4669 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4670 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4671 (declare-function org-columns-compute "org-colview" (property))
4673 ;; Declare ID code
4675 (declare-function org-id-store-link "org-id")
4676 (declare-function org-id-locations-load "org-id")
4677 (declare-function org-id-locations-save "org-id")
4678 (defvar org-id-track-globally)
4680 ;;; Variables for pre-computed regular expressions, all buffer local
4682 (defvar org-todo-regexp nil
4683 "Matches any of the TODO state keywords.")
4684 (make-variable-buffer-local 'org-todo-regexp)
4685 (defvar org-not-done-regexp nil
4686 "Matches any of the TODO state keywords except the last one.")
4687 (make-variable-buffer-local 'org-not-done-regexp)
4688 (defvar org-not-done-heading-regexp nil
4689 "Matches a TODO headline that is not done.")
4690 (make-variable-buffer-local 'org-not-done-regexp)
4691 (defvar org-todo-line-regexp nil
4692 "Matches a headline and puts TODO state into group 2 if present.")
4693 (make-variable-buffer-local 'org-todo-line-regexp)
4694 (defvar org-complex-heading-regexp nil
4695 "Matches a headline and puts everything into groups:
4696 group 1: the stars
4697 group 2: The todo keyword, maybe
4698 group 3: Priority cookie
4699 group 4: True headline
4700 group 5: Tags")
4701 (make-variable-buffer-local 'org-complex-heading-regexp)
4702 (defvar org-complex-heading-regexp-format nil
4703 "Printf format to make regexp to match an exact headline.
4704 This regexp will match the headline of any node which has the
4705 exact headline text that is put into the format, but may have any
4706 TODO state, priority and tags.")
4707 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4708 (defvar org-todo-line-tags-regexp nil
4709 "Matches a headline and puts TODO state into group 2 if present.
4710 Also put tags into group 4 if tags are present.")
4711 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4712 (defvar org-ds-keyword-length 12
4713 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4714 (make-variable-buffer-local 'org-ds-keyword-length)
4715 (defvar org-deadline-regexp nil
4716 "Matches the DEADLINE keyword.")
4717 (make-variable-buffer-local 'org-deadline-regexp)
4718 (defvar org-deadline-time-regexp nil
4719 "Matches the DEADLINE keyword together with a time stamp.")
4720 (make-variable-buffer-local 'org-deadline-time-regexp)
4721 (defvar org-deadline-time-hour-regexp nil
4722 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4723 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4724 (defvar org-deadline-line-regexp nil
4725 "Matches the DEADLINE keyword and the rest of the line.")
4726 (make-variable-buffer-local 'org-deadline-line-regexp)
4727 (defvar org-scheduled-regexp nil
4728 "Matches the SCHEDULED keyword.")
4729 (make-variable-buffer-local 'org-scheduled-regexp)
4730 (defvar org-scheduled-time-regexp nil
4731 "Matches the SCHEDULED keyword together with a time stamp.")
4732 (make-variable-buffer-local 'org-scheduled-time-regexp)
4733 (defvar org-scheduled-time-hour-regexp nil
4734 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4735 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4736 (defvar org-closed-time-regexp nil
4737 "Matches the CLOSED keyword together with a time stamp.")
4738 (make-variable-buffer-local 'org-closed-time-regexp)
4740 (defvar org-keyword-time-regexp nil
4741 "Matches any of the 4 keywords, together with the time stamp.")
4742 (make-variable-buffer-local 'org-keyword-time-regexp)
4743 (defvar org-keyword-time-not-clock-regexp nil
4744 "Matches any of the 3 keywords, together with the time stamp.")
4745 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4746 (defvar org-maybe-keyword-time-regexp nil
4747 "Matches a timestamp, possibly preceded by a keyword.")
4748 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4749 (defvar org-all-time-keywords nil
4750 "List of time keywords.")
4751 (make-variable-buffer-local 'org-all-time-keywords)
4753 (defconst org-plain-time-of-day-regexp
4754 (concat
4755 "\\(\\<[012]?[0-9]"
4756 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4757 "\\(--?"
4758 "\\(\\<[012]?[0-9]"
4759 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4760 "\\)?")
4761 "Regular expression to match a plain time or time range.
4762 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4763 groups carry important information:
4764 0 the full match
4765 1 the first time, range or not
4766 8 the second time, if it is a range.")
4768 (defconst org-plain-time-extension-regexp
4769 (concat
4770 "\\(\\<[012]?[0-9]"
4771 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4772 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4773 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4774 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4775 groups carry important information:
4776 0 the full match
4777 7 hours of duration
4778 9 minutes of duration")
4780 (defconst org-stamp-time-of-day-regexp
4781 (concat
4782 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4783 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4784 "\\(--?"
4785 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4786 "Regular expression to match a timestamp time or time range.
4787 After a match, the following groups carry important information:
4788 0 the full match
4789 1 date plus weekday, for back referencing to make sure both times are on the same day
4790 2 the first time, range or not
4791 4 the second time, if it is a range.")
4793 (defconst org-startup-options
4794 '(("fold" org-startup-folded t)
4795 ("overview" org-startup-folded t)
4796 ("nofold" org-startup-folded nil)
4797 ("showall" org-startup-folded nil)
4798 ("showeverything" org-startup-folded showeverything)
4799 ("content" org-startup-folded content)
4800 ("indent" org-startup-indented t)
4801 ("noindent" org-startup-indented nil)
4802 ("hidestars" org-hide-leading-stars t)
4803 ("showstars" org-hide-leading-stars nil)
4804 ("odd" org-odd-levels-only t)
4805 ("oddeven" org-odd-levels-only nil)
4806 ("align" org-startup-align-all-tables t)
4807 ("noalign" org-startup-align-all-tables nil)
4808 ("inlineimages" org-startup-with-inline-images t)
4809 ("noinlineimages" org-startup-with-inline-images nil)
4810 ("latexpreview" org-startup-with-latex-preview t)
4811 ("nolatexpreview" org-startup-with-latex-preview nil)
4812 ("customtime" org-display-custom-times t)
4813 ("logdone" org-log-done time)
4814 ("lognotedone" org-log-done note)
4815 ("nologdone" org-log-done nil)
4816 ("lognoteclock-out" org-log-note-clock-out t)
4817 ("nolognoteclock-out" org-log-note-clock-out nil)
4818 ("logrepeat" org-log-repeat state)
4819 ("lognoterepeat" org-log-repeat note)
4820 ("logdrawer" org-log-into-drawer t)
4821 ("nologdrawer" org-log-into-drawer nil)
4822 ("logstatesreversed" org-log-states-order-reversed t)
4823 ("nologstatesreversed" org-log-states-order-reversed nil)
4824 ("nologrepeat" org-log-repeat nil)
4825 ("logreschedule" org-log-reschedule time)
4826 ("lognotereschedule" org-log-reschedule note)
4827 ("nologreschedule" org-log-reschedule nil)
4828 ("logredeadline" org-log-redeadline time)
4829 ("lognoteredeadline" org-log-redeadline note)
4830 ("nologredeadline" org-log-redeadline nil)
4831 ("logrefile" org-log-refile time)
4832 ("lognoterefile" org-log-refile note)
4833 ("nologrefile" org-log-refile nil)
4834 ("fninline" org-footnote-define-inline t)
4835 ("nofninline" org-footnote-define-inline nil)
4836 ("fnlocal" org-footnote-section nil)
4837 ("fnauto" org-footnote-auto-label t)
4838 ("fnprompt" org-footnote-auto-label nil)
4839 ("fnconfirm" org-footnote-auto-label confirm)
4840 ("fnplain" org-footnote-auto-label plain)
4841 ("fnadjust" org-footnote-auto-adjust t)
4842 ("nofnadjust" org-footnote-auto-adjust nil)
4843 ("constcgs" constants-unit-system cgs)
4844 ("constSI" constants-unit-system SI)
4845 ("noptag" org-tag-persistent-alist nil)
4846 ("hideblocks" org-hide-block-startup t)
4847 ("nohideblocks" org-hide-block-startup nil)
4848 ("beamer" org-startup-with-beamer-mode t)
4849 ("entitiespretty" org-pretty-entities t)
4850 ("entitiesplain" org-pretty-entities nil))
4851 "Variable associated with STARTUP options for org-mode.
4852 Each element is a list of three items: the startup options (as written
4853 in the #+STARTUP line), the corresponding variable, and the value to set
4854 this variable to if the option is found. An optional forth element PUSH
4855 means to push this value onto the list in the variable.")
4857 (defun org-update-property-plist (key val props)
4858 "Update PROPS with KEY and VAL."
4859 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4860 (key (if appending (substring key 0 (- (length key) 1)) key))
4861 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4862 (previous (cdr (assoc key props))))
4863 (if appending
4864 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4865 (cons (cons key val) remainder))))
4867 (defcustom org-group-tags t
4868 "When non-nil (the default), use group tags.
4869 This can be turned on/off through `org-toggle-tags-groups'."
4870 :group 'org-tags
4871 :group 'org-startup
4872 :type 'boolean)
4874 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4876 (defun org-toggle-tags-groups ()
4877 "Toggle support for group tags.
4878 Support for group tags is controlled by the option
4879 `org-group-tags', which is non-nil by default."
4880 (interactive)
4881 (setq org-group-tags (not org-group-tags))
4882 (cond ((and (derived-mode-p 'org-agenda-mode)
4883 org-group-tags)
4884 (org-agenda-redo))
4885 ((derived-mode-p 'org-mode)
4886 (let ((org-inhibit-startup t)) (org-mode))))
4887 (message "Groups tags support has been turned %s"
4888 (if org-group-tags "on" "off")))
4890 (defun org-set-regexps-and-options-for-tags ()
4891 "Precompute variables used for tags."
4892 (when (derived-mode-p 'org-mode)
4893 (org-set-local 'org-file-tags nil)
4894 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4895 (splitre "[ \t]+")
4896 (start 0)
4897 tags ftags key value)
4898 (save-excursion
4899 (save-restriction
4900 (widen)
4901 (goto-char (point-min))
4902 (while (re-search-forward re nil t)
4903 (setq key (upcase (org-match-string-no-properties 1))
4904 value (org-match-string-no-properties 2))
4905 (if (stringp value) (setq value (org-trim value)))
4906 (cond
4907 ((equal key "TAGS")
4908 (setq tags (append tags (if tags '("\\n") nil)
4909 (org-split-string value splitre))))
4910 ((equal key "FILETAGS")
4911 (when (string-match "\\S-" value)
4912 (setq ftags
4913 (append
4914 ftags
4915 (apply 'append
4916 (mapcar (lambda (x) (org-split-string x ":"))
4917 (org-split-string value)))))))))))
4918 ;; Process the file tags.
4919 (and ftags (org-set-local 'org-file-tags
4920 (mapcar 'org-add-prop-inherited ftags)))
4921 (org-set-local 'org-tag-groups-alist nil)
4922 ;; Process the tags.
4923 (when (and (not tags) org-tag-alist)
4924 (setq tags
4925 (mapcar
4926 (lambda (tg) (cond ((eq (car tg) :startgroup) "{")
4927 ((eq (car tg) :endgroup) "}")
4928 ((eq (car tg) :grouptags) ":")
4929 ((eq (car tg) :newline) "\n")
4930 (t (concat (car tg)
4931 (if (characterp (cdr tg))
4932 (format "(%s)" (char-to-string (cdr tg))) "")))))
4933 org-tag-alist)))
4934 (let (e tgs g)
4935 (while (setq e (pop tags))
4936 (cond
4937 ((equal e "{")
4938 (progn (push '(:startgroup) tgs)
4939 (when (equal (nth 1 tags) ":")
4940 (push (list (replace-regexp-in-string
4941 "(.+)$" "" (nth 0 tags)))
4942 org-tag-groups-alist)
4943 (setq g 0))))
4944 ((equal e ":") (push '(:grouptags) tgs))
4945 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4946 ((equal e "\\n") (push '(:newline) tgs))
4947 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4948 (push (cons (match-string 1 e)
4949 (string-to-char (match-string 2 e))) tgs)
4950 (if (and g (> g 0))
4951 (setcar org-tag-groups-alist
4952 (append (car org-tag-groups-alist)
4953 (list (match-string 1 e)))))
4954 (if g (setq g (1+ g))))
4955 (t (push (list e) tgs)
4956 (if (and g (> g 0))
4957 (setcar org-tag-groups-alist
4958 (append (car org-tag-groups-alist) (list e))))
4959 (if g (setq g (1+ g))))))
4960 (org-set-local 'org-tag-alist nil)
4961 (while (setq e (pop tgs))
4962 (or (and (stringp (car e))
4963 (assoc (car e) org-tag-alist))
4964 (push e org-tag-alist)))
4965 ;; Return a list with tag variables
4966 (list org-file-tags org-tag-alist org-tag-groups-alist)))))
4968 (defvar org-ota nil)
4969 (defun org-set-regexps-and-options ()
4970 "Precompute regular expressions used in the current buffer."
4971 (when (derived-mode-p 'org-mode)
4972 (org-set-local 'org-todo-kwd-alist nil)
4973 (org-set-local 'org-todo-key-alist nil)
4974 (org-set-local 'org-todo-key-trigger nil)
4975 (org-set-local 'org-todo-keywords-1 nil)
4976 (org-set-local 'org-done-keywords nil)
4977 (org-set-local 'org-todo-heads nil)
4978 (org-set-local 'org-todo-sets nil)
4979 (org-set-local 'org-todo-log-states nil)
4980 (org-set-local 'org-file-properties nil)
4981 (let ((re (org-make-options-regexp
4982 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
4983 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4984 "SETUPFILE" "OPTIONS")
4985 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4986 (splitre "[ \t]+")
4987 (scripts org-use-sub-superscripts)
4988 kwds kws0 kwsa key log value cat arch const links hw dws
4989 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
4990 (start 0))
4991 (save-excursion
4992 (save-restriction
4993 (widen)
4994 (goto-char (point-min))
4995 (while
4996 (or (and
4997 ext-setup-or-nil
4998 (not org-ota)
4999 (let (ret)
5000 (with-temp-buffer
5001 (insert ext-setup-or-nil)
5002 (let ((major-mode 'org-mode) org-ota)
5003 (setq ret (save-match-data
5004 (org-set-regexps-and-options-for-tags)))))
5005 ;; Append setupfile tags to existing tags
5006 (setq org-ota t)
5007 (setq org-file-tags
5008 (delq nil (append org-file-tags (nth 0 ret)))
5009 org-tag-alist
5010 (delq nil (append org-tag-alist (nth 1 ret)))
5011 org-tag-groups-alist
5012 (delq nil (append org-tag-groups-alist (nth 2 ret))))))
5013 (and ext-setup-or-nil
5014 (string-match re ext-setup-or-nil start)
5015 (setq start (match-end 0)))
5016 (and (setq ext-setup-or-nil nil start 0)
5017 (re-search-forward re nil t)))
5018 (setq key (upcase (match-string 1 ext-setup-or-nil))
5019 value (org-match-string-no-properties 2 ext-setup-or-nil))
5020 (if (stringp value) (setq value (org-trim value)))
5021 (cond
5022 ((equal key "CATEGORY")
5023 (setq cat value))
5024 ((member key '("SEQ_TODO" "TODO"))
5025 (push (cons 'sequence (org-split-string value splitre)) kwds))
5026 ((equal key "TYP_TODO")
5027 (push (cons 'type (org-split-string value splitre)) kwds))
5028 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
5029 ;; general TODO-like setup
5030 (push (cons (intern (downcase (match-string 1 key)))
5031 (org-split-string value splitre)) kwds))
5032 ((equal key "COLUMNS")
5033 (org-set-local 'org-columns-default-format value))
5034 ((equal key "LINK")
5035 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5036 (push (cons (match-string 1 value)
5037 (org-trim (match-string 2 value)))
5038 links)))
5039 ((equal key "PRIORITIES")
5040 (setq prio (org-split-string value " +")))
5041 ((equal key "PROPERTY")
5042 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
5043 (setq props (org-update-property-plist (match-string 1 value)
5044 (match-string 2 value)
5045 props))))
5046 ((equal key "CONSTANTS")
5047 (org-table-set-constants))
5048 ((equal key "STARTUP")
5049 (let ((opts (org-split-string value splitre))
5050 l var val)
5051 (while (setq l (pop opts))
5052 (when (setq l (assoc l org-startup-options))
5053 (setq var (nth 1 l) val (nth 2 l))
5054 (if (not (nth 3 l))
5055 (set (make-local-variable var) val)
5056 (if (not (listp (symbol-value var)))
5057 (set (make-local-variable var) nil))
5058 (set (make-local-variable var) (symbol-value var))
5059 (add-to-list var val))))))
5060 ((equal key "ARCHIVE")
5061 (setq arch value)
5062 (remove-text-properties 0 (length arch)
5063 '(face t fontified t) arch))
5064 ((equal key "OPTIONS")
5065 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
5066 (setq scripts (read (match-string 2 value)))))
5067 ((and (equal key "SETUPFILE")
5068 ;; Prevent checking in Gnus messages
5069 (not buffer-read-only))
5070 (setq setup-contents (org-file-contents
5071 (expand-file-name
5072 (org-remove-double-quotes value))
5073 'noerror))
5074 (if (not ext-setup-or-nil)
5075 (setq ext-setup-or-nil setup-contents start 0)
5076 (setq ext-setup-or-nil
5077 (concat (substring ext-setup-or-nil 0 start)
5078 "\n" setup-contents "\n"
5079 (substring ext-setup-or-nil start)))))))
5080 ;; search for property blocks
5081 (goto-char (point-min))
5082 (while (re-search-forward org-block-regexp nil t)
5083 (when (equal "PROPERTY" (upcase (match-string 1)))
5084 (setq value (replace-regexp-in-string
5085 "[\n\r]" " " (match-string 4)))
5086 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
5087 (setq props (org-update-property-plist (match-string 1 value)
5088 (match-string 2 value)
5089 props)))))))
5090 (org-set-local 'org-use-sub-superscripts scripts)
5091 (when cat
5092 (org-set-local 'org-category (intern cat))
5093 (push (cons "CATEGORY" cat) props))
5094 (when prio
5095 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
5096 (setq prio (mapcar 'string-to-char prio))
5097 (org-set-local 'org-highest-priority (nth 0 prio))
5098 (org-set-local 'org-lowest-priority (nth 1 prio))
5099 (org-set-local 'org-default-priority (nth 2 prio)))
5100 (and props (org-set-local 'org-file-properties (nreverse props)))
5101 (and arch (org-set-local 'org-archive-location arch))
5102 (and links (setq org-link-abbrev-alist-local (nreverse links)))
5103 ;; Process the TODO keywords
5104 (unless kwds
5105 ;; Use the global values as if they had been given locally.
5106 (setq kwds (default-value 'org-todo-keywords))
5107 (if (stringp (car kwds))
5108 (setq kwds (list (cons org-todo-interpretation
5109 (default-value 'org-todo-keywords)))))
5110 (setq kwds (reverse kwds)))
5111 (setq kwds (nreverse kwds))
5112 (let (inter kws kw)
5113 (while (setq kws (pop kwds))
5114 (let ((kws (or
5115 (run-hook-with-args-until-success
5116 'org-todo-setup-filter-hook kws)
5117 kws)))
5118 (setq inter (pop kws) sep (member "|" kws)
5119 kws0 (delete "|" (copy-sequence kws))
5120 kwsa nil
5121 kws1 (mapcar
5122 (lambda (x)
5123 ;; 1 2
5124 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
5125 (progn
5126 (setq kw (match-string 1 x)
5127 key (and (match-end 2) (match-string 2 x))
5128 log (org-extract-log-state-settings x))
5129 (push (cons kw (and key (string-to-char key))) kwsa)
5130 (and log (push log org-todo-log-states))
5132 (error "Invalid TODO keyword %s" x)))
5133 kws0)
5134 kwsa (if kwsa (append '((:startgroup))
5135 (nreverse kwsa)
5136 '((:endgroup))))
5137 hw (car kws1)
5138 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
5139 tail (list inter hw (car dws) (org-last dws))))
5140 (add-to-list 'org-todo-heads hw 'append)
5141 (push kws1 org-todo-sets)
5142 (setq org-done-keywords (append org-done-keywords dws nil))
5143 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
5144 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
5145 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
5146 (setq org-todo-sets (nreverse org-todo-sets)
5147 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5148 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
5149 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
5150 ;; Compute the regular expressions and other local variables.
5151 ;; Using `org-outline-regexp-bol' would complicate them much,
5152 ;; because of the fixed white space at the end of that string.
5153 (if (not org-done-keywords)
5154 (setq org-done-keywords (and org-todo-keywords-1
5155 (list (org-last org-todo-keywords-1)))))
5156 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5157 (length org-scheduled-string)
5158 (length org-clock-string)
5159 (length org-closed-string)))
5160 org-not-done-keywords
5161 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5162 org-todo-regexp
5163 (concat "\\("
5164 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5165 "\\)")
5166 org-not-done-regexp
5167 (concat "\\("
5168 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5169 "\\)")
5170 org-not-done-heading-regexp
5171 (format org-heading-keyword-regexp-format org-not-done-regexp)
5172 org-todo-line-regexp
5173 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5174 org-complex-heading-regexp
5175 (concat "^\\(\\*+\\)"
5176 "\\(?: +" org-todo-regexp "\\)?"
5177 "\\(?: +\\(\\[#.\\]\\)\\)?"
5178 "\\(?: +\\(.*?\\)\\)??"
5179 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5180 "[ \t]*$")
5181 org-complex-heading-regexp-format
5182 (concat "^\\(\\*+\\)"
5183 "\\(?: +" org-todo-regexp "\\)?"
5184 "\\(?: +\\(\\[#.\\]\\)\\)?"
5185 "\\(?: +"
5186 ;; Stats cookies can be stuck to body.
5187 "\\(?:\\[[0-9%%/]+\\] *\\)?"
5188 "\\(%s\\)"
5189 "\\(?: *\\[[0-9%%/]+\\]\\)?"
5190 "\\)"
5191 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5192 "[ \t]*$")
5193 org-todo-line-tags-regexp
5194 (concat "^\\(\\*+\\)"
5195 "\\(?: +" org-todo-regexp "\\)?"
5196 "\\(?: +\\(.*?\\)\\)??"
5197 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5198 "[ \t]*$")
5199 org-deadline-regexp (concat "\\<" org-deadline-string)
5200 org-deadline-time-regexp
5201 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5202 org-deadline-time-hour-regexp
5203 (concat "\\<" org-deadline-string
5204 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5205 org-deadline-line-regexp
5206 (concat "\\<\\(" org-deadline-string "\\).*")
5207 org-scheduled-regexp
5208 (concat "\\<" org-scheduled-string)
5209 org-scheduled-time-regexp
5210 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5211 org-scheduled-time-hour-regexp
5212 (concat "\\<" org-scheduled-string
5213 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5214 org-closed-time-regexp
5215 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5216 org-keyword-time-regexp
5217 (concat "\\<\\(" org-scheduled-string
5218 "\\|" org-deadline-string
5219 "\\|" org-closed-string
5220 "\\|" org-clock-string "\\)"
5221 " *[[<]\\([^]>]+\\)[]>]")
5222 org-keyword-time-not-clock-regexp
5223 (concat "\\<\\(" org-scheduled-string
5224 "\\|" org-deadline-string
5225 "\\|" org-closed-string
5226 "\\)"
5227 " *[[<]\\([^]>]+\\)[]>]")
5228 org-maybe-keyword-time-regexp
5229 (concat "\\(\\<\\(" org-scheduled-string
5230 "\\|" org-deadline-string
5231 "\\|" org-closed-string
5232 "\\|" org-clock-string "\\)\\)?"
5233 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5234 org-all-time-keywords
5235 (mapcar (lambda (w) (substring w 0 -1))
5236 (list org-scheduled-string org-deadline-string
5237 org-clock-string org-closed-string)))
5238 (setq org-ota nil)
5239 (org-compute-latex-and-related-regexp))))
5241 (defun org-file-contents (file &optional noerror)
5242 "Return the contents of FILE, as a string."
5243 (if (and file (file-readable-p file))
5244 (with-temp-buffer
5245 (insert-file-contents file)
5246 (buffer-string))
5247 (funcall (if noerror #'message #'error)
5248 "Cannot read file \"%s\"%s"
5249 file
5250 (let ((from (buffer-file-name (buffer-base-buffer))))
5251 (if from (concat " (referenced in file \"" from "\")") "")))))
5253 (defun org-extract-log-state-settings (x)
5254 "Extract the log state setting from a TODO keyword string.
5255 This will extract info from a string like \"WAIT(w@/!)\"."
5256 (let (kw key log1 log2)
5257 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5258 (setq kw (match-string 1 x)
5259 key (and (match-end 2) (match-string 2 x))
5260 log1 (and (match-end 3) (match-string 3 x))
5261 log2 (and (match-end 4) (match-string 4 x)))
5262 (and (or log1 log2)
5263 (list kw
5264 (and log1 (if (equal log1 "!") 'time 'note))
5265 (and log2 (if (equal log2 "!") 'time 'note)))))))
5267 (defun org-remove-keyword-keys (list)
5268 "Remove a pair of parenthesis at the end of each string in LIST."
5269 (mapcar (lambda (x)
5270 (if (string-match "(.*)$" x)
5271 (substring x 0 (match-beginning 0))
5273 list))
5275 (defun org-assign-fast-keys (alist)
5276 "Assign fast keys to a keyword-key alist.
5277 Respect keys that are already there."
5278 (let (new e (alt ?0))
5279 (while (setq e (pop alist))
5280 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5281 (cdr e)) ;; Key already assigned.
5282 (push e new)
5283 (let ((clist (string-to-list (downcase (car e))))
5284 (used (append new alist)))
5285 (when (= (car clist) ?@)
5286 (pop clist))
5287 (while (and clist (rassoc (car clist) used))
5288 (pop clist))
5289 (unless clist
5290 (while (rassoc alt used)
5291 (incf alt)))
5292 (push (cons (car e) (or (car clist) alt)) new))))
5293 (nreverse new)))
5295 ;;; Some variables used in various places
5297 (defvar org-window-configuration nil
5298 "Used in various places to store a window configuration.")
5299 (defvar org-selected-window nil
5300 "Used in various places to store a window configuration.")
5301 (defvar org-finish-function nil
5302 "Function to be called when `C-c C-c' is used.
5303 This is for getting out of special buffers like capture.")
5306 ;; FIXME: Occasionally check by commenting these, to make sure
5307 ;; no other functions uses these, forgetting to let-bind them.
5308 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5309 (defvar org-last-state)
5310 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5312 ;; Defined somewhere in this file, but used before definition.
5313 (defvar org-entities) ;; defined in org-entities.el
5314 (defvar org-struct-menu)
5315 (defvar org-org-menu)
5316 (defvar org-tbl-menu)
5318 ;;;; Define the Org-mode
5320 ;; We use a before-change function to check if a table might need
5321 ;; an update.
5322 (defvar org-table-may-need-update t
5323 "Indicates that a table might need an update.
5324 This variable is set by `org-before-change-function'.
5325 `org-table-align' sets it back to nil.")
5326 (defun org-before-change-function (beg end)
5327 "Every change indicates that a table might need an update."
5328 (setq org-table-may-need-update t))
5329 (defvar org-mode-map)
5330 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5331 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5332 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5333 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5334 (defvar org-table-buffer-is-an nil)
5336 (defvar bidi-paragraph-direction)
5337 (defvar buffer-face-mode-face)
5339 (require 'outline)
5340 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5341 (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"))
5342 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5344 ;; Other stuff we need.
5345 (require 'time-date)
5346 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5347 (require 'easymenu)
5348 (require 'overlay)
5350 ;; (require 'org-macs) moved higher up in the file before it is first used
5351 (require 'org-entities)
5352 ;; (require 'org-compat) moved higher up in the file before it is first used
5353 (require 'org-faces)
5354 (require 'org-list)
5355 (require 'org-pcomplete)
5356 (require 'org-src)
5357 (require 'org-footnote)
5358 (require 'org-macro)
5360 ;; babel
5361 (require 'ob)
5363 ;;;###autoload
5364 (define-derived-mode org-mode outline-mode "Org"
5365 "Outline-based notes management and organizer, alias
5366 \"Carsten's outline-mode for keeping track of everything.\"
5368 Org-mode develops organizational tasks around a NOTES file which
5369 contains information about projects as plain text. Org-mode is
5370 implemented on top of outline-mode, which is ideal to keep the content
5371 of large files well structured. It supports ToDo items, deadlines and
5372 time stamps, which magically appear in the diary listing of the Emacs
5373 calendar. Tables are easily created with a built-in table editor.
5374 Plain text URL-like links connect to websites, emails (VM), Usenet
5375 messages (Gnus), BBDB entries, and any files related to the project.
5376 For printing and sharing of notes, an Org-mode file (or a part of it)
5377 can be exported as a structured ASCII or HTML file.
5379 The following commands are available:
5381 \\{org-mode-map}"
5383 ;; Get rid of Outline menus, they are not needed
5384 ;; Need to do this here because define-derived-mode sets up
5385 ;; the keymap so late. Still, it is a waste to call this each time
5386 ;; we switch another buffer into org-mode.
5387 (if (featurep 'xemacs)
5388 (when (boundp 'outline-mode-menu-heading)
5389 ;; Assume this is Greg's port, it uses easymenu
5390 (easy-menu-remove outline-mode-menu-heading)
5391 (easy-menu-remove outline-mode-menu-show)
5392 (easy-menu-remove outline-mode-menu-hide))
5393 (define-key org-mode-map [menu-bar headings] 'undefined)
5394 (define-key org-mode-map [menu-bar hide] 'undefined)
5395 (define-key org-mode-map [menu-bar show] 'undefined))
5397 (org-load-modules-maybe)
5398 (easy-menu-add org-org-menu)
5399 (easy-menu-add org-tbl-menu)
5400 (org-install-agenda-files-menu)
5401 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5402 (add-to-invisibility-spec '(org-cwidth))
5403 (add-to-invisibility-spec '(org-hide-block . t))
5404 (when (featurep 'xemacs)
5405 (org-set-local 'line-move-ignore-invisible t))
5406 (org-set-local 'outline-regexp org-outline-regexp)
5407 (org-set-local 'outline-level 'org-outline-level)
5408 (setq bidi-paragraph-direction 'left-to-right)
5409 (when (and org-ellipsis
5410 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5411 (fboundp 'make-glyph-code))
5412 (unless org-display-table
5413 (setq org-display-table (make-display-table)))
5414 (set-display-table-slot
5415 org-display-table 4
5416 (vconcat (mapcar
5417 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5418 org-ellipsis)))
5419 (if (stringp org-ellipsis) org-ellipsis "..."))))
5420 (setq buffer-display-table org-display-table))
5421 (org-set-regexps-and-options-for-tags)
5422 (org-set-regexps-and-options)
5423 (org-set-font-lock-defaults)
5424 (when (and org-tag-faces (not org-tags-special-faces-re))
5425 ;; tag faces set outside customize.... force initialization.
5426 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5427 ;; Calc embedded
5428 (org-set-local 'calc-embedded-open-mode "# ")
5429 ;; Modify a few syntax entries
5430 (modify-syntax-entry ?@ "w")
5431 (modify-syntax-entry ?\" "\"")
5432 (modify-syntax-entry ?\\ "_")
5433 (modify-syntax-entry ?~ "_")
5434 (if org-startup-truncated (setq truncate-lines t))
5435 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5436 (org-set-local 'font-lock-unfontify-region-function
5437 'org-unfontify-region)
5438 ;; Activate before-change-function
5439 (org-set-local 'org-table-may-need-update t)
5440 (org-add-hook 'before-change-functions 'org-before-change-function nil
5441 'local)
5442 ;; Check for running clock before killing a buffer
5443 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5444 ;; Initialize macros templates.
5445 (org-macro-initialize-templates)
5446 ;; Initialize radio targets.
5447 (org-update-radio-target-regexp)
5448 ;; Indentation.
5449 (org-set-local 'indent-line-function 'org-indent-line)
5450 (org-set-local 'indent-region-function 'org-indent-region)
5451 ;; Filling and auto-filling.
5452 (org-setup-filling)
5453 ;; Comments.
5454 (org-setup-comments-handling)
5455 ;; Initialize cache.
5456 (org-element-cache-reset)
5457 ;; Beginning/end of defun
5458 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5459 (org-set-local 'end-of-defun-function 'org-forward-element)
5460 ;; Next error for sparse trees
5461 (org-set-local 'next-error-function 'org-occur-next-match)
5462 ;; Make sure dependence stuff works reliably, even for users who set it
5463 ;; too late :-(
5464 (if org-enforce-todo-dependencies
5465 (add-hook 'org-blocker-hook
5466 'org-block-todo-from-children-or-siblings-or-parent)
5467 (remove-hook 'org-blocker-hook
5468 'org-block-todo-from-children-or-siblings-or-parent))
5469 (if org-enforce-todo-checkbox-dependencies
5470 (add-hook 'org-blocker-hook
5471 'org-block-todo-from-checkboxes)
5472 (remove-hook 'org-blocker-hook
5473 'org-block-todo-from-checkboxes))
5475 ;; Align options lines
5476 (org-set-local
5477 'align-mode-rules-list
5478 '((org-in-buffer-settings
5479 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5480 (modes . '(org-mode)))))
5482 ;; Imenu
5483 (org-set-local 'imenu-create-index-function
5484 'org-imenu-get-tree)
5486 ;; Make isearch reveal context
5487 (if (or (featurep 'xemacs)
5488 (not (boundp 'outline-isearch-open-invisible-function)))
5489 ;; Emacs 21 and XEmacs make use of the hook
5490 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5491 ;; Emacs 22 deals with this through a special variable
5492 (org-set-local 'outline-isearch-open-invisible-function
5493 (lambda (&rest ignore) (org-show-context 'isearch)))
5494 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5496 ;; Setup the pcomplete hooks
5497 (set (make-local-variable 'pcomplete-command-completion-function)
5498 'org-pcomplete-initial)
5499 (set (make-local-variable 'pcomplete-command-name-function)
5500 'org-command-at-point)
5501 (set (make-local-variable 'pcomplete-default-completion-function)
5502 'ignore)
5503 (set (make-local-variable 'pcomplete-parse-arguments-function)
5504 'org-parse-arguments)
5505 (set (make-local-variable 'pcomplete-termination-string) "")
5506 (when (>= emacs-major-version 23)
5507 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5509 ;; If empty file that did not turn on org-mode automatically, make it to.
5510 (if (and org-insert-mode-line-in-empty-file
5511 (org-called-interactively-p 'any)
5512 (= (point-min) (point-max)))
5513 (insert "# -*- mode: org -*-\n\n"))
5514 (unless org-inhibit-startup
5515 (org-unmodified
5516 (and org-startup-with-beamer-mode (org-beamer-mode))
5517 (when org-startup-align-all-tables
5518 (org-table-map-tables 'org-table-align 'quietly))
5519 (when org-startup-with-inline-images
5520 (org-display-inline-images))
5521 (when org-startup-with-latex-preview
5522 (org-preview-latex-fragment))
5523 (unless org-inhibit-startup-visibility-stuff
5524 (org-set-startup-visibility))))
5525 ;; Try to set org-hide correctly
5526 (let ((foreground (org-find-invisible-foreground)))
5527 (if foreground
5528 (set-face-foreground 'org-hide foreground))))
5530 ;; Update `customize-package-emacs-version-alist'
5531 (add-to-list 'customize-package-emacs-version-alist
5532 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5533 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5534 ("8.2.6" . "24.4")))
5536 (defvar org-mode-transpose-word-syntax-table
5537 (let ((st (make-syntax-table)))
5538 (mapc (lambda(c) (modify-syntax-entry
5539 (string-to-char (car c)) "w p" st))
5540 org-emphasis-alist)
5541 st))
5543 (when (fboundp 'abbrev-table-put)
5544 (abbrev-table-put org-mode-abbrev-table
5545 :parents (list text-mode-abbrev-table)))
5547 (defsubst org-fix-ellipsis-at-bol ()
5548 (save-excursion (goto-char (window-start)) (recenter 0)))
5550 (defun org-find-invisible-foreground ()
5551 (let ((candidates (remove
5552 "unspecified-bg"
5553 (nconc
5554 (list (face-background 'default)
5555 (face-background 'org-default))
5556 (mapcar
5557 (lambda (alist)
5558 (when (boundp alist)
5559 (cdr (assoc 'background-color (symbol-value alist)))))
5560 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5561 (list (face-foreground 'org-hide))))))
5562 (car (remove nil candidates))))
5564 (defun org-current-time (&optional rounding-minutes past)
5565 "Current time, possibly rounded to ROUNDING-MINUTES.
5566 When ROUNDING-MINUTES is not an integer, fall back on the car of
5567 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5568 the rounding returns a past time."
5569 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5570 (car org-time-stamp-rounding-minutes)))
5571 (time (decode-time)) res)
5572 (if (< r 1)
5573 (current-time)
5574 (setq res
5575 (apply 'encode-time
5576 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5577 (nthcdr 2 time))))
5578 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5579 (seconds-to-time (- (org-float-time res) (* r 60)))
5580 res))))
5582 (defun org-today ()
5583 "Return today date, considering `org-extend-today-until'."
5584 (time-to-days
5585 (time-subtract (current-time)
5586 (list 0 (* 3600 org-extend-today-until) 0))))
5588 ;;;; Font-Lock stuff, including the activators
5590 (defvar org-mouse-map (make-sparse-keymap))
5591 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5592 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5593 (when org-mouse-1-follows-link
5594 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5595 (when org-tab-follows-link
5596 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5597 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5599 (require 'font-lock)
5601 (defconst org-non-link-chars "]\t\n\r<>")
5602 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "file+emacs"
5603 "file+sys" "news" "shell" "elisp" "doi" "message"
5604 "help"))
5605 (defvar org-link-types-re nil
5606 "Matches a link that has a url-like prefix like \"http:\"")
5607 (defvar org-link-re-with-space nil
5608 "Matches a link with spaces, optional angular brackets around it.")
5609 (defvar org-link-re-with-space2 nil
5610 "Matches a link with spaces, optional angular brackets around it.")
5611 (defvar org-link-re-with-space3 nil
5612 "Matches a link with spaces, only for internal part in bracket links.")
5613 (defvar org-angle-link-re nil
5614 "Matches link with angular brackets, spaces are allowed.")
5615 (defvar org-plain-link-re nil
5616 "Matches plain link, without spaces.")
5617 (defvar org-bracket-link-regexp nil
5618 "Matches a link in double brackets.")
5619 (defvar org-bracket-link-analytic-regexp nil
5620 "Regular expression used to analyze links.
5621 Here is what the match groups contain after a match:
5622 1: http:
5623 2: http
5624 3: path
5625 4: [desc]
5626 5: desc")
5627 (defvar org-bracket-link-analytic-regexp++ nil
5628 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5629 (defvar org-any-link-re nil
5630 "Regular expression matching any link.")
5632 (defconst org-match-sexp-depth 3
5633 "Number of stacked braces for sub/superscript matching.")
5635 (defun org-create-multibrace-regexp (left right n)
5636 "Create a regular expression which will match a balanced sexp.
5637 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5638 as single character strings.
5639 The regexp returned will match the entire expression including the
5640 delimiters. It will also define a single group which contains the
5641 match except for the outermost delimiters. The maximum depth of
5642 stacked delimiters is N. Escaping delimiters is not possible."
5643 (let* ((nothing (concat "[^" left right "]*?"))
5644 (or "\\|")
5645 (re nothing)
5646 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5647 (while (> n 1)
5648 (setq n (1- n)
5649 re (concat re or next)
5650 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5651 (concat left "\\(" re "\\)" right)))
5653 (defconst org-match-substring-regexp
5654 (concat
5655 "\\(\\S-\\)\\([_^]\\)\\("
5656 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5657 "\\|"
5658 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5659 "\\|"
5660 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5661 "The regular expression matching a sub- or superscript.")
5663 (defconst org-match-substring-with-braces-regexp
5664 (concat
5665 "\\(\\S-\\)\\([_^]\\)"
5666 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5667 "The regular expression matching a sub- or superscript, forcing braces.")
5669 (defun org-make-link-regexps ()
5670 "Update the link regular expressions.
5671 This should be called after the variable `org-link-types' has changed."
5672 (let ((types-re (regexp-opt org-link-types t)))
5673 (setq org-link-types-re
5674 (concat "\\`" types-re ":")
5675 org-link-re-with-space
5676 (concat "<?" types-re ":"
5677 "\\([^" org-non-link-chars " ]"
5678 "[^" org-non-link-chars "]*"
5679 "[^" org-non-link-chars " ]\\)>?")
5680 org-link-re-with-space2
5681 (concat "<?" types-re ":"
5682 "\\([^" org-non-link-chars " ]"
5683 "[^\t\n\r]*"
5684 "[^" org-non-link-chars " ]\\)>?")
5685 org-link-re-with-space3
5686 (concat "<?" types-re ":"
5687 "\\([^" org-non-link-chars " ]"
5688 "[^\t\n\r]*\\)")
5689 org-angle-link-re
5690 (concat "<" types-re ":"
5691 "\\([^" org-non-link-chars " ]"
5692 "[^" org-non-link-chars "]*"
5693 "\\)>")
5694 org-plain-link-re
5695 (concat
5696 "\\<" types-re ":"
5697 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5698 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5699 org-bracket-link-regexp
5700 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5701 org-bracket-link-analytic-regexp
5702 (concat
5703 "\\[\\["
5704 "\\(" types-re ":\\)?"
5705 "\\([^]]+\\)"
5706 "\\]"
5707 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5708 "\\]")
5709 org-bracket-link-analytic-regexp++
5710 (concat
5711 "\\[\\["
5712 "\\(" (regexp-opt (cons "coderef" org-link-types) t) ":\\)?"
5713 "\\([^]]+\\)"
5714 "\\]"
5715 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5716 "\\]")
5717 org-any-link-re
5718 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5719 org-angle-link-re "\\)\\|\\("
5720 org-plain-link-re "\\)"))))
5722 (org-make-link-regexps)
5724 (defvar org-emph-face nil)
5726 (defun org-do-emphasis-faces (limit)
5727 "Run through the buffer and add overlays to emphasized strings."
5728 (let (rtn a)
5729 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5730 (let* ((border (char-after (match-beginning 3)))
5731 (bre (regexp-quote (char-to-string border))))
5732 (if (and (not (= border (char-after (match-beginning 4))))
5733 (not (save-match-data
5734 (string-match (concat bre ".*" bre)
5735 (replace-regexp-in-string
5736 "\n" " "
5737 (substring (match-string 2) 1 -1))))))
5738 (progn
5739 (setq rtn t)
5740 (setq a (assoc (match-string 3) org-emphasis-alist))
5741 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5742 'face
5743 (nth 1 a))
5744 (and (nth 2 a)
5745 (org-remove-flyspell-overlays-in
5746 (match-beginning 0) (match-end 0)))
5747 (add-text-properties (match-beginning 2) (match-end 2)
5748 '(font-lock-multiline t org-emphasis t))
5749 (when org-hide-emphasis-markers
5750 (add-text-properties (match-end 4) (match-beginning 5)
5751 '(invisible org-link))
5752 (add-text-properties (match-beginning 3) (match-end 3)
5753 '(invisible org-link))))))
5754 (goto-char (1+ (match-beginning 0))))
5755 rtn))
5757 (defun org-emphasize (&optional char)
5758 "Insert or change an emphasis, i.e. a font like bold or italic.
5759 If there is an active region, change that region to a new emphasis.
5760 If there is no region, just insert the marker characters and position
5761 the cursor between them.
5762 CHAR should be the marker character. If it is a space, it means to
5763 remove the emphasis of the selected region.
5764 If CHAR is not given (for example in an interactive call) it will be
5765 prompted for."
5766 (interactive)
5767 (let ((erc org-emphasis-regexp-components)
5768 (prompt "")
5769 (string "") beg end move c s)
5770 (if (org-region-active-p)
5771 (setq beg (region-beginning) end (region-end)
5772 string (buffer-substring beg end))
5773 (setq move t))
5775 (unless char
5776 (message "Emphasis marker or tag: [%s]"
5777 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5778 (setq char (read-char-exclusive)))
5779 (if (equal char ?\ )
5780 (setq s "" move nil)
5781 (unless (assoc (char-to-string char) org-emphasis-alist)
5782 (user-error "No such emphasis marker: \"%c\"" char))
5783 (setq s (char-to-string char)))
5784 (while (and (> (length string) 1)
5785 (equal (substring string 0 1) (substring string -1))
5786 (assoc (substring string 0 1) org-emphasis-alist))
5787 (setq string (substring string 1 -1)))
5788 (setq string (concat s string s))
5789 (if beg (delete-region beg end))
5790 (unless (or (bolp)
5791 (string-match (concat "[" (nth 0 erc) "\n]")
5792 (char-to-string (char-before (point)))))
5793 (insert " "))
5794 (unless (or (eobp)
5795 (string-match (concat "[" (nth 1 erc) "\n]")
5796 (char-to-string (char-after (point)))))
5797 (insert " ") (backward-char 1))
5798 (insert string)
5799 (and move (backward-char 1))))
5801 (defconst org-nonsticky-props
5802 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5804 (defsubst org-rear-nonsticky-at (pos)
5805 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5807 (defun org-activate-plain-links (limit)
5808 "Run through the buffer and add overlays to links."
5809 (let (f hl)
5810 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5811 (not (org-in-src-block-p)))
5812 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5813 (setq f (get-text-property (match-beginning 0) 'face))
5814 (setq hl (org-match-string-no-properties 0))
5815 (if (or (eq f 'org-tag)
5816 (and (listp f) (memq 'org-tag f)))
5818 (add-text-properties (match-beginning 0) (match-end 0)
5819 (list 'mouse-face 'highlight
5820 'face 'org-link
5821 'htmlize-link `(:uri ,hl)
5822 'keymap org-mouse-map))
5823 (org-rear-nonsticky-at (match-end 0)))
5824 t)))
5826 (defun org-activate-code (limit)
5827 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5828 (progn
5829 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5830 (remove-text-properties (match-beginning 0) (match-end 0)
5831 '(display t invisible t intangible t))
5832 t)))
5834 (defcustom org-src-fontify-natively t
5835 "When non-nil, fontify code in code blocks."
5836 :type 'boolean
5837 :version "24.4"
5838 :package-version '(Org . "8.3")
5839 :group 'org-appearance
5840 :group 'org-babel)
5842 (defcustom org-allow-promoting-top-level-subtree nil
5843 "When non-nil, allow promoting a top level subtree.
5844 The leading star of the top level headline will be replaced
5845 by a #."
5846 :type 'boolean
5847 :version "24.1"
5848 :group 'org-appearance)
5850 (defun org-fontify-meta-lines-and-blocks (limit)
5851 (condition-case nil
5852 (org-fontify-meta-lines-and-blocks-1 limit)
5853 (error (message "org-mode fontification error"))))
5855 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5856 "Fontify #+ lines and blocks."
5857 (let ((case-fold-search t))
5858 (if (re-search-forward
5859 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5860 limit t)
5861 (let ((beg (match-beginning 0))
5862 (block-start (match-end 0))
5863 (block-end nil)
5864 (lang (match-string 7))
5865 (beg1 (line-beginning-position 2))
5866 (dc1 (downcase (match-string 2)))
5867 (dc3 (downcase (match-string 3)))
5868 end end1 quoting block-type ovl)
5869 (cond
5870 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5871 ;; a single line of backend-specific content
5872 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5873 (remove-text-properties (match-beginning 0) (match-end 0)
5874 '(display t invisible t intangible t))
5875 (add-text-properties (match-beginning 1) (match-end 3)
5876 '(font-lock-fontified t face org-meta-line))
5877 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5878 '(font-lock-fontified t face org-block))
5879 ; for backend-specific code
5881 ((and (match-end 4) (equal dc3 "+begin"))
5882 ;; Truly a block
5883 (setq block-type (downcase (match-string 5))
5884 quoting (member block-type org-protecting-blocks))
5885 (when (re-search-forward
5886 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5887 nil t) ;; on purpose, we look further than LIMIT
5888 (setq end (min (point-max) (match-end 0))
5889 end1 (min (point-max) (1- (match-beginning 0))))
5890 (setq block-end (match-beginning 0))
5891 (when quoting
5892 (org-remove-flyspell-overlays-in beg1 end1)
5893 (remove-text-properties beg end
5894 '(display t invisible t intangible t)))
5895 (add-text-properties
5896 beg end '(font-lock-fontified t font-lock-multiline t))
5897 (add-text-properties beg beg1 '(face org-meta-line))
5898 (org-remove-flyspell-overlays-in beg beg1)
5899 (add-text-properties ; For end_src
5900 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5901 (org-remove-flyspell-overlays-in end1 end)
5902 (cond
5903 ((and lang (not (string= lang "")) org-src-fontify-natively)
5904 (org-src-font-lock-fontify-block lang block-start block-end)
5905 ;; remove old background overlays
5906 (mapc (lambda (ov)
5907 (if (eq (overlay-get ov 'face) 'org-block-background)
5908 (delete-overlay ov)))
5909 (overlays-at (/ (+ beg1 block-end) 2)))
5910 ;; add a background overlay
5911 (setq ovl (make-overlay beg1 block-end))
5912 (overlay-put ovl 'face 'org-block-background)
5913 (overlay-put ovl 'evaporate t)) ; make it go away when empty
5914 (quoting
5915 (add-text-properties beg1 (min (point-max) (1+ end1))
5916 '(face org-block))) ; end of source block
5917 ((not org-fontify-quote-and-verse-blocks))
5918 ((string= block-type "quote")
5919 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5920 ((string= block-type "verse")
5921 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5922 (add-text-properties beg beg1 '(face org-block-begin-line))
5923 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5924 '(face org-block-end-line))
5926 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5927 (org-remove-flyspell-overlays-in
5928 (match-beginning 0)
5929 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5930 (add-text-properties
5931 beg (match-end 3)
5932 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5933 '(font-lock-fontified t invisible t)
5934 '(font-lock-fontified t face org-document-info-keyword)))
5935 (add-text-properties
5936 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5937 (if (string-equal dc1 "+title:")
5938 '(font-lock-fontified t face org-document-title)
5939 '(font-lock-fontified t face org-document-info))))
5940 ((or (equal dc1 "+results")
5941 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5942 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5943 "+call:" "+header:" "+headers:" "+name:"))
5944 (and (match-end 4) (equal dc3 "+attr")))
5945 (org-remove-flyspell-overlays-in
5946 (match-beginning 0)
5947 (if (equal "+caption:" dc1) (match-end 2) (match-end 0)))
5948 (add-text-properties
5949 beg (match-end 0)
5950 '(font-lock-fontified t face org-meta-line))
5952 ((member dc3 '(" " ""))
5953 (org-remove-flyspell-overlays-in beg (match-end 0))
5954 (add-text-properties
5955 beg (match-end 0)
5956 '(font-lock-fontified t face font-lock-comment-face)))
5957 (t ;; just any other in-buffer setting, but not indented
5958 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5959 (add-text-properties
5960 beg (match-end 0)
5961 '(font-lock-fontified t face org-meta-line))
5962 t))))))
5964 (defun org-fontify-drawers (limit)
5965 "Fontify drawers."
5966 (when (re-search-forward org-drawer-regexp limit t)
5967 (add-text-properties
5968 (match-beginning 0) (match-end 0)
5969 '(font-lock-fontified t face org-special-keyword))
5970 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5973 (defun org-fontify-macros (limit)
5974 "Fontify macros."
5975 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
5976 (add-text-properties
5977 (match-beginning 0) (match-end 0)
5978 '(font-lock-fontified t face org-macro))
5979 (when org-hide-macro-markers
5980 (add-text-properties (match-end 2) (match-beginning 2)
5981 '(invisible t))
5982 (add-text-properties (match-beginning 1) (match-end 1)
5983 '(invisible t)))
5984 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5987 (defun org-activate-angle-links (limit)
5988 "Run through the buffer and add overlays to links."
5989 (if (and (re-search-forward org-angle-link-re limit t)
5990 (not (org-in-src-block-p)))
5991 (progn
5992 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5993 (add-text-properties (match-beginning 0) (match-end 0)
5994 (list 'mouse-face 'highlight
5995 'keymap org-mouse-map))
5996 (org-rear-nonsticky-at (match-end 0))
5997 t)))
5999 (defun org-activate-footnote-links (limit)
6000 "Run through the buffer and add overlays to footnotes."
6001 (let ((fn (org-footnote-next-reference-or-definition limit)))
6002 (when fn
6003 (let* ((beg (nth 1 fn))
6004 (end (nth 2 fn))
6005 (label (car fn))
6006 (referencep (/= (line-beginning-position) beg)))
6007 (when (and referencep (nth 3 fn))
6008 (save-excursion
6009 (goto-char beg)
6010 (search-forward (or label "fn:"))
6011 (org-remove-flyspell-overlays-in beg (match-end 0))))
6012 (add-text-properties beg end
6013 (list 'mouse-face 'highlight
6014 'keymap org-mouse-map
6015 'help-echo
6016 (if referencep "Footnote reference"
6017 "Footnote definition")
6018 'font-lock-fontified t
6019 'font-lock-multiline t
6020 'face 'org-footnote))))))
6022 (defun org-activate-bracket-links (limit)
6023 "Run through the buffer and add overlays to bracketed links."
6024 (if (and (re-search-forward org-bracket-link-regexp limit t)
6025 (not (org-in-src-block-p)))
6026 (let* ((hl (org-match-string-no-properties 1))
6027 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
6028 (ip (org-maybe-intangible
6029 (list 'invisible 'org-link
6030 'keymap org-mouse-map 'mouse-face 'highlight
6031 'font-lock-multiline t 'help-echo help
6032 'htmlize-link `(:uri ,hl))))
6033 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
6034 'font-lock-multiline t 'help-echo help
6035 'htmlize-link `(:uri ,hl))))
6036 ;; We need to remove the invisible property here. Table narrowing
6037 ;; may have made some of this invisible.
6038 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6039 (remove-text-properties (match-beginning 0) (match-end 0)
6040 '(invisible nil))
6041 (if (match-end 3)
6042 (progn
6043 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
6044 (org-rear-nonsticky-at (match-beginning 3))
6045 (add-text-properties (match-beginning 3) (match-end 3) vp)
6046 (org-rear-nonsticky-at (match-end 3))
6047 (add-text-properties (match-end 3) (match-end 0) ip)
6048 (org-rear-nonsticky-at (match-end 0)))
6049 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
6050 (org-rear-nonsticky-at (match-beginning 1))
6051 (add-text-properties (match-beginning 1) (match-end 1) vp)
6052 (org-rear-nonsticky-at (match-end 1))
6053 (add-text-properties (match-end 1) (match-end 0) ip)
6054 (org-rear-nonsticky-at (match-end 0)))
6055 t)))
6057 (defun org-activate-dates (limit)
6058 "Run through the buffer and add overlays to dates."
6059 (if (and (re-search-forward org-tsr-regexp-both limit t)
6060 (not (equal (char-before (match-beginning 0)) 91)))
6061 (progn
6062 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6063 (add-text-properties (match-beginning 0) (match-end 0)
6064 (list 'mouse-face 'highlight
6065 'keymap org-mouse-map))
6066 (org-rear-nonsticky-at (match-end 0))
6067 (when org-display-custom-times
6068 (if (match-end 3)
6069 (org-display-custom-time (match-beginning 3) (match-end 3)))
6070 (org-display-custom-time (match-beginning 1) (match-end 1)))
6071 t)))
6073 (defvar org-target-link-regexp nil
6074 "Regular expression matching radio targets in plain text.")
6075 (make-variable-buffer-local 'org-target-link-regexp)
6077 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6078 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6079 border border border))
6080 "Regular expression matching a link target.")
6082 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6083 "Regular expression matching a radio target.")
6085 (defconst org-any-target-regexp
6086 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6087 "Regular expression matching any target.")
6089 (defun org-activate-target-links (limit)
6090 "Run through the buffer and add overlays to target matches."
6091 (when org-target-link-regexp
6092 (let ((case-fold-search t))
6093 (if (re-search-forward org-target-link-regexp limit t)
6094 (progn
6095 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6096 (add-text-properties (match-beginning 1) (match-end 1)
6097 (list 'mouse-face 'highlight
6098 'keymap org-mouse-map
6099 'help-echo "Radio target link"
6100 'org-linked-text t))
6101 (org-rear-nonsticky-at (match-end 1))
6102 t)))))
6104 (defun org-update-radio-target-regexp ()
6105 "Find all radio targets in this file and update the regular expression."
6106 (interactive)
6107 (when (memq 'radio org-activate-links)
6108 (setq org-target-link-regexp
6109 (org-make-target-link-regexp (org-all-targets 'radio)))
6110 (org-restart-font-lock)))
6112 (defun org-hide-wide-columns (limit)
6113 (let (s e)
6114 (setq s (text-property-any (point) (or limit (point-max))
6115 'org-cwidth t))
6116 (when s
6117 (setq e (next-single-property-change s 'org-cwidth))
6118 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6119 (goto-char e)
6120 t)))
6122 (defvar org-latex-and-related-regexp nil
6123 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6125 (defun org-compute-latex-and-related-regexp ()
6126 "Compute regular expression for LaTeX, entities and sub/superscript.
6127 Result depends on variable `org-highlight-latex-and-related'."
6128 (org-set-local
6129 'org-latex-and-related-regexp
6130 (let* ((re-sub
6131 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6132 ((eq org-use-sub-superscripts '{})
6133 (list org-match-substring-with-braces-regexp))
6134 (org-use-sub-superscripts (list org-match-substring-regexp))))
6135 (re-latex
6136 (when (memq 'latex org-highlight-latex-and-related)
6137 (let ((matchers (plist-get org-format-latex-options :matchers)))
6138 (delq nil
6139 (mapcar (lambda (x)
6140 (and (member (car x) matchers) (nth 1 x)))
6141 org-latex-regexps)))))
6142 (re-entities
6143 (when (memq 'entities org-highlight-latex-and-related)
6144 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6145 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6147 (defun org-do-latex-and-related (limit)
6148 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6149 LIMIT bounds the search for syntax to highlight. Stop at first
6150 highlighted object, if any. Return t if some highlighting was
6151 done, nil otherwise."
6152 (when (org-string-nw-p org-latex-and-related-regexp)
6153 (catch 'found
6154 (while (re-search-forward org-latex-and-related-regexp limit t)
6155 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6156 'face))
6157 '(org-code org-verbatim underline))
6158 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6159 '(?_ ?^))
6161 0)))
6162 (font-lock-prepend-text-property
6163 (+ offset (match-beginning 0)) (match-end 0)
6164 'face 'org-latex-and-related)
6165 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6166 '(font-lock-multiline t)))
6167 (throw 'found t)))
6168 nil)))
6170 (defun org-restart-font-lock ()
6171 "Restart `font-lock-mode', to force refontification."
6172 (when (and (boundp 'font-lock-mode) font-lock-mode)
6173 (font-lock-mode -1)
6174 (font-lock-mode 1)))
6176 (defun org-all-targets (&optional radio)
6177 "Return a list of all targets in this file.
6178 When optional argument RADIO is non-nil, only find radio
6179 targets."
6180 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
6181 (save-excursion
6182 (goto-char (point-min))
6183 (while (re-search-forward re nil t)
6184 ;; Make sure point is really within the object.
6185 (backward-char)
6186 (let ((obj (org-element-context)))
6187 (when (memq (org-element-type obj) '(radio-target target))
6188 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
6189 rtn)))
6191 (defun org-make-target-link-regexp (targets)
6192 "Make regular expression matching all strings in TARGETS.
6193 The regular expression finds the targets also if there is a line break
6194 between words."
6195 (and targets
6196 (concat "\\(?:^\\|[^[:alnum:]]\\)\\("
6197 (mapconcat
6198 (lambda (x)
6199 (replace-regexp-in-string " +" "\\s-+" (regexp-quote x) t t))
6200 targets
6201 "\\|")
6202 "\\)\\(?:$\\|[^[:alnum:]]\\)")))
6204 (defun org-activate-tags (limit)
6205 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6206 (progn
6207 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6208 (add-text-properties (match-beginning 1) (match-end 1)
6209 (list 'mouse-face 'highlight
6210 'keymap org-mouse-map))
6211 (org-rear-nonsticky-at (match-end 1))
6212 t)))
6214 (defun org-outline-level ()
6215 "Compute the outline level of the heading at point.
6216 If this is called at a normal headline, the level is the number of stars.
6217 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6218 (save-excursion
6219 (if (not (condition-case nil
6220 (org-back-to-heading t)
6221 (error nil)))
6223 (looking-at org-outline-regexp)
6224 (1- (- (match-end 0) (match-beginning 0))))))
6226 (defvar org-font-lock-keywords nil)
6228 (defsubst org-re-property (property &optional literal)
6229 "Return a regexp matching a PROPERTY line.
6230 Match group 3 will be set to the value if it exists."
6231 (concat "^\\(?4:[ \t]*\\)\\(?1::\\(?2:"
6232 (if literal property (regexp-quote property))
6233 "\\):\\)[ \t]+\\(?3:[^ \t\r\n].*?\\)\\(?5:[ \t]*\\)$"))
6235 (defconst org-property-re
6236 (org-re-property ".*?" 'literal)
6237 "Regular expression matching a property line.
6238 There are four matching groups:
6239 1: :PROPKEY: including the leading and trailing colon,
6240 2: PROPKEY without the leading and trailing colon,
6241 3: PROPVAL without leading or trailing spaces,
6242 4: the indentation of the current line,
6243 5: trailing whitespace.")
6245 (defvar org-font-lock-hook nil
6246 "Functions to be called for special font lock stuff.")
6248 (defvar org-font-lock-set-keywords-hook nil
6249 "Functions that can manipulate `org-font-lock-extra-keywords'.
6250 This is called after `org-font-lock-extra-keywords' is defined, but before
6251 it is installed to be used by font lock. This can be useful if something
6252 needs to be inserted at a specific position in the font-lock sequence.")
6254 (defun org-font-lock-hook (limit)
6255 "Run `org-font-lock-hook' within LIMIT."
6256 (run-hook-with-args 'org-font-lock-hook limit))
6258 (defun org-set-font-lock-defaults ()
6259 "Set font lock defaults for the current buffer."
6260 (let* ((em org-fontify-emphasized-text)
6261 (lk org-activate-links)
6262 (org-font-lock-extra-keywords
6263 (list
6264 ;; Call the hook
6265 '(org-font-lock-hook)
6266 ;; Headlines
6267 `(,(if org-fontify-whole-heading-line
6268 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6269 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6270 (1 (org-get-level-face 1))
6271 (2 (org-get-level-face 2))
6272 (3 (org-get-level-face 3)))
6273 ;; Table lines
6274 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6275 (1 'org-table t))
6276 ;; Table internals
6277 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6278 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6279 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6280 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6281 ;; Drawers
6282 '(org-fontify-drawers)
6283 ;; Properties
6284 (list org-property-re
6285 '(1 'org-special-keyword t)
6286 '(3 'org-property-value t))
6287 ;; Links
6288 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6289 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6290 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6291 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6292 (if (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6293 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6294 (if (memq 'footnote lk) '(org-activate-footnote-links))
6295 ;; Targets.
6296 (list org-any-target-regexp '(0 'org-target t))
6297 ;; Diary sexps.
6298 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6299 ;; Macro
6300 '(org-fontify-macros)
6301 '(org-hide-wide-columns (0 nil append))
6302 ;; TODO keyword
6303 (list (format org-heading-keyword-regexp-format
6304 org-todo-regexp)
6305 '(2 (org-get-todo-face 2) t))
6306 ;; DONE
6307 (if org-fontify-done-headline
6308 (list (format org-heading-keyword-regexp-format
6309 (concat
6310 "\\(?:"
6311 (mapconcat 'regexp-quote org-done-keywords "\\|")
6312 "\\)"))
6313 '(2 'org-headline-done t))
6314 nil)
6315 ;; Priorities
6316 '(org-font-lock-add-priority-faces)
6317 ;; Tags
6318 '(org-font-lock-add-tag-faces)
6319 ;; Tags groups
6320 (if (and org-group-tags org-tag-groups-alist)
6321 (list (concat org-outline-regexp-bol ".+\\(:"
6322 (regexp-opt (mapcar 'car org-tag-groups-alist))
6323 ":\\).*$")
6324 '(1 'org-tag-group prepend)))
6325 ;; Special keywords
6326 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6327 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6328 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6329 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6330 ;; Emphasis
6331 (if em
6332 (if (featurep 'xemacs)
6333 '(org-do-emphasis-faces (0 nil append))
6334 '(org-do-emphasis-faces)))
6335 ;; Checkboxes
6336 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6337 1 'org-checkbox prepend)
6338 (if (cdr (assq 'checkbox org-list-automatic-rules))
6339 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6340 (0 (org-get-checkbox-statistics-face) t)))
6341 ;; Description list items
6342 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6343 1 'org-list-dt prepend)
6344 ;; ARCHIVEd headings
6345 (list (concat
6346 org-outline-regexp-bol
6347 "\\(.*:" org-archive-tag ":.*\\)")
6348 '(1 'org-archived prepend))
6349 ;; Specials
6350 '(org-do-latex-and-related)
6351 '(org-fontify-entities)
6352 '(org-raise-scripts)
6353 ;; Code
6354 '(org-activate-code (1 'org-code t))
6355 ;; COMMENT
6356 (list (format
6357 "^\\*\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6358 org-todo-regexp
6359 org-comment-string)
6360 '(9 'org-special-keyword t))
6361 ;; Blocks and meta lines
6362 '(org-fontify-meta-lines-and-blocks))))
6363 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6364 (run-hooks 'org-font-lock-set-keywords-hook)
6365 ;; Now set the full font-lock-keywords
6366 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6367 (org-set-local 'font-lock-defaults
6368 '(org-font-lock-keywords t nil nil backward-paragraph))
6369 (kill-local-variable 'font-lock-keywords) nil))
6371 (defun org-toggle-pretty-entities ()
6372 "Toggle the composition display of entities as UTF8 characters."
6373 (interactive)
6374 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6375 (org-restart-font-lock)
6376 (if org-pretty-entities
6377 (message "Entities are now displayed as UTF8 characters")
6378 (save-restriction
6379 (widen)
6380 (org-decompose-region (point-min) (point-max))
6381 (message "Entities are now displayed as plain text"))))
6383 (defvar org-custom-properties-overlays nil
6384 "List of overlays used for custom properties.")
6385 (make-variable-buffer-local 'org-custom-properties-overlays)
6387 (defun org-toggle-custom-properties-visibility ()
6388 "Display or hide properties in `org-custom-properties'."
6389 (interactive)
6390 (if org-custom-properties-overlays
6391 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6392 (setq org-custom-properties-overlays nil))
6393 (unless (not org-custom-properties)
6394 (save-excursion
6395 (save-restriction
6396 (widen)
6397 (goto-char (point-min))
6398 (while (re-search-forward org-property-re nil t)
6399 (mapc (lambda(p)
6400 (when (equal p (substring (match-string 1) 1 -1))
6401 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6402 (overlay-put o 'invisible t)
6403 (overlay-put o 'org-custom-property t)
6404 (push o org-custom-properties-overlays))))
6405 org-custom-properties)))))))
6407 (defun org-fontify-entities (limit)
6408 "Find an entity to fontify."
6409 (let (ee)
6410 (when org-pretty-entities
6411 (catch 'match
6412 (while (re-search-forward
6413 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6414 limit t)
6415 (if (and (not (org-in-indented-comment-line))
6416 (setq ee (org-entity-get (match-string 1)))
6417 (= (length (nth 6 ee)) 1))
6418 (let*
6419 ((end (if (equal (match-string 2) "{}")
6420 (match-end 2)
6421 (match-end 1))))
6422 (add-text-properties
6423 (match-beginning 0) end
6424 (list 'font-lock-fontified t))
6425 (compose-region (match-beginning 0) end
6426 (nth 6 ee) nil)
6427 (backward-char 1)
6428 (throw 'match t))))
6429 nil))))
6431 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6432 "Fontify string S like in Org-mode."
6433 (with-temp-buffer
6434 (insert s)
6435 (let ((org-odd-levels-only odd-levels))
6436 (org-mode)
6437 (font-lock-fontify-buffer)
6438 (buffer-string))))
6440 (defvar org-m nil)
6441 (defvar org-l nil)
6442 (defvar org-f nil)
6443 (defun org-get-level-face (n)
6444 "Get the right face for match N in font-lock matching of headlines."
6445 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6446 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6447 (if org-cycle-level-faces
6448 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6449 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6450 (cond
6451 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6452 ((eq n 2) org-f)
6453 (t (if org-level-color-stars-only nil org-f))))
6456 (defun org-get-todo-face (kwd)
6457 "Get the right face for a TODO keyword KWD.
6458 If KWD is a number, get the corresponding match group."
6459 (if (numberp kwd) (setq kwd (match-string kwd)))
6460 (or (org-face-from-face-or-color
6461 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6462 (and (member kwd org-done-keywords) 'org-done)
6463 'org-todo))
6465 (defun org-face-from-face-or-color (context inherit face-or-color)
6466 "Create a face list that inherits INHERIT, but sets the foreground color.
6467 When FACE-OR-COLOR is not a string, just return it."
6468 (if (stringp face-or-color)
6469 (list :inherit inherit
6470 (cdr (assoc context org-faces-easy-properties))
6471 face-or-color)
6472 face-or-color))
6474 (defun org-font-lock-add-tag-faces (limit)
6475 "Add the special tag faces."
6476 (when (and org-tag-faces org-tags-special-faces-re)
6477 (while (re-search-forward org-tags-special-faces-re limit t)
6478 (add-text-properties (match-beginning 1) (match-end 1)
6479 (list 'face (org-get-tag-face 1)
6480 'font-lock-fontified t))
6481 (backward-char 1))))
6483 (defun org-font-lock-add-priority-faces (limit)
6484 "Add the special priority faces."
6485 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6486 (when (save-match-data (org-at-heading-p))
6487 (add-text-properties
6488 (match-beginning 0) (match-end 0)
6489 (list 'face (or (org-face-from-face-or-color
6490 'priority 'org-priority
6491 (cdr (assoc (char-after (match-beginning 1))
6492 org-priority-faces)))
6493 'org-priority)
6494 'font-lock-fontified t)))))
6496 (defun org-get-tag-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 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6502 'org-tag))
6504 (defun org-unfontify-region (beg end &optional maybe_loudly)
6505 "Remove fontification and activation overlays from links."
6506 (font-lock-default-unfontify-region beg end)
6507 (let* ((buffer-undo-list t)
6508 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6509 (inhibit-modification-hooks t)
6510 deactivate-mark buffer-file-name buffer-file-truename)
6511 (org-decompose-region beg end)
6512 (remove-text-properties beg end
6513 '(mouse-face t keymap t org-linked-text t
6514 invisible t intangible t
6515 org-emphasis t))
6516 (org-remove-font-lock-display-properties beg end)))
6518 (defconst org-script-display '(((raise -0.3) (height 0.7))
6519 ((raise 0.3) (height 0.7))
6520 ((raise -0.5))
6521 ((raise 0.5)))
6522 "Display properties for showing superscripts and subscripts.")
6524 (defun org-remove-font-lock-display-properties (beg end)
6525 "Remove specific display properties that have been added by font lock.
6526 The will remove the raise properties that are used to show superscripts
6527 and subscripts."
6528 (let (next prop)
6529 (while (< beg end)
6530 (setq next (next-single-property-change beg 'display nil end)
6531 prop (get-text-property beg 'display))
6532 (if (member prop org-script-display)
6533 (put-text-property beg next 'display nil))
6534 (setq beg next))))
6536 (defun org-raise-scripts (limit)
6537 "Add raise properties to sub/superscripts."
6538 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6539 (if (re-search-forward
6540 (if (eq org-use-sub-superscripts t)
6541 org-match-substring-regexp
6542 org-match-substring-with-braces-regexp)
6543 limit t)
6544 (let* ((pos (point)) table-p comment-p
6545 (mpos (match-beginning 3))
6546 (emph-p (get-text-property mpos 'org-emphasis))
6547 (link-p (get-text-property mpos 'mouse-face))
6548 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6549 (goto-char (point-at-bol))
6550 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6551 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6552 (goto-char pos)
6553 ;; Handle a_b^c
6554 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6555 (if (or comment-p emph-p link-p keyw-p)
6557 (put-text-property (match-beginning 3) (match-end 0)
6558 'display
6559 (if (equal (char-after (match-beginning 2)) ?^)
6560 (nth (if table-p 3 1) org-script-display)
6561 (nth (if table-p 2 0) org-script-display)))
6562 (add-text-properties (match-beginning 2) (match-end 2)
6563 (list 'invisible t
6564 'org-dwidth t 'org-dwidth-n 1))
6565 (if (and (eq (char-after (match-beginning 3)) ?{)
6566 (eq (char-before (match-end 3)) ?}))
6567 (progn
6568 (add-text-properties
6569 (match-beginning 3) (1+ (match-beginning 3))
6570 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6571 (add-text-properties
6572 (1- (match-end 3)) (match-end 3)
6573 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6574 t)))))
6576 ;;;; Visibility cycling, including org-goto and indirect buffer
6578 ;;; Cycling
6580 (defvar org-cycle-global-status nil)
6581 (make-variable-buffer-local 'org-cycle-global-status)
6582 (put 'org-cycle-global-status 'org-state t)
6583 (defvar org-cycle-subtree-status nil)
6584 (make-variable-buffer-local 'org-cycle-subtree-status)
6585 (put 'org-cycle-subtree-status 'org-state t)
6587 (defvar org-inlinetask-min-level)
6589 (defun org-unlogged-message (&rest args)
6590 "Display a message, but avoid logging it in the *Messages* buffer."
6591 (let ((message-log-max nil))
6592 (apply 'message args)))
6594 ;;;###autoload
6595 (defun org-cycle (&optional arg)
6596 "TAB-action and visibility cycling for Org-mode.
6598 This is the command invoked in Org-mode by the TAB key. Its main purpose
6599 is outline visibility cycling, but it also invokes other actions
6600 in special contexts.
6602 - When this function is called with a prefix argument, rotate the entire
6603 buffer through 3 states (global cycling)
6604 1. OVERVIEW: Show only top-level headlines.
6605 2. CONTENTS: Show all headlines of all levels, but no body text.
6606 3. SHOW ALL: Show everything.
6607 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6608 determined by the variable `org-startup-folded', and by any VISIBILITY
6609 properties in the buffer.
6610 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6611 including any drawers.
6613 - When inside a table, re-align the table and move to the next field.
6615 - When point is at the beginning of a headline, rotate the subtree started
6616 by this line through 3 different states (local cycling)
6617 1. FOLDED: Only the main headline is shown.
6618 2. CHILDREN: The main headline and the direct children are shown.
6619 From this state, you can move to one of the children
6620 and zoom in further.
6621 3. SUBTREE: Show the entire subtree, including body text.
6622 If there is no subtree, switch directly from CHILDREN to FOLDED.
6624 - When point is at the beginning of an empty headline and the variable
6625 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6626 of the headline by demoting and promoting it to likely levels. This
6627 speeds up creation document structure by pressing TAB once or several
6628 times right after creating a new headline.
6630 - When there is a numeric prefix, go up to a heading with level ARG, do
6631 a `show-subtree' and return to the previous cursor position. If ARG
6632 is negative, go up that many levels.
6634 - When point is not at the beginning of a headline, execute the global
6635 binding for TAB, which is re-indenting the line. See the option
6636 `org-cycle-emulate-tab' for details.
6638 - Special case: if point is at the beginning of the buffer and there is
6639 no headline in line 1, this function will act as if called with prefix arg
6640 (C-u TAB, same as S-TAB) also when called without prefix arg.
6641 But only if also the variable `org-cycle-global-at-bob' is t."
6642 (interactive "P")
6643 (org-load-modules-maybe)
6644 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6645 (and org-cycle-level-after-item/entry-creation
6646 (or (org-cycle-level)
6647 (org-cycle-item-indentation))))
6648 (let* ((limit-level
6649 (or org-cycle-max-level
6650 (and (boundp 'org-inlinetask-min-level)
6651 org-inlinetask-min-level
6652 (1- org-inlinetask-min-level))))
6653 (nstars (and limit-level
6654 (if org-odd-levels-only
6655 (and limit-level (1- (* limit-level 2)))
6656 limit-level)))
6657 (org-outline-regexp
6658 (if (not (derived-mode-p 'org-mode))
6659 outline-regexp
6660 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6661 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6662 (not (looking-at org-outline-regexp))))
6663 (org-cycle-hook
6664 (if bob-special
6665 (delq 'org-optimize-window-after-visibility-change
6666 (copy-sequence org-cycle-hook))
6667 org-cycle-hook))
6668 (pos (point)))
6670 (if (or bob-special (equal arg '(4)))
6671 ;; special case: use global cycling
6672 (setq arg t))
6674 (cond
6676 ((equal arg '(16))
6677 (setq last-command 'dummy)
6678 (org-set-startup-visibility)
6679 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6681 ((equal arg '(64))
6682 (show-all)
6683 (org-unlogged-message "Entire buffer visible, including drawers"))
6685 ;; Try cdlatex TAB completion
6686 ((org-try-cdlatex-tab))
6688 ;; Table: enter it or move to the next field.
6689 ((org-at-table-p 'any)
6690 (if (org-at-table.el-p)
6691 (message "Use C-c ' to edit table.el tables")
6692 (if arg (org-table-edit-field t)
6693 (org-table-justify-field-maybe)
6694 (call-interactively 'org-table-next-field))))
6696 ((run-hook-with-args-until-success
6697 'org-tab-after-check-for-table-hook))
6699 ;; Global cycling: delegate to `org-cycle-internal-global'.
6700 ((eq arg t) (org-cycle-internal-global))
6702 ;; Drawers: delegate to `org-flag-drawer'.
6703 ((save-excursion
6704 (beginning-of-line 1)
6705 (looking-at org-drawer-regexp))
6706 (org-flag-drawer ; toggle block visibility
6707 (not (get-char-property (match-end 0) 'invisible))))
6709 ;; Show-subtree, ARG levels up from here.
6710 ((integerp arg)
6711 (save-excursion
6712 (org-back-to-heading)
6713 (outline-up-heading (if (< arg 0) (- arg)
6714 (- (funcall outline-level) arg)))
6715 (org-show-subtree)))
6717 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6718 ((and (featurep 'org-inlinetask)
6719 (org-inlinetask-at-task-p)
6720 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6721 (org-inlinetask-toggle-visibility))
6723 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6724 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6725 (save-excursion (beginning-of-line 1)
6726 (looking-at org-outline-regexp)))
6727 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6728 (org-cycle-internal-local))
6730 ;; From there: TAB emulation and template completion.
6731 (buffer-read-only (org-back-to-heading))
6733 ((run-hook-with-args-until-success
6734 'org-tab-after-check-for-cycling-hook))
6736 ((org-try-structure-completion))
6738 ((run-hook-with-args-until-success
6739 'org-tab-before-tab-emulation-hook))
6741 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6742 (or (not (bolp))
6743 (not (looking-at org-outline-regexp))))
6744 (call-interactively (global-key-binding "\t")))
6746 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6747 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6748 (or (and (eq org-cycle-emulate-tab 'white)
6749 (= (match-end 0) (point-at-eol)))
6750 (and (eq org-cycle-emulate-tab 'whitestart)
6751 (>= (match-end 0) pos))))
6753 (eq org-cycle-emulate-tab t))
6754 (call-interactively (global-key-binding "\t")))
6756 (t (save-excursion
6757 (org-back-to-heading)
6758 (org-cycle)))))))
6760 (defun org-cycle-internal-global ()
6761 "Do the global cycling action."
6762 ;; Hack to avoid display of messages for .org attachments in Gnus
6763 (let ((ga (string-match "\\*fontification" (buffer-name))))
6764 (cond
6765 ((and (eq last-command this-command)
6766 (eq org-cycle-global-status 'overview))
6767 ;; We just created the overview - now do table of contents
6768 ;; This can be slow in very large buffers, so indicate action
6769 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6770 (unless ga (org-unlogged-message "CONTENTS..."))
6771 (org-content)
6772 (unless ga (org-unlogged-message "CONTENTS...done"))
6773 (setq org-cycle-global-status 'contents)
6774 (run-hook-with-args 'org-cycle-hook 'contents))
6776 ((and (eq last-command this-command)
6777 (eq org-cycle-global-status 'contents))
6778 ;; We just showed the table of contents - now show everything
6779 (run-hook-with-args 'org-pre-cycle-hook 'all)
6780 (show-all)
6781 (unless ga (org-unlogged-message "SHOW ALL"))
6782 (setq org-cycle-global-status 'all)
6783 (run-hook-with-args 'org-cycle-hook 'all))
6786 ;; Default action: go to overview
6787 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6788 (org-overview)
6789 (unless ga (org-unlogged-message "OVERVIEW"))
6790 (setq org-cycle-global-status 'overview)
6791 (run-hook-with-args 'org-cycle-hook 'overview)))))
6793 (defvar org-called-with-limited-levels);Dyn-bound in ̀org-with-limited-levels'.
6795 (defun org-cycle-internal-local ()
6796 "Do the local cycling action."
6797 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6798 ;; First, determine end of headline (EOH), end of subtree or item
6799 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6800 (save-excursion
6801 (if (org-at-item-p)
6802 (progn
6803 (beginning-of-line)
6804 (setq struct (org-list-struct))
6805 (setq eoh (point-at-eol))
6806 (setq eos (org-list-get-item-end-before-blank (point) struct))
6807 (setq has-children (org-list-has-child-p (point) struct)))
6808 (org-back-to-heading)
6809 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6810 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6811 (setq has-children
6812 (or (save-excursion
6813 (let ((level (funcall outline-level)))
6814 (outline-next-heading)
6815 (and (org-at-heading-p t)
6816 (> (funcall outline-level) level))))
6817 (save-excursion
6818 (org-list-search-forward (org-item-beginning-re) eos t)))))
6819 ;; Determine end invisible part of buffer (EOL)
6820 (beginning-of-line 2)
6821 ;; XEmacs doesn't have `next-single-char-property-change'
6822 (if (featurep 'xemacs)
6823 (while (and (not (eobp)) ;; this is like `next-line'
6824 (get-char-property (1- (point)) 'invisible))
6825 (beginning-of-line 2))
6826 (while (and (not (eobp)) ;; this is like `next-line'
6827 (get-char-property (1- (point)) 'invisible))
6828 (goto-char (next-single-char-property-change (point) 'invisible))
6829 (and (eolp) (beginning-of-line 2))))
6830 (setq eol (point)))
6831 ;; Find out what to do next and set `this-command'
6832 (cond
6833 ((= eos eoh)
6834 ;; Nothing is hidden behind this heading
6835 (unless (org-before-first-heading-p)
6836 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6837 (org-unlogged-message "EMPTY ENTRY")
6838 (setq org-cycle-subtree-status nil)
6839 (save-excursion
6840 (goto-char eos)
6841 (outline-next-heading)
6842 (if (outline-invisible-p) (org-flag-heading nil))))
6843 ((and (or (>= eol eos)
6844 (not (string-match "\\S-" (buffer-substring eol eos))))
6845 (or has-children
6846 (not (setq children-skipped
6847 org-cycle-skip-children-state-if-no-children))))
6848 ;; Entire subtree is hidden in one line: children view
6849 (unless (org-before-first-heading-p)
6850 (run-hook-with-args 'org-pre-cycle-hook 'children))
6851 (if (org-at-item-p)
6852 (org-list-set-item-visibility (point-at-bol) struct 'children)
6853 (org-show-entry)
6854 (org-with-limited-levels (show-children))
6855 ;; FIXME: This slows down the func way too much.
6856 ;; How keep drawers hidden in subtree anyway?
6857 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6858 ;; (org-cycle-hide-drawers 'subtree))
6860 ;; Fold every list in subtree to top-level items.
6861 (when (eq org-cycle-include-plain-lists 'integrate)
6862 (save-excursion
6863 (org-back-to-heading)
6864 (while (org-list-search-forward (org-item-beginning-re) eos t)
6865 (beginning-of-line 1)
6866 (let* ((struct (org-list-struct))
6867 (prevs (org-list-prevs-alist struct))
6868 (end (org-list-get-bottom-point struct)))
6869 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6870 (org-list-get-all-items (point) struct prevs))
6871 (goto-char (if (< end eos) end eos)))))))
6872 (org-unlogged-message "CHILDREN")
6873 (save-excursion
6874 (goto-char eos)
6875 (outline-next-heading)
6876 (if (outline-invisible-p) (org-flag-heading nil)))
6877 (setq org-cycle-subtree-status 'children)
6878 (unless (org-before-first-heading-p)
6879 (run-hook-with-args 'org-cycle-hook 'children)))
6880 ((or children-skipped
6881 (and (eq last-command this-command)
6882 (eq org-cycle-subtree-status 'children)))
6883 ;; We just showed the children, or no children are there,
6884 ;; now show everything.
6885 (unless (org-before-first-heading-p)
6886 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6887 (outline-flag-region eoh eos nil)
6888 (org-unlogged-message
6889 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6890 (setq org-cycle-subtree-status 'subtree)
6891 (unless (org-before-first-heading-p)
6892 (run-hook-with-args 'org-cycle-hook 'subtree)))
6894 ;; Default action: hide the subtree.
6895 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6896 (outline-flag-region eoh eos t)
6897 (org-unlogged-message "FOLDED")
6898 (setq org-cycle-subtree-status 'folded)
6899 (unless (org-before-first-heading-p)
6900 (run-hook-with-args 'org-cycle-hook 'folded))))))
6902 ;;;###autoload
6903 (defun org-global-cycle (&optional arg)
6904 "Cycle the global visibility. For details see `org-cycle'.
6905 With \\[universal-argument] prefix arg, switch to startup visibility.
6906 With a numeric prefix, show all headlines up to that level."
6907 (interactive "P")
6908 (let ((org-cycle-include-plain-lists
6909 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6910 (cond
6911 ((integerp arg)
6912 (show-all)
6913 (hide-sublevels arg)
6914 (setq org-cycle-global-status 'contents))
6915 ((equal arg '(4))
6916 (org-set-startup-visibility)
6917 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6919 (org-cycle '(4))))))
6921 (defun org-set-startup-visibility ()
6922 "Set the visibility required by startup options and properties."
6923 (cond
6924 ((eq org-startup-folded t)
6925 (org-overview))
6926 ((eq org-startup-folded 'content)
6927 (org-content))
6928 ((or (eq org-startup-folded 'showeverything)
6929 (eq org-startup-folded nil))
6930 (show-all)))
6931 (unless (eq org-startup-folded 'showeverything)
6932 (if org-hide-block-startup (org-hide-block-all))
6933 (org-set-visibility-according-to-property 'no-cleanup)
6934 (org-cycle-hide-archived-subtrees 'all)
6935 (org-cycle-hide-drawers 'all)
6936 (org-cycle-show-empty-lines t)))
6938 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6939 "Switch subtree visibilities according to :VISIBILITY: property."
6940 (interactive)
6941 (let (org-show-entry-below state)
6942 (save-excursion
6943 (goto-char (point-min))
6944 (while (re-search-forward
6945 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6946 nil t)
6947 (setq state (match-string 1))
6948 (save-excursion
6949 (org-back-to-heading t)
6950 (hide-subtree)
6951 (org-reveal)
6952 (cond
6953 ((equal state '("fold" "folded"))
6954 (hide-subtree))
6955 ((equal state "children")
6956 (org-show-hidden-entry)
6957 (show-children))
6958 ((equal state "content")
6959 (save-excursion
6960 (save-restriction
6961 (org-narrow-to-subtree)
6962 (org-content))))
6963 ((member state '("all" "showall"))
6964 (show-subtree)))))
6965 (unless no-cleanup
6966 (org-cycle-hide-archived-subtrees 'all)
6967 (org-cycle-hide-drawers 'all)
6968 (org-cycle-show-empty-lines 'all)))))
6970 ;; This function uses outline-regexp instead of the more fundamental
6971 ;; org-outline-regexp so that org-cycle-global works outside of Org
6972 ;; buffers, where outline-regexp is needed.
6973 (defun org-overview ()
6974 "Switch to overview mode, showing only top-level headlines.
6975 Really, this shows all headlines with level equal or greater than the level
6976 of the first headline in the buffer. This is important, because if the
6977 first headline is not level one, then (hide-sublevels 1) gives confusing
6978 results."
6979 (interactive)
6980 (let ((pos (point))
6981 (level (save-excursion
6982 (goto-char (point-min))
6983 (if (re-search-forward (concat "^" outline-regexp) nil t)
6984 (progn
6985 (goto-char (match-beginning 0))
6986 (funcall outline-level))))))
6987 (and level (hide-sublevels level))
6988 (recenter '(4))
6989 (goto-char pos)))
6991 (defun org-content (&optional arg)
6992 "Show all headlines in the buffer, like a table of contents.
6993 With numerical argument N, show content up to level N."
6994 (interactive "P")
6995 (org-overview)
6996 (save-excursion
6997 ;; Visit all headings and show their offspring
6998 (and (integerp arg) (org-overview))
6999 (goto-char (point-max))
7000 (catch 'exit
7001 (while (and (progn (condition-case nil
7002 (outline-previous-visible-heading 1)
7003 (error (goto-char (point-min))))
7005 (looking-at org-outline-regexp))
7006 (if (integerp arg)
7007 (show-children (1- arg))
7008 (show-branches))
7009 (if (bobp) (throw 'exit nil))))))
7011 (defun org-optimize-window-after-visibility-change (state)
7012 "Adjust the window after a change in outline visibility.
7013 This function is the default value of the hook `org-cycle-hook'."
7014 (when (get-buffer-window (current-buffer))
7015 (cond
7016 ((eq state 'content) nil)
7017 ((eq state 'all) nil)
7018 ((eq state 'folded) nil)
7019 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7020 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7022 (defun org-remove-empty-overlays-at (pos)
7023 "Remove outline overlays that do not contain non-white stuff."
7024 (mapc
7025 (lambda (o)
7026 (and (eq 'outline (overlay-get o 'invisible))
7027 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7028 (overlay-end o))))
7029 (delete-overlay o)))
7030 (overlays-at pos)))
7032 (defun org-clean-visibility-after-subtree-move ()
7033 "Fix visibility issues after moving a subtree."
7034 ;; First, find a reasonable region to look at:
7035 ;; Start two siblings above, end three below
7036 (let* ((beg (save-excursion
7037 (and (org-get-last-sibling)
7038 (org-get-last-sibling))
7039 (point)))
7040 (end (save-excursion
7041 (and (org-get-next-sibling)
7042 (org-get-next-sibling)
7043 (org-get-next-sibling))
7044 (if (org-at-heading-p)
7045 (point-at-eol)
7046 (point))))
7047 (level (looking-at "\\*+"))
7048 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
7049 (save-excursion
7050 (save-restriction
7051 (narrow-to-region beg end)
7052 (when re
7053 ;; Properly fold already folded siblings
7054 (goto-char (point-min))
7055 (while (re-search-forward re nil t)
7056 (if (and (not (outline-invisible-p))
7057 (save-excursion
7058 (goto-char (point-at-eol)) (outline-invisible-p)))
7059 (hide-entry))))
7060 (org-cycle-show-empty-lines 'overview)
7061 (org-cycle-hide-drawers 'overview)))))
7063 (defun org-cycle-show-empty-lines (state)
7064 "Show empty lines above all visible headlines.
7065 The region to be covered depends on STATE when called through
7066 `org-cycle-hook'. Lisp program can use t for STATE to get the
7067 entire buffer covered. Note that an empty line is only shown if there
7068 are at least `org-cycle-separator-lines' empty lines before the headline."
7069 (when (not (= org-cycle-separator-lines 0))
7070 (save-excursion
7071 (let* ((n (abs org-cycle-separator-lines))
7072 (re (cond
7073 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7074 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7075 (t (let ((ns (number-to-string (- n 2))))
7076 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7077 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7078 beg end b e)
7079 (cond
7080 ((memq state '(overview contents t))
7081 (setq beg (point-min) end (point-max)))
7082 ((memq state '(children folded))
7083 (setq beg (point) end (progn (org-end-of-subtree t t)
7084 (beginning-of-line 2)
7085 (point)))))
7086 (when beg
7087 (goto-char beg)
7088 (while (re-search-forward re end t)
7089 (unless (get-char-property (match-end 1) 'invisible)
7090 (setq e (match-end 1))
7091 (if (< org-cycle-separator-lines 0)
7092 (setq b (save-excursion
7093 (goto-char (match-beginning 0))
7094 (org-back-over-empty-lines)
7095 (if (save-excursion
7096 (goto-char (max (point-min) (1- (point))))
7097 (org-at-heading-p))
7098 (1- (point))
7099 (point))))
7100 (setq b (match-beginning 1)))
7101 (outline-flag-region b e nil)))))))
7102 ;; Never hide empty lines at the end of the file.
7103 (save-excursion
7104 (goto-char (point-max))
7105 (outline-previous-heading)
7106 (outline-end-of-heading)
7107 (if (and (looking-at "[ \t\n]+")
7108 (= (match-end 0) (point-max)))
7109 (outline-flag-region (point) (match-end 0) nil))))
7111 (defun org-show-empty-lines-in-parent ()
7112 "Move to the parent and re-show empty lines before visible headlines."
7113 (save-excursion
7114 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7115 (org-cycle-show-empty-lines context))))
7117 (defun org-files-list ()
7118 "Return `org-agenda-files' list, plus all open org-mode files.
7119 This is useful for operations that need to scan all of a user's
7120 open and agenda-wise Org files."
7121 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7122 (dolist (buf (buffer-list))
7123 (with-current-buffer buf
7124 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7125 (let ((file (expand-file-name (buffer-file-name))))
7126 (unless (member file files)
7127 (push file files))))))
7128 files))
7130 (defsubst org-entry-beginning-position ()
7131 "Return the beginning position of the current entry."
7132 (save-excursion (outline-back-to-heading t) (point)))
7134 (defsubst org-entry-end-position ()
7135 "Return the end position of the current entry."
7136 (save-excursion (outline-next-heading) (point)))
7138 (defun org-cycle-hide-drawers (state &optional exceptions)
7139 "Re-hide all drawers after a visibility state change.
7140 When non-nil, optional argument EXCEPTIONS is a list of strings
7141 specifying which drawers should not be hidden."
7142 (when (and (derived-mode-p 'org-mode)
7143 (not (memq state '(overview folded contents))))
7144 (save-excursion
7145 (let* ((globalp (memq state '(contents all)))
7146 (beg (if globalp (point-min) (point)))
7147 (end (if globalp (point-max)
7148 (if (eq state 'children)
7149 (save-excursion (outline-next-heading) (point))
7150 (org-end-of-subtree t)))))
7151 (goto-char beg)
7152 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7153 (unless (member-ignore-case (match-string 1) exceptions)
7154 (let ((drawer (org-element-at-point)))
7155 (when (memq (org-element-type drawer) '(drawer property-drawer))
7156 (org-flag-drawer t drawer)
7157 ;; Make sure to skip drawer entirely or we might flag
7158 ;; it another time when matching its ending line with
7159 ;; `org-drawer-regexp'.
7160 (goto-char (org-element-property :end drawer))))))))))
7162 (defun org-cycle-hide-inline-tasks (state)
7163 "Re-hide inline tasks when switching to 'contents or 'children
7164 visibility state."
7165 (case state
7166 (contents
7167 (when (org-bound-and-true-p org-inlinetask-min-level)
7168 (hide-sublevels (1- org-inlinetask-min-level))))
7169 (children
7170 (when (featurep 'org-inlinetask)
7171 (save-excursion
7172 (while (and (outline-next-heading)
7173 (org-inlinetask-at-task-p))
7174 (org-inlinetask-toggle-visibility)
7175 (org-inlinetask-goto-end)))))))
7177 (defun org-flag-drawer (flag &optional element)
7178 "When FLAG is non-nil, hide the drawer we are at.
7179 Otherwise make it visible. When optional argument ELEMENT is
7180 a parsed drawer, as returned by `org-element-at-point', hide or
7181 show that drawer instead."
7182 (let ((drawer (or element (org-element-at-point))))
7183 (when (memq (org-element-type drawer) '(drawer property-drawer))
7184 (save-excursion
7185 (goto-char (org-element-property :post-affiliated drawer))
7186 (outline-flag-region
7187 (line-end-position)
7188 (progn (goto-char (org-element-property :end drawer))
7189 (skip-chars-backward " \r\t\n")
7190 (line-end-position))
7191 flag)))))
7193 (defun org-subtree-end-visible-p ()
7194 "Is the end of the current subtree visible?"
7195 (pos-visible-in-window-p
7196 (save-excursion (org-end-of-subtree t) (point))))
7198 (defun org-first-headline-recenter (&optional N)
7199 "Move cursor to the first headline and recenter the headline.
7200 Optional argument N means put the headline into the Nth line of the window."
7201 (goto-char (point-min))
7202 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7203 (beginning-of-line)
7204 (recenter (prefix-numeric-value N))))
7206 ;;; Saving and restoring visibility
7208 (defun org-outline-overlay-data (&optional use-markers)
7209 "Return a list of the locations of all outline overlays.
7210 These are overlays with the `invisible' property value `outline'.
7211 The return value is a list of cons cells, with start and stop
7212 positions for each overlay.
7213 If USE-MARKERS is set, return the positions as markers."
7214 (let (beg end)
7215 (save-excursion
7216 (save-restriction
7217 (widen)
7218 (delq nil
7219 (mapcar (lambda (o)
7220 (when (eq (overlay-get o 'invisible) 'outline)
7221 (setq beg (overlay-start o)
7222 end (overlay-end o))
7223 (and beg end (> end beg)
7224 (if use-markers
7225 (cons (copy-marker beg)
7226 (copy-marker end t))
7227 (cons beg end)))))
7228 (overlays-in (point-min) (point-max))))))))
7230 (defun org-set-outline-overlay-data (data)
7231 "Create visibility overlays for all positions in DATA.
7232 DATA should have been made by `org-outline-overlay-data'."
7233 (let (o)
7234 (save-excursion
7235 (save-restriction
7236 (widen)
7237 (show-all)
7238 (mapc (lambda (c)
7239 (outline-flag-region (car c) (cdr c) t))
7240 data)))))
7242 ;;; Folding of blocks
7244 (defvar org-hide-block-overlays nil
7245 "Overlays hiding blocks.")
7246 (make-variable-buffer-local 'org-hide-block-overlays)
7248 (defun org-block-map (function &optional start end)
7249 "Call FUNCTION at the head of all source blocks in the current buffer.
7250 Optional arguments START and END can be used to limit the range."
7251 (let ((start (or start (point-min)))
7252 (end (or end (point-max))))
7253 (save-excursion
7254 (goto-char start)
7255 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7256 (save-excursion
7257 (save-match-data
7258 (goto-char (match-beginning 0))
7259 (funcall function)))))))
7261 (defun org-hide-block-toggle-all ()
7262 "Toggle the visibility of all blocks in the current buffer."
7263 (org-block-map #'org-hide-block-toggle))
7265 (defun org-hide-block-all ()
7266 "Fold all blocks in the current buffer."
7267 (interactive)
7268 (org-show-block-all)
7269 (org-block-map #'org-hide-block-toggle-maybe))
7271 (defun org-show-block-all ()
7272 "Unfold all blocks in the current buffer."
7273 (interactive)
7274 (mapc 'delete-overlay org-hide-block-overlays)
7275 (setq org-hide-block-overlays nil))
7277 (defun org-hide-block-toggle-maybe ()
7278 "Toggle visibility of block at point."
7279 (interactive)
7280 (let ((case-fold-search t))
7281 (if (save-excursion
7282 (beginning-of-line 1)
7283 (looking-at org-block-regexp))
7284 (progn (org-hide-block-toggle)
7285 t) ;; to signal that we took action
7286 nil))) ;; to signal that we did not
7288 (defun org-hide-block-toggle (&optional force)
7289 "Toggle the visibility of the current block."
7290 (interactive)
7291 (save-excursion
7292 (beginning-of-line)
7293 (if (re-search-forward org-block-regexp nil t)
7294 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7295 (end (match-end 0)) ;; end of entire body
7297 (if (memq t (mapcar (lambda (overlay)
7298 (eq (overlay-get overlay 'invisible)
7299 'org-hide-block))
7300 (overlays-at start)))
7301 (if (or (not force) (eq force 'off))
7302 (mapc (lambda (ov)
7303 (when (member ov org-hide-block-overlays)
7304 (setq org-hide-block-overlays
7305 (delq ov org-hide-block-overlays)))
7306 (when (eq (overlay-get ov 'invisible)
7307 'org-hide-block)
7308 (delete-overlay ov)))
7309 (overlays-at start)))
7310 (setq ov (make-overlay start end))
7311 (overlay-put ov 'invisible 'org-hide-block)
7312 ;; make the block accessible to isearch
7313 (overlay-put
7314 ov 'isearch-open-invisible
7315 (lambda (ov)
7316 (when (member ov org-hide-block-overlays)
7317 (setq org-hide-block-overlays
7318 (delq ov org-hide-block-overlays)))
7319 (when (eq (overlay-get ov 'invisible)
7320 'org-hide-block)
7321 (delete-overlay ov))))
7322 (push ov org-hide-block-overlays)))
7323 (user-error "Not looking at a source block"))))
7325 ;; org-tab-after-check-for-cycling-hook
7326 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7327 ;; Remove overlays when changing major mode
7328 (add-hook 'org-mode-hook
7329 (lambda () (org-add-hook 'change-major-mode-hook
7330 'org-show-block-all 'append 'local)))
7332 ;;; Org-goto
7334 (defvar org-goto-window-configuration nil)
7335 (defvar org-goto-marker nil)
7336 (defvar org-goto-map)
7337 (defun org-goto-map ()
7338 "Set the keymap `org-goto'."
7339 (setq org-goto-map
7340 (let ((map (make-sparse-keymap)))
7341 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7342 mouse-drag-region universal-argument org-occur))
7343 cmd)
7344 (while (setq cmd (pop cmds))
7345 (substitute-key-definition cmd cmd map global-map)))
7346 (suppress-keymap map)
7347 (org-defkey map "\C-m" 'org-goto-ret)
7348 (org-defkey map [(return)] 'org-goto-ret)
7349 (org-defkey map [(left)] 'org-goto-left)
7350 (org-defkey map [(right)] 'org-goto-right)
7351 (org-defkey map [(control ?g)] 'org-goto-quit)
7352 (org-defkey map "\C-i" 'org-cycle)
7353 (org-defkey map [(tab)] 'org-cycle)
7354 (org-defkey map [(down)] 'outline-next-visible-heading)
7355 (org-defkey map [(up)] 'outline-previous-visible-heading)
7356 (if org-goto-auto-isearch
7357 (if (fboundp 'define-key-after)
7358 (define-key-after map [t] 'org-goto-local-auto-isearch)
7359 nil)
7360 (org-defkey map "q" 'org-goto-quit)
7361 (org-defkey map "n" 'outline-next-visible-heading)
7362 (org-defkey map "p" 'outline-previous-visible-heading)
7363 (org-defkey map "f" 'outline-forward-same-level)
7364 (org-defkey map "b" 'outline-backward-same-level)
7365 (org-defkey map "u" 'outline-up-heading))
7366 (org-defkey map "/" 'org-occur)
7367 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7368 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7369 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7370 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7371 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7372 map)))
7374 (defconst org-goto-help
7375 "Browse buffer copy, to find location or copy text.%s
7376 RET=jump to location C-g=quit and return to previous location
7377 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7379 (defvar org-goto-start-pos) ; dynamically scoped parameter
7381 (defun org-goto (&optional alternative-interface)
7382 "Look up a different location in the current file, keeping current visibility.
7384 When you want look-up or go to a different location in a
7385 document, the fastest way is often to fold the entire buffer and
7386 then dive into the tree. This method has the disadvantage, that
7387 the previous location will be folded, which may not be what you
7388 want.
7390 This command works around this by showing a copy of the current
7391 buffer in an indirect buffer, in overview mode. You can dive
7392 into the tree in that copy, use org-occur and incremental search
7393 to find a location. When pressing RET or `Q', the command
7394 returns to the original buffer in which the visibility is still
7395 unchanged. After RET it will also jump to the location selected
7396 in the indirect buffer and expose the headline hierarchy above.
7398 With a prefix argument, use the alternative interface: e.g. if
7399 `org-goto-interface' is 'outline use 'outline-path-completion."
7400 (interactive "P")
7401 (org-goto-map)
7402 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7403 (org-refile-use-outline-path t)
7404 (org-refile-target-verify-function nil)
7405 (interface
7406 (if (not alternative-interface)
7407 org-goto-interface
7408 (if (eq org-goto-interface 'outline)
7409 'outline-path-completion
7410 'outline)))
7411 (org-goto-start-pos (point))
7412 (selected-point
7413 (if (eq interface 'outline)
7414 (car (org-get-location (current-buffer) org-goto-help))
7415 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7416 (org-refile-check-position pa)
7417 (nth 3 pa)))))
7418 (if selected-point
7419 (progn
7420 (org-mark-ring-push org-goto-start-pos)
7421 (goto-char selected-point)
7422 (if (or (outline-invisible-p) (org-invisible-p2))
7423 (org-show-context 'org-goto)))
7424 (message "Quit"))))
7426 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7427 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7428 (defvar org-goto-local-auto-isearch-map) ; defined below
7430 (defun org-get-location (buf help)
7431 "Let the user select a location in the Org-mode buffer BUF.
7432 This function uses a recursive edit. It returns the selected position
7433 or nil."
7434 (org-no-popups
7435 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7436 (isearch-hide-immediately nil)
7437 (isearch-search-fun-function
7438 (lambda () 'org-goto-local-search-headings))
7439 (org-goto-selected-point org-goto-exit-command))
7440 (save-excursion
7441 (save-window-excursion
7442 (delete-other-windows)
7443 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7444 (org-pop-to-buffer-same-window
7445 (condition-case nil
7446 (make-indirect-buffer (current-buffer) "*org-goto*")
7447 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7448 (with-output-to-temp-buffer "*Org Help*"
7449 (princ (format help (if org-goto-auto-isearch
7450 " Just type for auto-isearch."
7451 " n/p/f/b/u to navigate, q to quit."))))
7452 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7453 (setq buffer-read-only nil)
7454 (let ((org-startup-truncated t)
7455 (org-startup-folded nil)
7456 (org-startup-align-all-tables nil))
7457 (org-mode)
7458 (org-overview))
7459 (setq buffer-read-only t)
7460 (if (and (boundp 'org-goto-start-pos)
7461 (integer-or-marker-p org-goto-start-pos))
7462 (let ((org-show-hierarchy-above t)
7463 (org-show-siblings t)
7464 (org-show-following-heading t))
7465 (goto-char org-goto-start-pos)
7466 (and (outline-invisible-p) (org-show-context)))
7467 (goto-char (point-min)))
7468 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7469 (message "Select location and press RET")
7470 (use-local-map org-goto-map)
7471 (recursive-edit)))
7472 (kill-buffer "*org-goto*")
7473 (cons org-goto-selected-point org-goto-exit-command))))
7475 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7476 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7477 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7478 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7480 (defun org-goto-local-search-headings (string bound noerror)
7481 "Search and make sure that any matches are in headlines."
7482 (catch 'return
7483 (while (if isearch-forward
7484 (search-forward string bound noerror)
7485 (search-backward string bound noerror))
7486 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7487 (and (member :headline context)
7488 (not (member :tags context))))
7489 (throw 'return (point))))))
7491 (defun org-goto-local-auto-isearch ()
7492 "Start isearch."
7493 (interactive)
7494 (goto-char (point-min))
7495 (let ((keys (this-command-keys)))
7496 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7497 (isearch-mode t)
7498 (isearch-process-search-char (string-to-char keys)))))
7500 (defun org-goto-ret (&optional arg)
7501 "Finish `org-goto' by going to the new location."
7502 (interactive "P")
7503 (setq org-goto-selected-point (point)
7504 org-goto-exit-command 'return)
7505 (throw 'exit nil))
7507 (defun org-goto-left ()
7508 "Finish `org-goto' by going to the new location."
7509 (interactive)
7510 (if (org-at-heading-p)
7511 (progn
7512 (beginning-of-line 1)
7513 (setq org-goto-selected-point (point)
7514 org-goto-exit-command 'left)
7515 (throw 'exit nil))
7516 (user-error "Not on a heading")))
7518 (defun org-goto-right ()
7519 "Finish `org-goto' by going to the new location."
7520 (interactive)
7521 (if (org-at-heading-p)
7522 (progn
7523 (setq org-goto-selected-point (point)
7524 org-goto-exit-command 'right)
7525 (throw 'exit nil))
7526 (user-error "Not on a heading")))
7528 (defun org-goto-quit ()
7529 "Finish `org-goto' without cursor motion."
7530 (interactive)
7531 (setq org-goto-selected-point nil)
7532 (setq org-goto-exit-command 'quit)
7533 (throw 'exit nil))
7535 ;;; Indirect buffer display of subtrees
7537 (defvar org-indirect-dedicated-frame nil
7538 "This is the frame being used for indirect tree display.")
7539 (defvar org-last-indirect-buffer nil)
7541 (defun org-tree-to-indirect-buffer (&optional arg)
7542 "Create indirect buffer and narrow it to current subtree.
7543 With a numerical prefix ARG, go up to this level and then take that tree.
7544 If ARG is negative, go up that many levels.
7546 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7547 indirect buffer previously made with this command, to avoid proliferation of
7548 indirect buffers. However, when you call the command with a \
7549 \\[universal-argument] prefix, or
7550 when `org-indirect-buffer-display' is `new-frame', the last buffer
7551 is kept so that you can work with several indirect buffers at the same time.
7552 If `org-indirect-buffer-display' is `dedicated-frame', the \
7553 \\[universal-argument] prefix also
7554 requests that a new frame be made for the new buffer, so that the dedicated
7555 frame is not changed."
7556 (interactive "P")
7557 (let ((cbuf (current-buffer))
7558 (cwin (selected-window))
7559 (pos (point))
7560 beg end level heading ibuf)
7561 (save-excursion
7562 (org-back-to-heading t)
7563 (when (numberp arg)
7564 (setq level (org-outline-level))
7565 (if (< arg 0) (setq arg (+ level arg)))
7566 (while (> (setq level (org-outline-level)) arg)
7567 (org-up-heading-safe)))
7568 (setq beg (point)
7569 heading (org-get-heading))
7570 (org-end-of-subtree t t)
7571 (if (org-at-heading-p) (backward-char 1))
7572 (setq end (point)))
7573 (if (and (buffer-live-p org-last-indirect-buffer)
7574 (not (eq org-indirect-buffer-display 'new-frame))
7575 (not arg))
7576 (kill-buffer org-last-indirect-buffer))
7577 (setq ibuf (org-get-indirect-buffer cbuf heading)
7578 org-last-indirect-buffer ibuf)
7579 (cond
7580 ((or (eq org-indirect-buffer-display 'new-frame)
7581 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7582 (select-frame (make-frame))
7583 (delete-other-windows)
7584 (org-pop-to-buffer-same-window ibuf)
7585 (org-set-frame-title heading))
7586 ((eq org-indirect-buffer-display 'dedicated-frame)
7587 (raise-frame
7588 (select-frame (or (and org-indirect-dedicated-frame
7589 (frame-live-p org-indirect-dedicated-frame)
7590 org-indirect-dedicated-frame)
7591 (setq org-indirect-dedicated-frame (make-frame)))))
7592 (delete-other-windows)
7593 (org-pop-to-buffer-same-window ibuf)
7594 (org-set-frame-title (concat "Indirect: " heading)))
7595 ((eq org-indirect-buffer-display 'current-window)
7596 (org-pop-to-buffer-same-window ibuf))
7597 ((eq org-indirect-buffer-display 'other-window)
7598 (pop-to-buffer ibuf))
7599 (t (error "Invalid value")))
7600 (if (featurep 'xemacs)
7601 (save-excursion (org-mode) (turn-on-font-lock)))
7602 (narrow-to-region beg end)
7603 (show-all)
7604 (goto-char pos)
7605 (run-hook-with-args 'org-cycle-hook 'all)
7606 (and (window-live-p cwin) (select-window cwin))))
7608 (defun org-get-indirect-buffer (&optional buffer heading)
7609 (setq buffer (or buffer (current-buffer)))
7610 (let ((n 1) (base (buffer-name buffer)) bname)
7611 (while (buffer-live-p
7612 (get-buffer
7613 (setq bname
7614 (concat base "-"
7615 (if heading (concat heading "-" (number-to-string n))
7616 (number-to-string n))))))
7617 (setq n (1+ n)))
7618 (condition-case nil
7619 (make-indirect-buffer buffer bname 'clone)
7620 (error (make-indirect-buffer buffer bname)))))
7622 (defun org-set-frame-title (title)
7623 "Set the title of the current frame to the string TITLE."
7624 ;; FIXME: how to name a single frame in XEmacs???
7625 (unless (featurep 'xemacs)
7626 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7628 ;;;; Structure editing
7630 ;;; Inserting headlines
7632 (defun org-previous-line-empty-p (&optional next)
7633 "Is the previous line a blank line?
7634 When NEXT is non-nil, check the next line instead."
7635 (save-excursion
7636 (and (not (bobp))
7637 (or (beginning-of-line (if next 2 0)) t)
7638 (save-match-data
7639 (looking-at "[ \t]*$")))))
7641 (defun org-insert-heading (&optional arg invisible-ok)
7642 "Insert a new heading or item with same depth at point.
7643 If point is in a plain list and ARG is nil, create a new list item.
7644 With one universal prefix argument, insert a heading even in lists.
7645 With two universal prefix arguments, insert the heading at the end
7646 of the parent subtree.
7648 If point is at the beginning of a headline, insert a sibling before
7649 the current headline. If point is not at the beginning, split the line
7650 and create a new headline with the text in the current line after point
7651 \(see `org-M-RET-may-split-line' on how to modify this behavior).
7653 If point is at the beginning of a normal line, turn this line into
7654 a heading.
7656 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7657 This is important for non-interactive uses of the command."
7658 (interactive "P")
7659 (if (org-called-interactively-p 'any) (org-reveal))
7660 (let ((itemp (org-in-item-p))
7661 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7662 (respect-content (or org-insert-heading-respect-content
7663 (equal arg '(4))))
7664 (initial-content "")
7665 (adjust-empty-lines t))
7667 (cond
7669 ((or (= (buffer-size) 0)
7670 (and (not (save-excursion
7671 (and (ignore-errors (org-back-to-heading invisible-ok))
7672 (org-at-heading-p))))
7673 (or arg (not itemp))))
7674 ;; At beginning of buffer or so high up that only a heading
7675 ;; makes sense.
7676 (insert
7677 (if (or (bobp) (org-previous-line-empty-p)) "" "\n")
7678 (if (org-in-src-block-p) ",* " "* "))
7679 (run-hooks 'org-insert-heading-hook))
7681 ((and itemp (not (equal arg '(4))))
7682 ;; Insert an item
7683 (org-insert-item))
7686 ;; Maybe move at the end of the subtree
7687 (when (equal arg '(16))
7688 (org-up-heading-safe)
7689 (org-end-of-subtree t))
7690 ;; Insert a heading
7691 (save-restriction
7692 (widen)
7693 (let* ((level nil)
7694 (on-heading (org-at-heading-p))
7695 (empty-line-p (if on-heading
7696 (org-previous-line-empty-p)
7697 ;; We will decide later
7698 nil))
7699 ;; Get a level string to fall back on
7700 (fix-level
7701 (save-excursion
7702 (org-back-to-heading t)
7703 (if (org-previous-line-empty-p) (setq empty-line-p t))
7704 (looking-at org-outline-regexp)
7705 (make-string (1- (length (match-string 0))) ?*)))
7706 (stars
7707 (save-excursion
7708 (condition-case nil
7709 (progn
7710 (org-back-to-heading invisible-ok)
7711 (when (and (not on-heading)
7712 (featurep 'org-inlinetask)
7713 (integerp org-inlinetask-min-level)
7714 (>= (length (match-string 0))
7715 org-inlinetask-min-level))
7716 ;; Find a heading level before the inline task
7717 (while (and (setq level (org-up-heading-safe))
7718 (>= level org-inlinetask-min-level)))
7719 (if (org-at-heading-p)
7720 (org-back-to-heading invisible-ok)
7721 (error "This should not happen")))
7722 (unless (and (save-excursion
7723 (save-match-data
7724 (org-backward-heading-same-level
7725 1 invisible-ok))
7726 (= (point) (match-beginning 0)))
7727 (not (org-previous-line-empty-p t)))
7728 (setq empty-line-p (or empty-line-p
7729 (org-previous-line-empty-p))))
7730 (match-string 0))
7731 (error (or fix-level "* ")))))
7732 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7733 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7734 pos hide-previous previous-pos)
7736 ;; If we insert after content, move there and clean up whitespace
7737 (when respect-content
7738 (org-end-of-subtree nil t)
7739 (skip-chars-backward " \r\n")
7740 (and (not (looking-back "^\\*+"))
7741 (looking-at "[ \t]+") (replace-match ""))
7742 (unless (eobp) (forward-char 1))
7743 (when (looking-at "^\\*")
7744 (unless (bobp) (backward-char 1))
7745 (insert "\n")))
7747 ;; If we are splitting, grab the text that should be moved to the new headline
7748 (when may-split
7749 (if (org-on-heading-p)
7750 ;; This is a heading, we split intelligently (keeping tags)
7751 (let ((pos (point)))
7752 (goto-char (point-at-bol))
7753 (unless (looking-at org-complex-heading-regexp)
7754 (error "This should not happen"))
7755 (when (and (match-beginning 4)
7756 (> pos (match-beginning 4))
7757 (< pos (match-end 4)))
7758 (setq initial-content (buffer-substring pos (match-end 4)))
7759 (goto-char pos)
7760 (delete-region (point) (match-end 4))
7761 (if (looking-at "[ \t]*$")
7762 (replace-match "")
7763 (insert (make-string (length initial-content) ?\ )))
7764 (setq initial-content (org-trim initial-content)))
7765 (goto-char pos))
7766 ;; a normal line
7767 (unless (bolp)
7768 (setq initial-content (buffer-substring (point) (point-at-eol)))
7769 (delete-region (point) (point-at-eol))
7770 (setq initial-content (org-trim initial-content)))))
7772 ;; If we are at the beginning of the line, insert before it. Else after
7773 (cond
7774 ((and (bolp) (looking-at "[ \t]*$")))
7775 ((and (bolp) (not (looking-at "[ \t]*$")))
7776 (open-line 1))
7778 (goto-char (point-at-eol))
7779 (insert "\n")))
7781 ;; Insert the new heading
7782 (insert stars)
7783 (just-one-space)
7784 (insert initial-content)
7785 (when adjust-empty-lines
7786 (if (or (not blank)
7787 (and blank (not (org-previous-line-empty-p))))
7788 (org-N-empty-lines-before-current (if blank 1 0))))
7789 (run-hooks 'org-insert-heading-hook)))))))
7791 (defun org-N-empty-lines-before-current (N)
7792 "Make the number of empty lines before current exactly N.
7793 So this will delete or add empty lines."
7794 (save-excursion
7795 (goto-char (point-at-bol))
7796 (if (looking-back "\\s-+" nil 'greedy)
7797 (replace-match ""))
7798 (or (bobp) (insert "\n"))
7799 (while (> N 0)
7800 (insert "\n")
7801 (setq N (1- N)))))
7803 (defun org-get-heading (&optional no-tags no-todo)
7804 "Return the heading of the current entry, without the stars.
7805 When NO-TAGS is non-nil, don't include tags.
7806 When NO-TODO is non-nil, don't include TODO keywords."
7807 (save-excursion
7808 (org-back-to-heading t)
7809 (cond
7810 ((and no-tags no-todo)
7811 (looking-at org-complex-heading-regexp)
7812 (match-string 4))
7813 (no-tags
7814 (looking-at (concat org-outline-regexp
7815 "\\(.*?\\)"
7816 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7817 (match-string 1))
7818 (no-todo
7819 (looking-at org-todo-line-regexp)
7820 (match-string 3))
7821 (t (looking-at org-heading-regexp)
7822 (match-string 2)))))
7824 (defvar orgstruct-mode) ; defined below
7826 (defun org-heading-components ()
7827 "Return the components of the current heading.
7828 This is a list with the following elements:
7829 - the level as an integer
7830 - the reduced level, different if `org-odd-levels-only' is set.
7831 - the TODO keyword, or nil
7832 - the priority character, like ?A, or nil if no priority is given
7833 - the headline text itself, or the tags string if no headline text
7834 - the tags string, or nil."
7835 (save-excursion
7836 (org-back-to-heading t)
7837 (if (let (case-fold-search)
7838 (looking-at
7839 (if orgstruct-mode
7840 org-heading-regexp
7841 org-complex-heading-regexp)))
7842 (if orgstruct-mode
7843 (list (length (match-string 1))
7844 (org-reduced-level (length (match-string 1)))
7847 (match-string 2)
7848 nil)
7849 (list (length (match-string 1))
7850 (org-reduced-level (length (match-string 1)))
7851 (org-match-string-no-properties 2)
7852 (and (match-end 3) (aref (match-string 3) 2))
7853 (org-match-string-no-properties 4)
7854 (org-match-string-no-properties 5))))))
7856 (defun org-get-entry ()
7857 "Get the entry text, after heading, entire subtree."
7858 (save-excursion
7859 (org-back-to-heading t)
7860 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7862 (defun org-insert-heading-after-current ()
7863 "Insert a new heading with same level as current, after current subtree."
7864 (interactive)
7865 (org-back-to-heading)
7866 (org-insert-heading)
7867 (org-move-subtree-down)
7868 (end-of-line 1))
7870 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7871 "Insert heading with `org-insert-heading-respect-content' set to t."
7872 (interactive "P")
7873 (let ((org-insert-heading-respect-content t))
7874 (org-insert-heading '(4) invisible-ok)))
7876 (defun org-insert-todo-heading-respect-content (&optional force-state)
7877 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7878 (interactive "P")
7879 (let ((org-insert-heading-respect-content t))
7880 (org-insert-todo-heading force-state '(4))))
7882 (defun org-insert-todo-heading (arg &optional force-heading)
7883 "Insert a new heading with the same level and TODO state as current heading.
7884 If the heading has no TODO state, or if the state is DONE, use the first
7885 state (TODO by default). Also with one prefix arg, force first state. With
7886 two prefix args, force inserting at the end of the parent subtree."
7887 (interactive "P")
7888 (when (or force-heading (not (org-insert-item 'checkbox)))
7889 (org-insert-heading (or (and (equal arg '(16)) '(16))
7890 force-heading))
7891 (save-excursion
7892 (org-back-to-heading)
7893 (outline-previous-heading)
7894 (looking-at org-todo-line-regexp))
7895 (let*
7896 ((new-mark-x
7897 (if (or (equal arg '(4))
7898 (not (match-beginning 2))
7899 (member (match-string 2) org-done-keywords))
7900 (car org-todo-keywords-1)
7901 (match-string 2)))
7902 (new-mark
7904 (run-hook-with-args-until-success
7905 'org-todo-get-default-hook new-mark-x nil)
7906 new-mark-x)))
7907 (beginning-of-line 1)
7908 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7909 (if org-treat-insert-todo-heading-as-state-change
7910 (org-todo new-mark)
7911 (insert new-mark " "))))
7912 (when org-provide-todo-statistics
7913 (org-update-parent-todo-statistics))))
7915 (defun org-insert-subheading (arg)
7916 "Insert a new subheading and demote it.
7917 Works for outline headings and for plain lists alike."
7918 (interactive "P")
7919 (org-insert-heading arg)
7920 (cond
7921 ((org-at-heading-p) (org-do-demote))
7922 ((org-at-item-p) (org-indent-item))))
7924 (defun org-insert-todo-subheading (arg)
7925 "Insert a new subheading with TODO keyword or checkbox and demote it.
7926 Works for outline headings and for plain lists alike."
7927 (interactive "P")
7928 (org-insert-todo-heading arg)
7929 (cond
7930 ((org-at-heading-p) (org-do-demote))
7931 ((org-at-item-p) (org-indent-item))))
7933 ;;; Promotion and Demotion
7935 (defvar org-after-demote-entry-hook nil
7936 "Hook run after an entry has been demoted.
7937 The cursor will be at the beginning of the entry.
7938 When a subtree is being demoted, the hook will be called for each node.")
7940 (defvar org-after-promote-entry-hook nil
7941 "Hook run after an entry has been promoted.
7942 The cursor will be at the beginning of the entry.
7943 When a subtree is being promoted, the hook will be called for each node.")
7945 (defun org-promote-subtree ()
7946 "Promote the entire subtree.
7947 See also `org-promote'."
7948 (interactive)
7949 (save-excursion
7950 (org-with-limited-levels (org-map-tree 'org-promote)))
7951 (org-fix-position-after-promote))
7953 (defun org-demote-subtree ()
7954 "Demote the entire subtree. See `org-demote'.
7955 See also `org-promote'."
7956 (interactive)
7957 (save-excursion
7958 (org-with-limited-levels (org-map-tree 'org-demote)))
7959 (org-fix-position-after-promote))
7962 (defun org-do-promote ()
7963 "Promote the current heading higher up the tree.
7964 If the region is active in `transient-mark-mode', promote all headings
7965 in the region."
7966 (interactive)
7967 (save-excursion
7968 (if (org-region-active-p)
7969 (org-map-region 'org-promote (region-beginning) (region-end))
7970 (org-promote)))
7971 (org-fix-position-after-promote))
7973 (defun org-do-demote ()
7974 "Demote the current heading lower down the tree.
7975 If the region is active in `transient-mark-mode', demote all headings
7976 in the region."
7977 (interactive)
7978 (save-excursion
7979 (if (org-region-active-p)
7980 (org-map-region 'org-demote (region-beginning) (region-end))
7981 (org-demote)))
7982 (org-fix-position-after-promote))
7984 (defun org-fix-position-after-promote ()
7985 "Make sure that after pro/demotion cursor position is right."
7986 (let ((pos (point)))
7987 (when (save-excursion
7988 (beginning-of-line 1)
7989 (looking-at org-todo-line-regexp)
7990 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7991 (cond ((eobp) (insert " "))
7992 ((eolp) (insert " "))
7993 ((equal (char-after) ?\ ) (forward-char 1))))))
7995 (defun org-current-level ()
7996 "Return the level of the current entry, or nil if before the first headline.
7997 The level is the number of stars at the beginning of the headline."
7998 (save-excursion
7999 (org-with-limited-levels
8000 (if (ignore-errors (org-back-to-heading t))
8001 (funcall outline-level)))))
8003 (defun org-get-previous-line-level ()
8004 "Return the outline depth of the last headline before the current line.
8005 Returns 0 for the first headline in the buffer, and nil if before the
8006 first headline."
8007 (and (org-current-level)
8008 (or (and (/= (line-beginning-position) (point-min))
8009 (save-excursion (beginning-of-line 0) (org-current-level)))
8010 0)))
8012 (defun org-reduced-level (l)
8013 "Compute the effective level of a heading.
8014 This takes into account the setting of `org-odd-levels-only'."
8015 (cond
8016 ((zerop l) 0)
8017 (org-odd-levels-only (1+ (floor (/ l 2))))
8018 (t l)))
8020 (defun org-level-increment ()
8021 "Return the number of stars that will be added or removed at a
8022 time to headlines when structure editing, based on the value of
8023 `org-odd-levels-only'."
8024 (if org-odd-levels-only 2 1))
8026 (defun org-get-valid-level (level &optional change)
8027 "Rectify a level change under the influence of `org-odd-levels-only'
8028 LEVEL is a current level, CHANGE is by how much the level should be
8029 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8030 even level numbers will become the next higher odd number."
8031 (if org-odd-levels-only
8032 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8033 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8034 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8035 (max 1 (+ level (or change 0)))))
8037 (if (boundp 'define-obsolete-function-alias)
8038 (if (or (featurep 'xemacs) (< emacs-major-version 23))
8039 (define-obsolete-function-alias 'org-get-legal-level
8040 'org-get-valid-level)
8041 (define-obsolete-function-alias 'org-get-legal-level
8042 'org-get-valid-level "23.1")))
8044 (defun org-promote ()
8045 "Promote the current heading higher up the tree.
8046 If the region is active in `transient-mark-mode', promote all headings
8047 in the region."
8048 (org-back-to-heading t)
8049 (let* ((level (save-match-data (funcall outline-level)))
8050 (after-change-functions (remove 'flyspell-after-change-function
8051 after-change-functions))
8052 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8053 (diff (abs (- level (length up-head) -1))))
8054 (cond ((and (= level 1) org-called-with-limited-levels
8055 org-allow-promoting-top-level-subtree)
8056 (replace-match "# " nil t))
8057 ((= level 1)
8058 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8059 (t (replace-match up-head nil t)))
8060 ;; Fixup tag positioning
8061 (unless (= level 1)
8062 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
8063 (if org-adapt-indentation (org-fixup-indentation (- diff))))
8064 (run-hooks 'org-after-promote-entry-hook)))
8066 (defun org-demote ()
8067 "Demote the current heading lower down the tree.
8068 If the region is active in `transient-mark-mode', demote all headings
8069 in the region."
8070 (org-back-to-heading t)
8071 (let* ((level (save-match-data (funcall outline-level)))
8072 (after-change-functions (remove 'flyspell-after-change-function
8073 after-change-functions))
8074 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8075 (diff (abs (- level (length down-head) -1))))
8076 (replace-match down-head nil t)
8077 ;; Fixup tag positioning
8078 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
8079 (if org-adapt-indentation (org-fixup-indentation diff))
8080 (run-hooks 'org-after-demote-entry-hook)))
8082 (defun org-cycle-level ()
8083 "Cycle the level of an empty headline through possible states.
8084 This goes first to child, then to parent, level, then up the hierarchy.
8085 After top level, it switches back to sibling level."
8086 (interactive)
8087 (let ((org-adapt-indentation nil))
8088 (when (org-point-at-end-of-empty-headline)
8089 (setq this-command 'org-cycle-level) ; Only needed for caching
8090 (let ((cur-level (org-current-level))
8091 (prev-level (org-get-previous-line-level)))
8092 (cond
8093 ;; If first headline in file, promote to top-level.
8094 ((= prev-level 0)
8095 (loop repeat (/ (- cur-level 1) (org-level-increment))
8096 do (org-do-promote)))
8097 ;; If same level as prev, demote one.
8098 ((= prev-level cur-level)
8099 (org-do-demote))
8100 ;; If parent is top-level, promote to top level if not already.
8101 ((= prev-level 1)
8102 (loop repeat (/ (- cur-level 1) (org-level-increment))
8103 do (org-do-promote)))
8104 ;; If top-level, return to prev-level.
8105 ((= cur-level 1)
8106 (loop repeat (/ (- prev-level 1) (org-level-increment))
8107 do (org-do-demote)))
8108 ;; If less than prev-level, promote one.
8109 ((< cur-level prev-level)
8110 (org-do-promote))
8111 ;; If deeper than prev-level, promote until higher than
8112 ;; prev-level.
8113 ((> cur-level prev-level)
8114 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8115 do (org-do-promote))))
8116 t))))
8118 (defun org-map-tree (fun)
8119 "Call FUN for every heading underneath the current one."
8120 (org-back-to-heading)
8121 (let ((level (funcall outline-level)))
8122 (save-excursion
8123 (funcall fun)
8124 (while (and (progn
8125 (outline-next-heading)
8126 (> (funcall outline-level) level))
8127 (not (eobp)))
8128 (funcall fun)))))
8130 (defun org-map-region (fun beg end)
8131 "Call FUN for every heading between BEG and END."
8132 (let ((org-ignore-region t))
8133 (save-excursion
8134 (setq end (copy-marker end))
8135 (goto-char beg)
8136 (if (and (re-search-forward org-outline-regexp-bol nil t)
8137 (< (point) end))
8138 (funcall fun))
8139 (while (and (progn
8140 (outline-next-heading)
8141 (< (point) end))
8142 (not (eobp)))
8143 (funcall fun)))))
8145 (defvar org-property-end-re) ; silence byte-compiler
8146 (defun org-fixup-indentation (diff)
8147 "Change the indentation in the current entry by DIFF.
8148 However, if any line in the current entry has no indentation, or if it
8149 would end up with no indentation after the change, nothing at all is done."
8150 (save-excursion
8151 (let ((end (save-excursion (outline-next-heading)
8152 (point-marker)))
8153 (prohibit (if (> diff 0)
8154 "^\\S-"
8155 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8156 col)
8157 (unless (save-excursion (end-of-line 1)
8158 (re-search-forward prohibit end t))
8159 (while (and (< (point) end)
8160 (re-search-forward "^[ \t]+" end t))
8161 (goto-char (match-end 0))
8162 (setq col (current-column))
8163 (if (< diff 0) (replace-match ""))
8164 (org-indent-to-column (+ diff col))))
8165 (move-marker end nil))))
8167 (defun org-convert-to-odd-levels ()
8168 "Convert an org-mode file with all levels allowed to one with odd levels.
8169 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8170 level 5 etc."
8171 (interactive)
8172 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8173 (let ((outline-level 'org-outline-level)
8174 (org-odd-levels-only nil) n)
8175 (save-excursion
8176 (goto-char (point-min))
8177 (while (re-search-forward "^\\*\\*+ " nil t)
8178 (setq n (- (length (match-string 0)) 2))
8179 (while (>= (setq n (1- n)) 0)
8180 (org-demote))
8181 (end-of-line 1))))))
8183 (defun org-convert-to-oddeven-levels ()
8184 "Convert an org-mode file with only odd levels to one with odd/even levels.
8185 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8186 file contains a section with an even level, conversion would
8187 destroy the structure of the file. An error is signaled in this
8188 case."
8189 (interactive)
8190 (goto-char (point-min))
8191 ;; First check if there are no even levels
8192 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8193 (org-show-context t)
8194 (error "Not all levels are odd in this file. Conversion not possible"))
8195 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8196 (let ((outline-regexp org-outline-regexp)
8197 (outline-level 'org-outline-level)
8198 (org-odd-levels-only nil) n)
8199 (save-excursion
8200 (goto-char (point-min))
8201 (while (re-search-forward "^\\*\\*+ " nil t)
8202 (setq n (/ (1- (length (match-string 0))) 2))
8203 (while (>= (setq n (1- n)) 0)
8204 (org-promote))
8205 (end-of-line 1))))))
8207 (defun org-tr-level (n)
8208 "Make N odd if required."
8209 (if org-odd-levels-only (1+ (/ n 2)) n))
8211 ;;; Vertical tree motion, cutting and pasting of subtrees
8213 (defun org-move-subtree-up (&optional arg)
8214 "Move the current subtree up past ARG headlines of the same level."
8215 (interactive "p")
8216 (org-move-subtree-down (- (prefix-numeric-value arg))))
8218 (defun org-move-subtree-down (&optional arg)
8219 "Move the current subtree down past ARG headlines of the same level."
8220 (interactive "p")
8221 (setq arg (prefix-numeric-value arg))
8222 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8223 'org-get-last-sibling))
8224 (ins-point (make-marker))
8225 (cnt (abs arg))
8226 (col (current-column))
8227 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8228 ;; Select the tree
8229 (org-back-to-heading)
8230 (setq beg0 (point))
8231 (save-excursion
8232 (setq ne-beg (org-back-over-empty-lines))
8233 (setq beg (point)))
8234 (save-match-data
8235 (save-excursion (outline-end-of-heading)
8236 (setq folded (outline-invisible-p)))
8237 (outline-end-of-subtree))
8238 (outline-next-heading)
8239 (setq ne-end (org-back-over-empty-lines))
8240 (setq end (point))
8241 (goto-char beg0)
8242 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8243 ;; include less whitespace
8244 (save-excursion
8245 (goto-char beg)
8246 (forward-line (- ne-beg ne-end))
8247 (setq beg (point))))
8248 ;; Find insertion point, with error handling
8249 (while (> cnt 0)
8250 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8251 (progn (goto-char beg0)
8252 (user-error "Cannot move past superior level or buffer limit")))
8253 (setq cnt (1- cnt)))
8254 (if (> arg 0)
8255 ;; Moving forward - still need to move over subtree
8256 (progn (org-end-of-subtree t t)
8257 (save-excursion
8258 (org-back-over-empty-lines)
8259 (or (bolp) (newline)))))
8260 (setq ne-ins (org-back-over-empty-lines))
8261 (move-marker ins-point (point))
8262 (setq txt (buffer-substring beg end))
8263 (org-save-markers-in-region beg end)
8264 (delete-region beg end)
8265 (org-remove-empty-overlays-at beg)
8266 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8267 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8268 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8269 (let ((bbb (point)))
8270 (insert-before-markers txt)
8271 (org-reinstall-markers-in-region bbb)
8272 (move-marker ins-point bbb))
8273 (or (bolp) (insert "\n"))
8274 (setq ins-end (point))
8275 (goto-char ins-point)
8276 (org-skip-whitespace)
8277 (when (and (< arg 0)
8278 (org-first-sibling-p)
8279 (> ne-ins ne-beg))
8280 ;; Move whitespace back to beginning
8281 (save-excursion
8282 (goto-char ins-end)
8283 (let ((kill-whole-line t))
8284 (kill-line (- ne-ins ne-beg)) (point)))
8285 (insert (make-string (- ne-ins ne-beg) ?\n)))
8286 (move-marker ins-point nil)
8287 (if folded
8288 (hide-subtree)
8289 (org-show-entry)
8290 (show-children)
8291 (org-cycle-hide-drawers 'children))
8292 (org-clean-visibility-after-subtree-move)
8293 ;; move back to the initial column we were at
8294 (move-to-column col)))
8296 (defvar org-subtree-clip ""
8297 "Clipboard for cut and paste of subtrees.
8298 This is actually only a copy of the kill, because we use the normal kill
8299 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8301 (defvar org-subtree-clip-folded nil
8302 "Was the last copied subtree folded?
8303 This is used to fold the tree back after pasting.")
8305 (defun org-cut-subtree (&optional n)
8306 "Cut the current subtree into the clipboard.
8307 With prefix arg N, cut this many sequential subtrees.
8308 This is a short-hand for marking the subtree and then cutting it."
8309 (interactive "p")
8310 (org-copy-subtree n 'cut))
8312 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8313 "Copy the current subtree it in the clipboard.
8314 With prefix arg N, copy this many sequential subtrees.
8315 This is a short-hand for marking the subtree and then copying it.
8316 If CUT is non-nil, actually cut the subtree.
8317 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8318 of some markers in the region, even if CUT is non-nil. This is
8319 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8320 (interactive "p")
8321 (let (beg end folded (beg0 (point)))
8322 (if (org-called-interactively-p 'any)
8323 (org-back-to-heading nil) ; take what looks like a subtree
8324 (org-back-to-heading t)) ; take what is really there
8325 (setq beg (point))
8326 (skip-chars-forward " \t\r\n")
8327 (save-match-data
8328 (if nosubtrees
8329 (outline-next-heading)
8330 (save-excursion (outline-end-of-heading)
8331 (setq folded (outline-invisible-p)))
8332 (condition-case nil
8333 (org-forward-heading-same-level (1- n) t)
8334 (error nil))
8335 (org-end-of-subtree t t)))
8336 (setq end (point))
8337 (goto-char beg0)
8338 (when (> end beg)
8339 (setq org-subtree-clip-folded folded)
8340 (when (or cut force-store-markers)
8341 (org-save-markers-in-region beg end))
8342 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8343 (setq org-subtree-clip (current-kill 0))
8344 (message "%s: Subtree(s) with %d characters"
8345 (if cut "Cut" "Copied")
8346 (length org-subtree-clip)))))
8348 (defun org-paste-subtree (&optional level tree for-yank)
8349 "Paste the clipboard as a subtree, with modification of headline level.
8350 The entire subtree is promoted or demoted in order to match a new headline
8351 level.
8353 If the cursor is at the beginning of a headline, the same level as
8354 that headline is used to paste the tree.
8356 If not, the new level is derived from the *visible* headings
8357 before and after the insertion point, and taken to be the inferior headline
8358 level of the two. So if the previous visible heading is level 3 and the
8359 next is level 4 (or vice versa), level 4 will be used for insertion.
8360 This makes sure that the subtree remains an independent subtree and does
8361 not swallow low level entries.
8363 You can also force a different level, either by using a numeric prefix
8364 argument, or by inserting the heading marker by hand. For example, if the
8365 cursor is after \"*****\", then the tree will be shifted to level 5.
8367 If optional TREE is given, use this text instead of the kill ring.
8369 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8370 move back over whitespace before inserting, and move point to the end of
8371 the inserted text when done."
8372 (interactive "P")
8373 (setq tree (or tree (and kill-ring (current-kill 0))))
8374 (unless (org-kill-is-subtree-p tree)
8375 (user-error "%s"
8376 (substitute-command-keys
8377 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8378 (org-with-limited-levels
8379 (let* ((visp (not (outline-invisible-p)))
8380 (txt tree)
8381 (^re_ "\\(\\*+\\)[ \t]*")
8382 (old-level (if (string-match org-outline-regexp-bol txt)
8383 (- (match-end 0) (match-beginning 0) 1)
8384 -1))
8385 (force-level (cond (level (prefix-numeric-value level))
8386 ((and (looking-at "[ \t]*$")
8387 (string-match
8388 "^\\*+$" (buffer-substring
8389 (point-at-bol) (point))))
8390 (- (match-end 1) (match-beginning 1)))
8391 ((and (bolp)
8392 (looking-at org-outline-regexp))
8393 (- (match-end 0) (point) 1))))
8394 (previous-level (save-excursion
8395 (condition-case nil
8396 (progn
8397 (outline-previous-visible-heading 1)
8398 (if (looking-at ^re_)
8399 (- (match-end 0) (match-beginning 0) 1)
8401 (error 1))))
8402 (next-level (save-excursion
8403 (condition-case nil
8404 (progn
8405 (or (looking-at org-outline-regexp)
8406 (outline-next-visible-heading 1))
8407 (if (looking-at ^re_)
8408 (- (match-end 0) (match-beginning 0) 1)
8410 (error 1))))
8411 (new-level (or force-level (max previous-level next-level)))
8412 (shift (if (or (= old-level -1)
8413 (= new-level -1)
8414 (= old-level new-level))
8416 (- new-level old-level)))
8417 (delta (if (> shift 0) -1 1))
8418 (func (if (> shift 0) 'org-demote 'org-promote))
8419 (org-odd-levels-only nil)
8420 beg end newend)
8421 ;; Remove the forced level indicator
8422 (if force-level
8423 (delete-region (point-at-bol) (point)))
8424 ;; Paste
8425 (beginning-of-line (if (bolp) 1 2))
8426 (setq beg (point))
8427 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8428 (insert-before-markers txt)
8429 (unless (string-match "\n\\'" txt) (insert "\n"))
8430 (setq newend (point))
8431 (org-reinstall-markers-in-region beg)
8432 (setq end (point))
8433 (goto-char beg)
8434 (skip-chars-forward " \t\n\r")
8435 (setq beg (point))
8436 (if (and (outline-invisible-p) visp)
8437 (save-excursion (outline-show-heading)))
8438 ;; Shift if necessary
8439 (unless (= shift 0)
8440 (save-restriction
8441 (narrow-to-region beg end)
8442 (while (not (= shift 0))
8443 (org-map-region func (point-min) (point-max))
8444 (setq shift (+ delta shift)))
8445 (goto-char (point-min))
8446 (setq newend (point-max))))
8447 (when (or (org-called-interactively-p 'interactive) for-yank)
8448 (message "Clipboard pasted as level %d subtree" new-level))
8449 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8450 kill-ring
8451 (eq org-subtree-clip (current-kill 0))
8452 org-subtree-clip-folded)
8453 ;; The tree was folded before it was killed/copied
8454 (hide-subtree))
8455 (and for-yank (goto-char newend)))))
8457 (defun org-kill-is-subtree-p (&optional txt)
8458 "Check if the current kill is an outline subtree, or a set of trees.
8459 Returns nil if kill does not start with a headline, or if the first
8460 headline level is not the largest headline level in the tree.
8461 So this will actually accept several entries of equal levels as well,
8462 which is OK for `org-paste-subtree'.
8463 If optional TXT is given, check this string instead of the current kill."
8464 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8465 (re (org-get-limited-outline-regexp))
8466 (^re (concat "^" re))
8467 (start-level (and kill
8468 (string-match
8469 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8470 kill)
8471 (- (match-end 2) (match-beginning 2) 1)))
8472 (start (1+ (or (match-beginning 2) -1))))
8473 (if (not start-level)
8474 (progn
8475 nil) ;; does not even start with a heading
8476 (catch 'exit
8477 (while (setq start (string-match ^re kill (1+ start)))
8478 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8479 (throw 'exit nil)))
8480 t))))
8482 (defvar org-markers-to-move nil
8483 "Markers that should be moved with a cut-and-paste operation.
8484 Those markers are stored together with their positions relative to
8485 the start of the region.")
8487 (defun org-save-markers-in-region (beg end)
8488 "Check markers in region.
8489 If these markers are between BEG and END, record their position relative
8490 to BEG, so that after moving the block of text, we can put the markers back
8491 into place.
8492 This function gets called just before an entry or tree gets cut from the
8493 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8494 called immediately, to move the markers with the entries."
8495 (setq org-markers-to-move nil)
8496 (when (featurep 'org-clock)
8497 (org-clock-save-markers-for-cut-and-paste beg end))
8498 (when (featurep 'org-agenda)
8499 (org-agenda-save-markers-for-cut-and-paste beg end)))
8501 (defun org-check-and-save-marker (marker beg end)
8502 "Check if MARKER is between BEG and END.
8503 If yes, remember the marker and the distance to BEG."
8504 (when (and (marker-buffer marker)
8505 (equal (marker-buffer marker) (current-buffer)))
8506 (if (and (>= marker beg) (< marker end))
8507 (push (cons marker (- marker beg)) org-markers-to-move))))
8509 (defun org-reinstall-markers-in-region (beg)
8510 "Move all remembered markers to their position relative to BEG."
8511 (mapc (lambda (x)
8512 (move-marker (car x) (+ beg (cdr x))))
8513 org-markers-to-move)
8514 (setq org-markers-to-move nil))
8516 (defun org-narrow-to-subtree ()
8517 "Narrow buffer to the current subtree."
8518 (interactive)
8519 (save-excursion
8520 (save-match-data
8521 (org-with-limited-levels
8522 (narrow-to-region
8523 (progn (org-back-to-heading t) (point))
8524 (progn (org-end-of-subtree t t)
8525 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8526 (point)))))))
8528 (defun org-narrow-to-block ()
8529 "Narrow buffer to the current block."
8530 (interactive)
8531 (let* ((case-fold-search t)
8532 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8533 "^[ \t]*#\\+end_.*")))
8534 (if blockp
8535 (narrow-to-region (car blockp) (cdr blockp))
8536 (user-error "Not in a block"))))
8538 (eval-when-compile
8539 (defvar org-property-drawer-re))
8541 (defvar org-property-start-re) ;; defined below
8542 (defun org-clone-subtree-with-time-shift (n &optional shift)
8543 "Clone the task (subtree) at point N times.
8544 The clones will be inserted as siblings.
8546 In interactive use, the user will be prompted for the number of
8547 clones to be produced. If the entry has a timestamp, the user
8548 will also be prompted for a time shift, which may be a repeater
8549 as used in time stamps, for example `+3d'. To disable this,
8550 you can call the function with a universal prefix argument.
8552 When a valid repeater is given and the entry contains any time
8553 stamps, the clones will become a sequence in time, with time
8554 stamps in the subtree shifted for each clone produced. If SHIFT
8555 is nil or the empty string, time stamps will be left alone. The
8556 ID property of the original subtree is removed.
8558 If the original subtree did contain time stamps with a repeater,
8559 the following will happen:
8560 - the repeater will be removed in each clone
8561 - an additional clone will be produced, with the current, unshifted
8562 date(s) in the entry.
8563 - the original entry will be placed *after* all the clones, with
8564 repeater intact.
8565 - the start days in the repeater in the original entry will be shifted
8566 to past the last clone.
8567 In this way you can spell out a number of instances of a repeating task,
8568 and still retain the repeater to cover future instances of the task."
8569 (interactive "nNumber of clones to produce: ")
8570 (let ((shift
8571 (or shift
8572 (if (and (not (equal current-prefix-arg '(4)))
8573 (save-excursion
8574 (re-search-forward org-ts-regexp-both
8575 (save-excursion
8576 (org-end-of-subtree t)
8577 (point)) t)))
8578 (read-from-minibuffer
8579 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8580 ""))) ;; No time shift
8581 (n-no-remove -1)
8582 (drawer-re org-drawer-regexp)
8583 beg end template task idprop
8584 shift-n shift-what doshift nmin nmax)
8585 (if (not (and (integerp n) (> n 0)))
8586 (error "Invalid number of replications %s" n))
8587 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8588 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8589 shift)))
8590 (error "Invalid shift specification %s" shift))
8591 (when doshift
8592 (setq shift-n (string-to-number (match-string 1 shift))
8593 shift-what (cdr (assoc (match-string 2 shift)
8594 '(("d" . day) ("w" . week)
8595 ("m" . month) ("y" . year))))))
8596 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8597 (setq nmin 1 nmax n)
8598 (org-back-to-heading t)
8599 (setq beg (point))
8600 (setq idprop (org-entry-get nil "ID"))
8601 (org-end-of-subtree t t)
8602 (or (bolp) (insert "\n"))
8603 (setq end (point))
8604 (setq template (buffer-substring beg end))
8605 (when (and doshift
8606 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8607 (delete-region beg end)
8608 (setq end beg)
8609 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8610 (goto-char end)
8611 (loop for n from nmin to nmax do
8612 ;; prepare clone
8613 (with-temp-buffer
8614 (insert template)
8615 (org-mode)
8616 (goto-char (point-min))
8617 (org-show-subtree)
8618 (and idprop (if org-clone-delete-id
8619 (org-entry-delete nil "ID")
8620 (org-id-get-create t)))
8621 (unless (= n 0)
8622 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8623 (kill-whole-line))
8624 (goto-char (point-min))
8625 (while (re-search-forward drawer-re nil t)
8626 (org-remove-empty-drawer-at (point))))
8627 (goto-char (point-min))
8628 (when doshift
8629 (while (re-search-forward org-ts-regexp-both nil t)
8630 (org-timestamp-change (* n shift-n) shift-what))
8631 (unless (= n n-no-remove)
8632 (goto-char (point-min))
8633 (while (re-search-forward org-ts-regexp nil t)
8634 (save-excursion
8635 (goto-char (match-beginning 0))
8636 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8637 (delete-region (match-beginning 1) (match-end 1)))))))
8638 (setq task (buffer-string)))
8639 (insert task))
8640 (goto-char beg)))
8642 ;;; Outline Sorting
8644 (defun org-sort (with-case)
8645 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8646 Optional argument WITH-CASE means sort case-sensitively."
8647 (interactive "P")
8648 (cond
8649 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8650 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8652 (org-call-with-arg 'org-sort-entries with-case))))
8654 (defun org-sort-remove-invisible (s)
8655 "Remove invisible links from string S."
8656 (remove-text-properties 0 (length s) org-rm-props s)
8657 (while (string-match org-bracket-link-regexp s)
8658 (setq s (replace-match (if (match-end 2)
8659 (match-string 3 s)
8660 (match-string 1 s)) t t s)))
8661 (let ((st (format " %s " s)))
8662 (while (string-match org-emph-re st)
8663 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8664 (setq s (substring st 1 -1)))
8667 (defvar org-priority-regexp) ; defined later in the file
8669 (defvar org-after-sorting-entries-or-items-hook nil
8670 "Hook that is run after a bunch of entries or items have been sorted.
8671 When children are sorted, the cursor is in the parent line when this
8672 hook gets called. When a region or a plain list is sorted, the cursor
8673 will be in the first entry of the sorted region/list.")
8675 (defun org-sort-entries
8676 (&optional with-case sorting-type getkey-func compare-func property)
8677 "Sort entries on a certain level of an outline tree.
8678 If there is an active region, the entries in the region are sorted.
8679 Else, if the cursor is before the first entry, sort the top-level items.
8680 Else, the children of the entry at point are sorted.
8682 Sorting can be alphabetically, numerically, by date/time as given by
8683 a time stamp, by a property, by priority order, or by a custom function.
8685 The command prompts for the sorting type unless it has been given to the
8686 function through the SORTING-TYPE argument, which needs to be a character,
8687 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8688 the precise meaning of each character:
8690 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8691 c By creation time, which is assumed to be the first inactive time stamp
8692 at the beginning of a line.
8693 d By deadline date/time.
8694 k By clocking time.
8695 n Numerically, by converting the beginning of the entry/item to a number.
8696 o By order of TODO keywords.
8697 p By priority according to the cookie.
8698 r By the value of a property.
8699 s By scheduled date/time.
8700 t By date/time, either the first active time stamp in the entry, or, if
8701 none exist, by the first inactive one.
8703 Capital letters will reverse the sort order.
8705 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8706 called with point at the beginning of the record. It must return either
8707 a string or a number that should serve as the sorting key for that record.
8709 Comparing entries ignores case by default. However, with an optional argument
8710 WITH-CASE, the sorting considers case as well.
8712 Sorting is done against the visible part of the headlines, it ignores hidden
8713 links.
8715 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
8716 (interactive "P")
8717 (let ((case-func (if with-case 'identity 'downcase))
8718 (cmstr
8719 ;; The clock marker is lost when using `sort-subr', let's
8720 ;; store the clocking string.
8721 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8722 (save-excursion
8723 (goto-char org-clock-marker)
8724 (looking-back "^.*") (match-string-no-properties 0))))
8725 start beg end stars re re2
8726 txt what tmp)
8727 ;; Find beginning and end of region to sort
8728 (cond
8729 ((org-region-active-p)
8730 ;; we will sort the region
8731 (setq end (region-end)
8732 what "region")
8733 (goto-char (region-beginning))
8734 (if (not (org-at-heading-p)) (outline-next-heading))
8735 (setq start (point)))
8736 ((or (org-at-heading-p)
8737 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8738 ;; we will sort the children of the current headline
8739 (org-back-to-heading)
8740 (setq start (point)
8741 end (progn (org-end-of-subtree t t)
8742 (or (bolp) (insert "\n"))
8743 (org-back-over-empty-lines)
8744 (point))
8745 what "children")
8746 (goto-char start)
8747 (show-subtree)
8748 (outline-next-heading))
8750 ;; we will sort the top-level entries in this file
8751 (goto-char (point-min))
8752 (or (org-at-heading-p) (outline-next-heading))
8753 (setq start (point))
8754 (goto-char (point-max))
8755 (beginning-of-line 1)
8756 (when (looking-at ".*?\\S-")
8757 ;; File ends in a non-white line
8758 (end-of-line 1)
8759 (insert "\n"))
8760 (setq end (point-max))
8761 (setq what "top-level")
8762 (goto-char start)
8763 (show-all)))
8765 (setq beg (point))
8766 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8768 (looking-at "\\(\\*+\\)")
8769 (setq stars (match-string 1)
8770 re (concat "^" (regexp-quote stars) " +")
8771 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8772 txt (buffer-substring beg end))
8773 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8774 (if (and (not (equal stars "*")) (string-match re2 txt))
8775 (user-error "Region to sort contains a level above the first entry"))
8777 (unless sorting-type
8778 (message
8779 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8780 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8781 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8782 what)
8783 (setq sorting-type (read-char-exclusive))
8785 (unless getkey-func
8786 (and (= (downcase sorting-type) ?f)
8787 (setq getkey-func
8788 (org-icompleting-read "Sort using function: "
8789 obarray 'fboundp t nil nil))
8790 (setq getkey-func (intern getkey-func))))
8792 (and (= (downcase sorting-type) ?r)
8793 (not property)
8794 (setq property
8795 (org-icompleting-read "Property: "
8796 (mapcar 'list (org-buffer-property-keys t))
8797 nil t))))
8799 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8800 (message "Sorting entries...")
8802 (save-restriction
8803 (narrow-to-region start end)
8804 (let ((dcst (downcase sorting-type))
8805 (case-fold-search nil)
8806 (now (current-time)))
8807 (sort-subr
8808 (/= dcst sorting-type)
8809 ;; This function moves to the beginning character of the "record" to
8810 ;; be sorted.
8811 (lambda nil
8812 (if (re-search-forward re nil t)
8813 (goto-char (match-beginning 0))
8814 (goto-char (point-max))))
8815 ;; This function moves to the last character of the "record" being
8816 ;; sorted.
8817 (lambda nil
8818 (save-match-data
8819 (condition-case nil
8820 (outline-forward-same-level 1)
8821 (error
8822 (goto-char (point-max))))))
8823 ;; This function returns the value that gets sorted against.
8824 (lambda nil
8825 (cond
8826 ((= dcst ?n)
8827 (if (looking-at org-complex-heading-regexp)
8828 (string-to-number (org-sort-remove-invisible (match-string 4)))
8829 nil))
8830 ((= dcst ?a)
8831 (if (looking-at org-complex-heading-regexp)
8832 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8833 nil))
8834 ((= dcst ?k)
8835 (get-text-property (point) :org-clock-minutes))
8836 ((= dcst ?t)
8837 (let ((end (save-excursion (outline-next-heading) (point))))
8838 (if (or (re-search-forward org-ts-regexp end t)
8839 (re-search-forward org-ts-regexp-both end t))
8840 (org-time-string-to-seconds (match-string 0))
8841 (org-float-time now))))
8842 ((= dcst ?c)
8843 (let ((end (save-excursion (outline-next-heading) (point))))
8844 (if (re-search-forward
8845 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8846 end t)
8847 (org-time-string-to-seconds (match-string 0))
8848 (org-float-time now))))
8849 ((= dcst ?s)
8850 (let ((end (save-excursion (outline-next-heading) (point))))
8851 (if (re-search-forward org-scheduled-time-regexp end t)
8852 (org-time-string-to-seconds (match-string 1))
8853 (org-float-time now))))
8854 ((= dcst ?d)
8855 (let ((end (save-excursion (outline-next-heading) (point))))
8856 (if (re-search-forward org-deadline-time-regexp end t)
8857 (org-time-string-to-seconds (match-string 1))
8858 (org-float-time now))))
8859 ((= dcst ?p)
8860 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8861 (string-to-char (match-string 2))
8862 org-default-priority))
8863 ((= dcst ?r)
8864 (or (org-entry-get nil property) ""))
8865 ((= dcst ?o)
8866 (if (looking-at org-complex-heading-regexp)
8867 (- 9999 (length (member (match-string 2)
8868 org-todo-keywords-1)))))
8869 ((= dcst ?f)
8870 (if getkey-func
8871 (progn
8872 (setq tmp (funcall getkey-func))
8873 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8874 tmp)
8875 (error "Invalid key function `%s'" getkey-func)))
8876 (t (error "Invalid sorting type `%c'" sorting-type))))
8878 (cond
8879 ((= dcst ?a) 'string<)
8880 ((= dcst ?f) compare-func)
8881 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8882 (run-hooks 'org-after-sorting-entries-or-items-hook)
8883 ;; Reset the clock marker if needed
8884 (when cmstr
8885 (save-excursion
8886 (goto-char start)
8887 (search-forward cmstr nil t)
8888 (move-marker org-clock-marker (point))))
8889 (message "Sorting entries...done")))
8891 (defun org-do-sort (table what &optional with-case sorting-type)
8892 "Sort TABLE of WHAT according to SORTING-TYPE.
8893 The user will be prompted for the SORTING-TYPE if the call to this
8894 function does not specify it.
8895 WHAT is only for the prompt, to indicate what is being sorted.
8896 The sorting key will be extracted from the car of the elements of
8897 the table.
8898 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8899 (unless sorting-type
8900 (message
8901 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8902 what)
8903 (setq sorting-type (read-char-exclusive)))
8904 (let ((dcst (downcase sorting-type))
8905 extractfun comparefun)
8906 ;; Define the appropriate functions
8907 (cond
8908 ((= dcst ?n)
8909 (setq extractfun 'string-to-number
8910 comparefun (if (= dcst sorting-type) '< '>)))
8911 ((= dcst ?a)
8912 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8913 (lambda(x) (downcase (org-sort-remove-invisible x))))
8914 comparefun (if (= dcst sorting-type)
8915 'string<
8916 (lambda (a b) (and (not (string< a b))
8917 (not (string= a b)))))))
8918 ((= dcst ?t)
8919 (setq extractfun
8920 (lambda (x)
8921 (cond ((or (string-match org-ts-regexp x)
8922 (string-match org-ts-regexp-both x))
8923 (org-float-time
8924 (org-time-string-to-time (match-string 0 x))))
8925 ((string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" x)
8926 (org-hh:mm-string-to-minutes x))
8927 (t 0)))
8928 comparefun (if (= dcst sorting-type) '< '>)))
8929 (t (error "Invalid sorting type `%c'" sorting-type)))
8931 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8932 table)
8933 (lambda (a b) (funcall comparefun (car a) (car b))))))
8936 ;;; The orgstruct minor mode
8938 ;; Define a minor mode which can be used in other modes in order to
8939 ;; integrate the org-mode structure editing commands.
8941 ;; This is really a hack, because the org-mode structure commands use
8942 ;; keys which normally belong to the major mode. Here is how it
8943 ;; works: The minor mode defines all the keys necessary to operate the
8944 ;; structure commands, but wraps the commands into a function which
8945 ;; tests if the cursor is currently at a headline or a plain list
8946 ;; item. If that is the case, the structure command is used,
8947 ;; temporarily setting many Org-mode variables like regular
8948 ;; expressions for filling etc. However, when any of those keys is
8949 ;; used at a different location, function uses `key-binding' to look
8950 ;; up if the key has an associated command in another currently active
8951 ;; keymap (minor modes, major mode, global), and executes that
8952 ;; command. There might be problems if any of the keys is otherwise
8953 ;; used as a prefix key.
8955 (defcustom orgstruct-heading-prefix-regexp ""
8956 "Regexp that matches the custom prefix of Org headlines in
8957 orgstruct(++)-mode."
8958 :group 'org
8959 :version "24.4"
8960 :package-version '(Org . "8.3")
8961 :type 'regexp)
8962 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8964 (defcustom orgstruct-setup-hook nil
8965 "Hook run after orgstruct-mode-map is filled."
8966 :group 'org
8967 :version "24.4"
8968 :package-version '(Org . "8.0")
8969 :type 'hook)
8971 (defvar orgstruct-initialized nil)
8973 (defvar org-local-vars nil
8974 "List of local variables, for use by `orgstruct-mode'.")
8976 ;;;###autoload
8977 (define-minor-mode orgstruct-mode
8978 "Toggle the minor mode `orgstruct-mode'.
8979 This mode is for using Org-mode structure commands in other
8980 modes. The following keys behave as if Org-mode were active, if
8981 the cursor is on a headline, or on a plain list item (both as
8982 defined by Org-mode)."
8983 nil " OrgStruct" (make-sparse-keymap)
8984 (funcall (if orgstruct-mode
8985 'add-to-invisibility-spec
8986 'remove-from-invisibility-spec)
8987 '(outline . t))
8988 (when orgstruct-mode
8989 (org-load-modules-maybe)
8990 (unless orgstruct-initialized
8991 (orgstruct-setup)
8992 (setq orgstruct-initialized t))))
8994 ;;;###autoload
8995 (defun turn-on-orgstruct ()
8996 "Unconditionally turn on `orgstruct-mode'."
8997 (orgstruct-mode 1))
8999 (defvar org-fb-vars nil)
9000 (make-variable-buffer-local 'org-fb-vars)
9001 (defun orgstruct++-mode (&optional arg)
9002 "Toggle `orgstruct-mode', the enhanced version of it.
9003 In addition to setting orgstruct-mode, this also exports all
9004 indentation and autofilling variables from org-mode into the
9005 buffer. It will also recognize item context in multiline items."
9006 (interactive "P")
9007 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9008 (if (< arg 1)
9009 (progn (orgstruct-mode -1)
9010 (mapc (lambda(v)
9011 (org-set-local (car v)
9012 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
9013 org-fb-vars))
9014 (orgstruct-mode 1)
9015 (setq org-fb-vars nil)
9016 (unless org-local-vars
9017 (setq org-local-vars (org-get-local-variables)))
9018 (let (var val)
9019 (mapc
9020 (lambda (x)
9021 (when (string-match
9022 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
9023 (symbol-name (car x)))
9024 (setq var (car x) val (nth 1 x))
9025 (push (list var `(quote ,(eval var))) org-fb-vars)
9026 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9027 org-local-vars)
9028 (org-set-local 'orgstruct-is-++ t))))
9030 (defvar orgstruct-is-++ nil
9031 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9032 (make-variable-buffer-local 'orgstruct-is-++)
9034 ;;;###autoload
9035 (defun turn-on-orgstruct++ ()
9036 "Unconditionally turn on `orgstruct++-mode'."
9037 (orgstruct++-mode 1))
9039 (defun orgstruct-error ()
9040 "Error when there is no default binding for a structure key."
9041 (interactive)
9042 (funcall (if (fboundp 'user-error)
9043 'user-error
9044 'error)
9045 "This key has no function outside structure elements"))
9047 (defun orgstruct-setup ()
9048 "Setup orgstruct keymap."
9049 (dolist (cell '((org-demote . t)
9050 (org-metaleft . t)
9051 (org-metaright . t)
9052 (org-promote . t)
9053 (org-shiftmetaleft . t)
9054 (org-shiftmetaright . t)
9055 org-backward-element
9056 org-backward-heading-same-level
9057 org-ctrl-c-ret
9058 org-ctrl-c-minus
9059 org-ctrl-c-star
9060 org-cycle
9061 org-forward-heading-same-level
9062 org-insert-heading
9063 org-insert-heading-respect-content
9064 org-kill-note-or-show-branches
9065 org-mark-subtree
9066 org-meta-return
9067 org-metadown
9068 org-metaup
9069 org-narrow-to-subtree
9070 org-promote-subtree
9071 org-reveal
9072 org-shiftdown
9073 org-shiftleft
9074 org-shiftmetadown
9075 org-shiftmetaup
9076 org-shiftright
9077 org-shifttab
9078 org-shifttab
9079 org-shiftup
9080 org-show-subtree
9081 org-sort
9082 org-up-element
9083 outline-demote
9084 outline-next-visible-heading
9085 outline-previous-visible-heading
9086 outline-promote
9087 outline-up-heading
9088 show-children))
9089 (let ((f (or (car-safe cell) cell))
9090 (disable-when-heading-prefix (cdr-safe cell)))
9091 (when (fboundp f)
9092 (let ((new-bindings))
9093 (dolist (binding (nconc (where-is-internal f org-mode-map)
9094 (where-is-internal f outline-mode-map)))
9095 (push binding new-bindings)
9096 ;; TODO use local-function-key-map
9097 (dolist (rep '(("<tab>" . "TAB")
9098 ("<return>" . "RET")
9099 ("<escape>" . "ESC")
9100 ("<delete>" . "DEL")))
9101 (setq binding (read-kbd-macro
9102 (let ((case-fold-search))
9103 (replace-regexp-in-string
9104 (regexp-quote (cdr rep))
9105 (car rep)
9106 (key-description binding)))))
9107 (pushnew binding new-bindings :test 'equal)))
9108 (dolist (binding new-bindings)
9109 (let ((key (lookup-key orgstruct-mode-map binding)))
9110 (when (or (not key) (numberp key))
9111 (condition-case nil
9112 (org-defkey orgstruct-mode-map
9113 binding
9114 (orgstruct-make-binding f binding disable-when-heading-prefix))
9115 (error nil)))))))))
9116 (run-hooks 'orgstruct-setup-hook))
9118 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9119 "Create a function for binding in the structure minor mode.
9120 FUN is the command to call inside a table. KEY is the key that
9121 should be checked in for a command to execute outside of tables.
9122 Non-nil `disable-when-heading-prefix' means to disable the command
9123 if `orgstruct-heading-prefix-regexp' is not empty."
9124 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9125 (let ((nname name)
9126 (i 0))
9127 (while (fboundp (intern nname))
9128 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9129 (setq name (intern nname)))
9130 (eval
9131 (let ((bindings '((org-heading-regexp
9132 (concat "^"
9133 orgstruct-heading-prefix-regexp
9134 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9135 (org-outline-regexp
9136 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9137 (org-outline-regexp-bol
9138 (concat "^" org-outline-regexp))
9139 (outline-regexp org-outline-regexp)
9140 (outline-heading-end-regexp "\n")
9141 (outline-level 'org-outline-level)
9142 (outline-heading-alist))))
9143 `(defun ,name (arg)
9144 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9145 "Outside of structure, run the binding of `"
9146 (key-description key) "'."
9147 (when disable-when-heading-prefix
9148 (concat
9149 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9150 "back to the default binding due to limitations of Org's implementation of\n"
9151 "`" (symbol-name fun) "'.")))
9152 (interactive "p")
9153 (let* ((disable
9154 ,(and disable-when-heading-prefix
9155 '(not (string= orgstruct-heading-prefix-regexp ""))))
9156 (fallback
9157 (or disable
9158 (not
9159 (let* ,bindings
9160 (org-context-p 'headline 'item
9161 ,(when (memq fun
9162 '(org-insert-heading
9163 org-insert-heading-respect-content
9164 org-meta-return))
9165 '(when orgstruct-is-++
9166 'item-body))))))))
9167 (if fallback
9168 (let* ((orgstruct-mode)
9169 (binding
9170 (loop with key = ,key
9171 for rep in
9172 '(nil
9173 ("<\\([^>]*\\)tab>" . "\\1TAB")
9174 ("<\\([^>]*\\)return>" . "\\1RET")
9175 ("<\\([^>]*\\)escape>" . "\\1ESC")
9176 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9178 (when rep
9179 (setq key (read-kbd-macro
9180 (let ((case-fold-search))
9181 (replace-regexp-in-string
9182 (car rep)
9183 (cdr rep)
9184 (key-description key))))))
9185 thereis (key-binding key))))
9186 (if (keymapp binding)
9187 (org-set-transient-map binding)
9188 (let ((func (or binding
9189 (unless disable
9190 'orgstruct-error))))
9191 (when func
9192 (call-interactively func)))))
9193 (org-run-like-in-org-mode
9194 (lambda ()
9195 (interactive)
9196 (let* ,bindings
9197 (call-interactively ',fun)))))))))
9198 name))
9200 (defun org-contextualize-keys (alist contexts)
9201 "Return valid elements in ALIST depending on CONTEXTS.
9203 `org-agenda-custom-commands' or `org-capture-templates' are the
9204 values used for ALIST, and `org-agenda-custom-commands-contexts'
9205 or `org-capture-templates-contexts' are the associated contexts
9206 definitions."
9207 (let ((contexts
9208 ;; normalize contexts
9209 (mapcar
9210 (lambda(c) (cond ((listp (cadr c))
9211 (list (car c) (car c) (cadr c)))
9212 ((string= "" (cadr c))
9213 (list (car c) (car c) (caddr c)))
9214 (t c))) contexts))
9215 (a alist) c r s)
9216 ;; loop over all commands or templates
9217 (while (setq c (pop a))
9218 (let (vrules repl)
9219 (cond
9220 ((not (assoc (car c) contexts))
9221 (push c r))
9222 ((and (assoc (car c) contexts)
9223 (setq vrules (org-contextualize-validate-key
9224 (car c) contexts)))
9225 (mapc (lambda (vr)
9226 (when (not (equal (car vr) (cadr vr)))
9227 (setq repl vr))) vrules)
9228 (if (not repl) (push c r)
9229 (push (cadr repl) s)
9230 (push
9231 (cons (car c)
9232 (cdr (or (assoc (cadr repl) alist)
9233 (error "Undefined key `%s' as contextual replacement for `%s'"
9234 (cadr repl) (car c)))))
9235 r))))))
9236 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9237 (delq
9239 (delete-dups
9240 (mapcar (lambda (x)
9241 (let ((tpl (car x)))
9242 (when (not (delq
9244 (mapcar (lambda(y)
9245 (equal y tpl)) s))) x)))
9246 (reverse r))))))
9248 (defun org-contextualize-validate-key (key contexts)
9249 "Check CONTEXTS for agenda or capture KEY."
9250 (let (r rr res)
9251 (while (setq r (pop contexts))
9252 (mapc
9253 (lambda (rr)
9254 (when
9255 (and (equal key (car r))
9256 (if (functionp rr) (funcall rr)
9257 (or (and (eq (car rr) 'in-file)
9258 (buffer-file-name)
9259 (string-match (cdr rr) (buffer-file-name)))
9260 (and (eq (car rr) 'in-mode)
9261 (string-match (cdr rr) (symbol-name major-mode)))
9262 (and (eq (car rr) 'in-buffer)
9263 (string-match (cdr rr) (buffer-name)))
9264 (if (and (eq (car rr) 'not-in-file)
9265 (buffer-file-name))
9266 (not (string-match (cdr rr) (buffer-file-name)))
9268 (when (eq (car rr) 'not-in-mode)
9269 (not (string-match (cdr rr) (symbol-name major-mode))))
9270 (when (eq (car rr) 'not-in-buffer)
9271 (not (string-match (cdr rr) (buffer-name)))))))
9272 (push r res)))
9273 (car (last r))))
9274 (delete-dups (delq nil res))))
9276 (defun org-context-p (&rest contexts)
9277 "Check if local context is any of CONTEXTS.
9278 Possible values in the list of contexts are `table', `headline', and `item'."
9279 (let ((pos (point)))
9280 (goto-char (point-at-bol))
9281 (prog1 (or (and (memq 'table contexts)
9282 (looking-at "[ \t]*|"))
9283 (and (memq 'headline contexts)
9284 (looking-at org-outline-regexp))
9285 (and (memq 'item contexts)
9286 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9287 (and (memq 'item-body contexts)
9288 (org-in-item-p)))
9289 (goto-char pos))))
9291 (defun org-get-local-variables ()
9292 "Return a list of all local variables in an Org mode buffer."
9293 (let (varlist)
9294 (with-current-buffer (get-buffer-create "*Org tmp*")
9295 (erase-buffer)
9296 (org-mode)
9297 (setq varlist (buffer-local-variables)))
9298 (kill-buffer "*Org tmp*")
9299 (delq nil
9300 (mapcar
9301 (lambda (x)
9302 (setq x
9303 (if (symbolp x)
9304 (list x)
9305 (list (car x) (cdr x))))
9306 (if (and (not (get (car x) 'org-state))
9307 (string-match
9308 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9309 (symbol-name (car x))))
9310 x nil))
9311 varlist))))
9313 (defun org-clone-local-variables (from-buffer &optional regexp)
9314 "Clone local variables from FROM-BUFFER.
9315 Optional argument REGEXP selects variables to clone."
9316 (mapc
9317 (lambda (pair)
9318 (and (symbolp (car pair))
9319 (or (null regexp)
9320 (string-match regexp (symbol-name (car pair))))
9321 (set (make-local-variable (car pair))
9322 (cdr pair))))
9323 (buffer-local-variables from-buffer)))
9325 ;;;###autoload
9326 (defun org-run-like-in-org-mode (cmd)
9327 "Run a command, pretending that the current buffer is in Org-mode.
9328 This will temporarily bind local variables that are typically bound in
9329 Org-mode to the values they have in Org-mode, and then interactively
9330 call CMD."
9331 (org-load-modules-maybe)
9332 (unless org-local-vars
9333 (setq org-local-vars (org-get-local-variables)))
9334 (let (binds)
9335 (dolist (var org-local-vars)
9336 (when (or (not (boundp (car var)))
9337 (eq (symbol-value (car var))
9338 (default-value (car var))))
9339 (push (list (car var) `(quote ,(cadr var))) binds)))
9340 (eval `(let ,binds
9341 (call-interactively (quote ,cmd))))))
9343 ;;;; Archiving
9345 (defun org-get-category (&optional pos force-refresh)
9346 "Get the category applying to position POS."
9347 (save-match-data
9348 (if force-refresh (org-refresh-category-properties))
9349 (let ((pos (or pos (point))))
9350 (or (get-text-property pos 'org-category)
9351 (progn (org-refresh-category-properties)
9352 (get-text-property pos 'org-category))))))
9354 (defun org-refresh-category-properties ()
9355 "Refresh category text properties in the buffer."
9356 (let ((case-fold-search t)
9357 (inhibit-read-only t)
9358 (def-cat (cond
9359 ((null org-category)
9360 (if buffer-file-name
9361 (file-name-sans-extension
9362 (file-name-nondirectory buffer-file-name))
9363 "???"))
9364 ((symbolp org-category) (symbol-name org-category))
9365 (t org-category)))
9366 beg end cat pos optionp)
9367 (org-with-silent-modifications
9368 (save-excursion
9369 (save-restriction
9370 (widen)
9371 (goto-char (point-min))
9372 (put-text-property (point) (point-max) 'org-category def-cat)
9373 (while (re-search-forward
9374 "^[ \t]*\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9375 (setq pos (match-end 0)
9376 optionp (equal (char-after (match-beginning 0)) ?#)
9377 cat (org-trim (match-string 2)))
9378 (if optionp
9379 (setq beg (point-at-bol) end (point-max))
9380 (org-back-to-heading t)
9381 (setq beg (point) end (org-end-of-subtree t t)))
9382 (put-text-property beg end 'org-category cat)
9383 (put-text-property beg end 'org-category-position beg)
9384 (goto-char pos)))))))
9386 (defun org-refresh-properties (dprop tprop)
9387 "Refresh buffer text properties.
9388 DPROP is the drawer property and TPROP is the corresponding text
9389 property to set."
9390 (let ((case-fold-search t)
9391 (inhibit-read-only t) p)
9392 (org-with-silent-modifications
9393 (save-excursion
9394 (save-restriction
9395 (widen)
9396 (goto-char (point-min))
9397 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9398 (setq p (org-match-string-no-properties 1))
9399 (save-excursion
9400 (org-back-to-heading t)
9401 (put-text-property
9402 (point-at-bol) (or (outline-next-heading) (point-max)) tprop p))))))))
9405 ;;;; Link Stuff
9407 ;;; Link abbreviations
9409 (defun org-link-expand-abbrev (link)
9410 "Apply replacements as defined in `org-link-abbrev-alist'."
9411 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9412 (let* ((key (match-string 1 link))
9413 (as (or (assoc key org-link-abbrev-alist-local)
9414 (assoc key org-link-abbrev-alist)))
9415 (tag (and (match-end 2) (match-string 3 link)))
9416 rpl)
9417 (if (not as)
9418 link
9419 (setq rpl (cdr as))
9420 (cond
9421 ((symbolp rpl) (funcall rpl tag))
9422 ((string-match "%(\\([^)]+\\))" rpl)
9423 (replace-match
9424 (save-match-data
9425 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9426 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9427 ((string-match "%h" rpl)
9428 (replace-match (url-hexify-string (or tag "")) t t rpl))
9429 (t (concat rpl tag)))))
9430 link))
9432 ;;; Storing and inserting links
9434 (defvar org-insert-link-history nil
9435 "Minibuffer history for links inserted with `org-insert-link'.")
9437 (defvar org-stored-links nil
9438 "Contains the links stored with `org-store-link'.")
9440 (defvar org-store-link-plist nil
9441 "Plist with info about the most recently link created with `org-store-link'.")
9443 (defvar org-link-protocols nil
9444 "Link protocols added to Org-mode using `org-add-link-type'.")
9446 (defvar org-store-link-functions nil
9447 "List of functions that are called to create and store a link.
9448 Each function will be called in turn until one returns a non-nil
9449 value. Each function should check if it is responsible for creating
9450 this link (for example by looking at the major mode).
9451 If not, it must exit and return nil.
9452 If yes, it should return a non-nil value after a calling
9453 `org-store-link-props' with a list of properties and values.
9454 Special properties are:
9456 :type The link prefix, like \"http\". This must be given.
9457 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9458 This is obligatory as well.
9459 :description Optional default description for the second pair
9460 of brackets in an Org-mode link. The user can still change
9461 this when inserting this link into an Org-mode buffer.
9463 In addition to these, any additional properties can be specified
9464 and then used in capture templates.")
9466 (defun org-add-link-type (type &optional follow export)
9467 "Add TYPE to the list of `org-link-types'.
9468 Re-compute all regular expressions depending on `org-link-types'
9470 FOLLOW and EXPORT are two functions.
9472 FOLLOW should take the link path as the single argument and do whatever
9473 is necessary to follow the link, for example find a file or display
9474 a mail message.
9476 EXPORT should format the link path for export to one of the export formats.
9477 It should be a function accepting three arguments:
9479 path the path of the link, the text after the prefix (like \"http:\")
9480 desc the description of the link, if any, or a description added by
9481 org-export-normalize-links if there is none
9482 format the export format, a symbol like `html' or `latex' or `ascii'..
9484 The function may use the FORMAT information to return different values
9485 depending on the format. The return value will be put literally into
9486 the exported file. If the return value is nil, this means Org should
9487 do what it normally does with links which do not have EXPORT defined.
9489 Org-mode has a built-in default for exporting links. If you are happy with
9490 this default, there is no need to define an export function for the link
9491 type. For a simple example of an export function, see `org-bbdb.el'."
9492 (add-to-list 'org-link-types type t)
9493 (org-make-link-regexps)
9494 (if (assoc type org-link-protocols)
9495 (setcdr (assoc type org-link-protocols) (list follow export))
9496 (push (list type follow export) org-link-protocols)))
9498 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9499 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9501 ;;;###autoload
9502 (defun org-store-link (arg)
9503 "\\<org-mode-map>Store an org-link to the current location.
9504 This link is added to `org-stored-links' and can later be inserted
9505 into an org-buffer with \\[org-insert-link].
9507 For some link types, a prefix arg is interpreted.
9508 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9509 For file links, arg negates `org-context-in-file-links'.
9511 A double prefix arg force skipping storing functions that are not
9512 part of Org's core.
9514 A triple prefix arg force storing a link for each line in the
9515 active region."
9516 (interactive "P")
9517 (org-load-modules-maybe)
9518 (if (and (equal arg '(64)) (org-region-active-p))
9519 (save-excursion
9520 (let ((end (region-end)))
9521 (goto-char (region-beginning))
9522 (set-mark (point))
9523 (while (< (point-at-eol) end)
9524 (move-end-of-line 1) (activate-mark)
9525 (let (current-prefix-arg)
9526 (call-interactively 'org-store-link))
9527 (move-beginning-of-line 2)
9528 (set-mark (point)))))
9529 (org-with-limited-levels
9530 (setq org-store-link-plist nil)
9531 (let (link cpltxt desc description search
9532 txt custom-id agenda-link sfuns sfunsn)
9533 (cond
9535 ;; Store a link using an external link type
9536 ((and (not (equal arg '(16)))
9537 (setq sfuns
9538 (delq
9539 nil (mapcar (lambda (f)
9540 (let (fs) (if (funcall f) (push f fs))))
9541 org-store-link-functions))
9542 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9543 (or (and (cdr sfuns)
9544 (funcall (intern
9545 (completing-read
9546 "Which function for creating the link? "
9547 sfunsn nil t (car sfunsn)))))
9548 (funcall (caar sfuns)))
9549 (setq link (plist-get org-store-link-plist :link)
9550 desc (or (plist-get org-store-link-plist
9551 :description) link))))
9553 ;; Store a link from a source code buffer
9554 ((org-src-edit-buffer-p)
9555 (let (label gc)
9556 (while (or (not label)
9557 (save-excursion
9558 (save-restriction
9559 (widen)
9560 (goto-char (point-min))
9561 (re-search-forward
9562 (regexp-quote (format org-coderef-label-format label))
9563 nil t))))
9564 (when label (message "Label exists already") (sit-for 2))
9565 (setq label (read-string "Code line label: " label)))
9566 (end-of-line 1)
9567 (setq link (format org-coderef-label-format label))
9568 (setq gc (- 79 (length link)))
9569 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9570 (insert link)
9571 (setq link (concat "(" label ")") desc nil)))
9573 ;; We are in the agenda, link to referenced location
9574 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9575 (let ((m (or (get-text-property (point) 'org-hd-marker)
9576 (get-text-property (point) 'org-marker))))
9577 (when m
9578 (org-with-point-at m
9579 (setq agenda-link
9580 (if (org-called-interactively-p 'any)
9581 (call-interactively 'org-store-link)
9582 (org-store-link nil)))))))
9584 ((eq major-mode 'calendar-mode)
9585 (let ((cd (calendar-cursor-to-date)))
9586 (setq link
9587 (format-time-string
9588 (car org-time-stamp-formats)
9589 (apply 'encode-time
9590 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9591 nil nil nil))))
9592 (org-store-link-props :type "calendar" :date cd)))
9594 ((eq major-mode 'help-mode)
9595 (setq link (concat "help:" (save-excursion
9596 (goto-char (point-min))
9597 (looking-at "^[^ ]+")
9598 (match-string 0))))
9599 (org-store-link-props :type "help"))
9601 ((eq major-mode 'w3-mode)
9602 (setq cpltxt (if (and (buffer-name)
9603 (not (string-match "Untitled" (buffer-name))))
9604 (buffer-name)
9605 (url-view-url t))
9606 link (url-view-url t))
9607 (org-store-link-props :type "w3" :url (url-view-url t)))
9609 ((eq major-mode 'image-mode)
9610 (setq cpltxt (concat "file:"
9611 (abbreviate-file-name buffer-file-name))
9612 link cpltxt)
9613 (org-store-link-props :type "image" :file buffer-file-name))
9615 ;; In dired, store a link to the file of the current line
9616 ((derived-mode-p 'dired-mode)
9617 (let ((file (dired-get-filename nil t)))
9618 (setq file (if file
9619 (abbreviate-file-name
9620 (expand-file-name (dired-get-filename nil t)))
9621 ;; otherwise, no file so use current directory.
9622 default-directory))
9623 (setq cpltxt (concat "file:" file)
9624 link cpltxt)))
9626 ((setq search (run-hook-with-args-until-success
9627 'org-create-file-search-functions))
9628 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9629 "::" search))
9630 (setq cpltxt (or description link)))
9632 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9633 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9634 (cond
9635 ;; Store a link using the target at point
9636 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9637 (setq cpltxt
9638 (concat "file:"
9639 (abbreviate-file-name
9640 (buffer-file-name (buffer-base-buffer)))
9641 "::" (match-string 1))
9642 link cpltxt))
9643 ((and (featurep 'org-id)
9644 (or (eq org-id-link-to-org-use-id t)
9645 (and (org-called-interactively-p 'any)
9646 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9647 (and (eq org-id-link-to-org-use-id
9648 'create-if-interactive-and-no-custom-id)
9649 (not custom-id))))
9650 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9651 ;; Store a link using the ID at point
9652 (setq link (condition-case nil
9653 (prog1 (org-id-store-link)
9654 (setq desc (or (plist-get org-store-link-plist
9655 :description)
9656 "")))
9657 (error
9658 ;; Probably before first headline, link only to file
9659 (concat "file:"
9660 (abbreviate-file-name
9661 (buffer-file-name (buffer-base-buffer))))))))
9663 ;; Just link to current headline
9664 (setq cpltxt (concat "file:"
9665 (abbreviate-file-name
9666 (buffer-file-name (buffer-base-buffer)))))
9667 ;; Add a context search string
9668 (when (org-xor org-context-in-file-links arg)
9669 (let* ((ee (org-element-at-point))
9670 (et (org-element-type ee))
9671 (ev (plist-get (cadr ee) :value))
9672 (ek (plist-get (cadr ee) :key))
9673 (eok (and (stringp ek) (string-match "name" ek))))
9674 (setq txt (cond
9675 ((org-at-heading-p) nil)
9676 ((and (eq et 'keyword) eok) ev)
9677 ((org-region-active-p)
9678 (buffer-substring (region-beginning) (region-end)))))
9679 (when (or (null txt) (string-match "\\S-" txt))
9680 (setq cpltxt
9681 (concat cpltxt "::"
9682 (condition-case nil
9683 (org-make-org-heading-search-string txt)
9684 (error "")))
9685 desc (or (and (eq et 'keyword) eok ev)
9686 (nth 4 (ignore-errors (org-heading-components)))
9687 "NONE")))))
9688 (if (string-match "::\\'" cpltxt)
9689 (setq cpltxt (substring cpltxt 0 -2)))
9690 (setq link cpltxt))))
9692 ((buffer-file-name (buffer-base-buffer))
9693 ;; Just link to this file here.
9694 (setq cpltxt (concat "file:"
9695 (abbreviate-file-name
9696 (buffer-file-name (buffer-base-buffer)))))
9697 ;; Add a context string.
9698 (when (org-xor org-context-in-file-links arg)
9699 (setq txt (if (org-region-active-p)
9700 (buffer-substring (region-beginning) (region-end))
9701 (buffer-substring (point-at-bol) (point-at-eol))))
9702 ;; Only use search option if there is some text.
9703 (when (string-match "\\S-" txt)
9704 (setq cpltxt
9705 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9706 desc "NONE")))
9707 (setq link cpltxt))
9709 ((org-called-interactively-p 'interactive)
9710 (user-error "No method for storing a link from this buffer"))
9712 (t (setq link nil)))
9714 ;; We're done setting link and desc, clean up
9715 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9716 (setq link (or link cpltxt)
9717 desc (or desc cpltxt))
9718 (cond ((equal desc "NONE") (setq desc nil))
9719 ((and desc (string-match org-bracket-link-analytic-regexp desc))
9720 (let ((d0 (match-string 3 desc))
9721 (p0 (match-string 5 desc)))
9722 (setq desc
9723 (replace-regexp-in-string
9724 org-bracket-link-regexp
9725 (concat (or p0 d0)
9726 (if (equal (length (match-string 0 desc))
9727 (length desc)) "*" "")) desc)))))
9729 ;; Return the link
9730 (if (not (and (or (org-called-interactively-p 'any)
9731 executing-kbd-macro) link))
9732 (or agenda-link (and link (org-make-link-string link desc)))
9733 (push (list link desc) org-stored-links)
9734 (message "Stored: %s" (or desc link))
9735 (when custom-id
9736 (setq link (concat "file:" (abbreviate-file-name
9737 (buffer-file-name)) "::#" custom-id))
9738 (push (list link desc) org-stored-links))
9739 (car org-stored-links))))))
9741 (defun org-store-link-props (&rest plist)
9742 "Store link properties, extract names and addresses."
9743 (let (x adr)
9744 (when (setq x (plist-get plist :from))
9745 (setq adr (mail-extract-address-components x))
9746 (setq plist (plist-put plist :fromname (car adr)))
9747 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9748 (when (setq x (plist-get plist :to))
9749 (setq adr (mail-extract-address-components x))
9750 (setq plist (plist-put plist :toname (car adr)))
9751 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9752 (let ((from (plist-get plist :from))
9753 (to (plist-get plist :to)))
9754 (when (and from to org-from-is-user-regexp)
9755 (setq plist
9756 (plist-put plist :fromto
9757 (if (string-match org-from-is-user-regexp from)
9758 (concat "to %t")
9759 (concat "from %f"))))))
9760 (setq org-store-link-plist plist))
9762 (defun org-add-link-props (&rest plist)
9763 "Add these properties to the link property list."
9764 (let (key value)
9765 (while plist
9766 (setq key (pop plist) value (pop plist))
9767 (setq org-store-link-plist
9768 (plist-put org-store-link-plist key value)))))
9770 (defun org-email-link-description (&optional fmt)
9771 "Return the description part of an email link.
9772 This takes information from `org-store-link-plist' and formats it
9773 according to FMT (default from `org-email-link-description-format')."
9774 (setq fmt (or fmt org-email-link-description-format))
9775 (let* ((p org-store-link-plist)
9776 (to (plist-get p :toaddress))
9777 (from (plist-get p :fromaddress))
9778 (table
9779 (list
9780 (cons "%c" (plist-get p :fromto))
9781 (cons "%F" (plist-get p :from))
9782 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9783 (cons "%T" (plist-get p :to))
9784 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9785 (cons "%s" (plist-get p :subject))
9786 (cons "%d" (plist-get p :date))
9787 (cons "%m" (plist-get p :message-id)))))
9788 (when (string-match "%c" fmt)
9789 ;; Check if the user wrote this message
9790 (if (and org-from-is-user-regexp from to
9791 (save-match-data (string-match org-from-is-user-regexp from)))
9792 (setq fmt (replace-match "to %t" t t fmt))
9793 (setq fmt (replace-match "from %f" t t fmt))))
9794 (org-replace-escapes fmt table)))
9796 (defun org-make-org-heading-search-string (&optional string)
9797 "Make search string for the current headline or STRING."
9798 (let ((s (or string
9799 (and (derived-mode-p 'org-mode)
9800 (save-excursion
9801 (org-back-to-heading t)
9802 (org-element-property :raw-value (org-element-at-point))))))
9803 (lines org-context-in-file-links))
9804 (or string (setq s (concat "*" s))) ; Add * for headlines
9805 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9806 (when (and string (integerp lines) (> lines 0))
9807 (let ((slines (org-split-string s "\n")))
9808 (when (< lines (length slines))
9809 (setq s (mapconcat
9810 'identity
9811 (reverse (nthcdr (- (length slines) lines)
9812 (reverse slines))) "\n")))))
9813 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9815 (defun org-make-link-string (link &optional description)
9816 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9817 (unless (string-match "\\S-" link)
9818 (error "Empty link"))
9819 (when (and description
9820 (stringp description)
9821 (not (string-match "\\S-" description)))
9822 (setq description nil))
9823 (when (stringp description)
9824 ;; Remove brackets from the description, they are fatal.
9825 (while (string-match "\\[" description)
9826 (setq description (replace-match "{" t t description)))
9827 (while (string-match "\\]" description)
9828 (setq description (replace-match "}" t t description))))
9829 (when (equal link description)
9830 ;; No description needed, it is identical
9831 (setq description nil))
9832 (when (and (not description)
9833 (not (string-match (org-image-file-name-regexp) link))
9834 (not (equal link (org-link-escape link))))
9835 (setq description (org-extract-attributes link)))
9836 (setq link
9837 (cond ((string-match (org-image-file-name-regexp) link) link)
9838 ((string-match org-link-types-re link)
9839 (concat (match-string 1 link)
9840 (org-link-escape (substring link (match-end 1)))))
9841 (t (org-link-escape link))))
9842 (concat "[[" link "]"
9843 (if description (concat "[" description "]") "")
9844 "]"))
9846 (defconst org-link-escape-chars
9847 ;;%20 %2B %3B %3D %5B %5D
9848 '(?\ ?\+ ?\; ?\= ?\[ ?\])
9849 "List of characters that should be escaped in a link when stored to Org.
9850 This is the list that is used for internal purposes.")
9852 (defconst org-link-escape-chars-browser
9853 ;;%20 %22
9854 '(?\ ?\")
9855 "List of characters to be escaped before handing over to the browser.
9856 If you consider using this constant then you probably want to use
9857 the function `org-link-escape-browser' instead. See there why
9858 this constant is a candidate to be removed once Org drops support
9859 for Emacs 24.1 and 24.2.")
9861 (defun org-link-escape (text &optional table merge)
9862 "Return percent escaped representation of TEXT.
9863 TEXT is a string with the text to escape.
9864 Optional argument TABLE is a list with characters that should be
9865 escaped. When nil, `org-link-escape-chars' is used.
9866 If optional argument MERGE is set, merge TABLE into
9867 `org-link-escape-chars'."
9868 (cond
9869 ((and table merge)
9870 (mapc (lambda (defchr)
9871 (unless (member defchr table)
9872 (setq table (cons defchr table)))) org-link-escape-chars))
9873 ((null table)
9874 (setq table org-link-escape-chars)))
9875 (mapconcat
9876 (lambda (char)
9877 (if (or (member char table)
9878 (and (or (< char 32) (= char ?\%) (> char 126))
9879 org-url-hexify-p))
9880 (mapconcat (lambda (sequence-element)
9881 (format "%%%.2X" sequence-element))
9882 (or (encode-coding-char char 'utf-8)
9883 (error "Unable to percent escape character: %s"
9884 (char-to-string char))) "")
9885 (char-to-string char))) text ""))
9887 (defun org-link-escape-browser (text)
9888 "Escape some characters before handing over to the browser.
9889 This function is a candidate to be removed together with the
9890 constant `org-link-escape-chars-browser' once Org drops support
9891 for Emacs 24.1 and 24.2. All calls to this function will have to
9892 be replaced with `url-encode-url' which is available since Emacs
9893 24.3.1."
9894 ;; Example with the Org link
9895 ;; [[http://lists.gnu.org/archive/cgi-bin/namazu.cgi?idxname=emacs-orgmode&query=%252Bsubject:"Release+8.2"]]
9896 ;; to open the browser with +subject:"Release 8.2" filled into the
9897 ;; query field: In this case the variable TEXT contains the
9898 ;; unescaped [...]=%2Bsubject:"Release+8.2". Then `url-encode-url'
9899 ;; converts correctly to [...]=%2Bsubject:%22Release+8.2%22 or
9900 ;; `org-link-escape' with `org-link-escape-chars-browser' converts
9901 ;; wrongly to [...]=%252Bsubject:%22Release+8.2%22.
9902 (if (fboundp 'url-encode-url)
9903 (url-encode-url text)
9904 (if (org-string-match-p
9905 (concat "[[:nonascii:]" org-link-escape-chars-browser "]")
9906 text)
9907 (org-link-escape text org-link-escape-chars-browser)
9908 text)))
9910 (defun org-link-unescape (str)
9911 "Unhex hexified Unicode strings as returned from the JavaScript function
9912 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9913 (unless (and (null str) (string= "" str))
9914 (let ((pos 0) (case-fold-search t) unhexed)
9915 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9916 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9917 (setq str (replace-match unhexed t t str))
9918 (setq pos (+ pos (length unhexed))))))
9919 str)
9921 (defun org-link-unescape-compound (hex)
9922 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9923 Note: this function also decodes single byte encodings like
9924 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9925 (save-match-data
9926 (let* ((bytes (cdr (split-string hex "%")))
9927 (ret "")
9928 (eat 0)
9929 (sum 0))
9930 (while bytes
9931 (let* ((val (string-to-number (pop bytes) 16))
9932 (shift-xor
9933 (if (= 0 eat)
9934 (cond
9935 ((>= val 252) (cons 6 252))
9936 ((>= val 248) (cons 5 248))
9937 ((>= val 240) (cons 4 240))
9938 ((>= val 224) (cons 3 224))
9939 ((>= val 192) (cons 2 192))
9940 (t (cons 0 0)))
9941 (cons 6 128))))
9942 (if (>= val 192) (setq eat (car shift-xor)))
9943 (setq val (logxor val (cdr shift-xor)))
9944 (setq sum (+ (lsh sum (car shift-xor)) val))
9945 (if (> eat 0) (setq eat (- eat 1)))
9946 (cond
9947 ((= 0 eat) ;multi byte
9948 (setq ret (concat ret (org-char-to-string sum)))
9949 (setq sum 0))
9950 ((not bytes) ; single byte(s)
9951 (setq ret (org-link-unescape-single-byte-sequence hex))))
9952 )) ;; end (while bytes
9953 ret )))
9955 (defun org-link-unescape-single-byte-sequence (hex)
9956 "Unhexify hex-encoded single byte character sequences."
9957 (mapconcat (lambda (byte)
9958 (char-to-string (string-to-number byte 16)))
9959 (cdr (split-string hex "%")) ""))
9961 (defun org-xor (a b)
9962 "Exclusive or."
9963 (if a (not b) b))
9965 (defun org-fixup-message-id-for-http (s)
9966 "Replace special characters in a message id, so it can be used in an http query."
9967 (when (string-match "%" s)
9968 (setq s (mapconcat (lambda (c)
9969 (if (eq c ?%)
9970 "%25"
9971 (char-to-string c)))
9972 s "")))
9973 (while (string-match "<" s)
9974 (setq s (replace-match "%3C" t t s)))
9975 (while (string-match ">" s)
9976 (setq s (replace-match "%3E" t t s)))
9977 (while (string-match "@" s)
9978 (setq s (replace-match "%40" t t s)))
9981 (defun org-link-prettify (link)
9982 "Return a human-readable representation of LINK.
9983 The car of LINK must be a raw link.
9984 The cdr of LINK must be either a link description or nil."
9985 (let ((desc (or (cadr link) "<no description>")))
9986 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9987 "<" (car link) ">")))
9989 ;;;###autoload
9990 (defun org-insert-link-global ()
9991 "Insert a link like Org-mode does.
9992 This command can be called in any mode to insert a link in Org-mode syntax."
9993 (interactive)
9994 (org-load-modules-maybe)
9995 (org-run-like-in-org-mode 'org-insert-link))
9997 (defun org-insert-all-links (arg &optional pre post)
9998 "Insert all links in `org-stored-links'.
9999 When a universal prefix, do not delete the links from `org-stored-links'.
10000 When `ARG' is a number, insert the last N link(s).
10001 `PRE' and `POST' are optional arguments to define a string to
10002 prepend or to append."
10003 (interactive "P")
10004 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10005 (links (copy-seq org-stored-links))
10006 (pr (or pre "- "))
10007 (po (or post "\n"))
10008 (cnt 1) l)
10009 (if (null org-stored-links)
10010 (message "No link to insert")
10011 (while (and (or (listp arg) (>= arg cnt))
10012 (setq l (if (listp arg)
10013 (pop links)
10014 (pop org-stored-links))))
10015 (setq cnt (1+ cnt))
10016 (insert pr)
10017 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10018 (insert po)))))
10020 (defun org-insert-last-stored-link (arg)
10021 "Insert the last link stored in `org-stored-links'."
10022 (interactive "p")
10023 (org-insert-all-links arg "" "\n"))
10025 (defun org-link-fontify-links-to-this-file ()
10026 "Fontify links to the current file in `org-stored-links'."
10027 (let ((f (buffer-file-name)) a b)
10028 (setq a (mapcar (lambda(l)
10029 (let ((ll (car l)))
10030 (when (and (string-match "^file:\\(.+\\)::" ll)
10031 (equal f (expand-file-name (match-string 1 ll))))
10032 ll)))
10033 org-stored-links))
10034 (when (featurep 'org-id)
10035 (setq b (mapcar (lambda(l)
10036 (let ((ll (car l)))
10037 (when (and (string-match "^id:\\(.+\\)$" ll)
10038 (equal f (expand-file-name
10039 (or (org-id-find-id-file
10040 (match-string 1 ll)) ""))))
10041 ll)))
10042 org-stored-links)))
10043 (mapcar (lambda(l)
10044 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10045 (delq nil (append a b)))))
10047 (defvar org-link-links-in-this-file nil)
10048 (defun org-insert-link (&optional complete-file link-location default-description)
10049 "Insert a link. At the prompt, enter the link.
10051 Completion can be used to insert any of the link protocol prefixes like
10052 http or ftp in use.
10054 The history can be used to select a link previously stored with
10055 `org-store-link'. When the empty string is entered (i.e. if you just
10056 press RET at the prompt), the link defaults to the most recently
10057 stored link. As SPC triggers completion in the minibuffer, you need to
10058 use M-SPC or C-q SPC to force the insertion of a space character.
10060 You will also be prompted for a description, and if one is given, it will
10061 be displayed in the buffer instead of the link.
10063 If there is already a link at point, this command will allow you to edit link
10064 and description parts.
10066 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
10067 be selected using completion. The path to the file will be relative to the
10068 current directory if the file is in the current directory or a subdirectory.
10069 Otherwise, the link will be the absolute path as completed in the minibuffer
10070 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10071 option `org-link-file-path-type'.
10073 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
10074 the current directory or below.
10076 With three \\[universal-argument] prefixes, negate the meaning of
10077 `org-keep-stored-link-after-insertion'.
10079 If `org-make-link-description-function' is non-nil, this function will be
10080 called with the link target, and the result will be the default
10081 link description.
10083 If the LINK-LOCATION parameter is non-nil, this value will be
10084 used as the link location instead of reading one interactively.
10086 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10087 be used as the default description."
10088 (interactive "P")
10089 (let* ((wcf (current-window-configuration))
10090 (origbuf (current-buffer))
10091 (region (if (org-region-active-p)
10092 (buffer-substring (region-beginning) (region-end))))
10093 (remove (and region (list (region-beginning) (region-end))))
10094 (desc region)
10095 tmphist ; byte-compile incorrectly complains about this
10096 (link link-location)
10097 (abbrevs org-link-abbrev-alist-local)
10098 entry file all-prefixes auto-desc)
10099 (cond
10100 (link-location) ; specified by arg, just use it.
10101 ((org-in-regexp org-bracket-link-regexp 1)
10102 ;; We do have a link at point, and we are going to edit it.
10103 (setq remove (list (match-beginning 0) (match-end 0)))
10104 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
10105 (setq link (read-string "Link: "
10106 (org-link-unescape
10107 (org-match-string-no-properties 1)))))
10108 ((or (org-in-regexp org-angle-link-re)
10109 (org-in-regexp org-plain-link-re))
10110 ;; Convert to bracket link
10111 (setq remove (list (match-beginning 0) (match-end 0))
10112 link (read-string "Link: "
10113 (org-remove-angle-brackets (match-string 0)))))
10114 ((member complete-file '((4) (16)))
10115 ;; Completing read for file names.
10116 (setq link (org-file-complete-link complete-file)))
10118 ;; Read link, with completion for stored links.
10119 (org-link-fontify-links-to-this-file)
10120 (org-switch-to-buffer-other-window "*Org Links*")
10121 (with-current-buffer "*Org Links*"
10122 (erase-buffer)
10123 (insert "Insert a link.
10124 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10125 (when org-stored-links
10126 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10127 (insert (mapconcat 'org-link-prettify
10128 (reverse org-stored-links) "\n")))
10129 (goto-char (point-min)))
10130 (let ((cw (selected-window)))
10131 (select-window (get-buffer-window "*Org Links*" 'visible))
10132 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10133 (unless (pos-visible-in-window-p (point-max))
10134 (org-fit-window-to-buffer))
10135 (and (window-live-p cw) (select-window cw)))
10136 ;; Fake a link history, containing the stored links.
10137 (setq tmphist (append (mapcar 'car org-stored-links)
10138 org-insert-link-history))
10139 (setq all-prefixes (append (mapcar 'car abbrevs)
10140 (mapcar 'car org-link-abbrev-alist)
10141 org-link-types))
10142 (unwind-protect
10143 (progn
10144 (setq link
10145 (org-completing-read
10146 "Link: "
10147 (append
10148 (mapcar (lambda (x) (concat x ":"))
10149 all-prefixes)
10150 (mapcar 'car org-stored-links))
10151 nil nil nil
10152 'tmphist
10153 (caar org-stored-links)))
10154 (if (not (string-match "\\S-" link))
10155 (user-error "No link selected"))
10156 (mapc (lambda(l)
10157 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
10158 org-stored-links)
10159 (if (or (member link all-prefixes)
10160 (and (equal ":" (substring link -1))
10161 (member (substring link 0 -1) all-prefixes)
10162 (setq link (substring link 0 -1))))
10163 (setq link (with-current-buffer origbuf
10164 (org-link-try-special-completion link)))))
10165 (set-window-configuration wcf)
10166 (kill-buffer "*Org Links*"))
10167 (setq entry (assoc link org-stored-links))
10168 (or entry (push link org-insert-link-history))
10169 (setq desc (or desc (nth 1 entry)))))
10171 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10172 (not org-keep-stored-link-after-insertion))
10173 (setq org-stored-links (delq (assoc link org-stored-links)
10174 org-stored-links)))
10176 (if (and (string-match org-plain-link-re link)
10177 (not (string-match org-ts-regexp link)))
10178 ;; URL-like link, normalize the use of angular brackets.
10179 (setq link (org-remove-angle-brackets link)))
10181 ;; Check if we are linking to the current file with a search
10182 ;; option If yes, simplify the link by using only the search
10183 ;; option.
10184 (when (and buffer-file-name
10185 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10186 (let* ((path (match-string 1 link))
10187 (case-fold-search nil)
10188 (search (match-string 2 link)))
10189 (save-match-data
10190 (if (equal (file-truename buffer-file-name) (file-truename path))
10191 ;; We are linking to this same file, with a search option
10192 (setq link search)))))
10194 ;; Check if we can/should use a relative path. If yes, simplify the link
10195 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10196 (let* ((type (match-string 1 link))
10197 (path (match-string 2 link))
10198 (origpath path)
10199 (case-fold-search nil))
10200 (cond
10201 ((or (eq org-link-file-path-type 'absolute)
10202 (equal complete-file '(16)))
10203 (setq path (abbreviate-file-name (expand-file-name path))))
10204 ((eq org-link-file-path-type 'noabbrev)
10205 (setq path (expand-file-name path)))
10206 ((eq org-link-file-path-type 'relative)
10207 (setq path (file-relative-name path)))
10209 (save-match-data
10210 (if (string-match (concat "^" (regexp-quote
10211 (expand-file-name
10212 (file-name-as-directory
10213 default-directory))))
10214 (expand-file-name path))
10215 ;; We are linking a file with relative path name.
10216 (setq path (substring (expand-file-name path)
10217 (match-end 0)))
10218 (setq path (abbreviate-file-name (expand-file-name path)))))))
10219 (setq link (concat type path))
10220 (if (equal desc origpath)
10221 (setq desc path))))
10223 (if org-make-link-description-function
10224 (setq desc
10225 (or (condition-case nil
10226 (funcall org-make-link-description-function link desc)
10227 (error (progn (message "Can't get link description from `%s'"
10228 (symbol-name org-make-link-description-function))
10229 (sit-for 2) nil)))
10230 (read-string "Description: " default-description)))
10231 (if default-description (setq desc default-description)
10232 (setq desc (or (and auto-desc desc)
10233 (read-string "Description: " desc)))))
10235 (unless (string-match "\\S-" desc) (setq desc nil))
10236 (if remove (apply 'delete-region remove))
10237 (insert (org-make-link-string link desc))))
10239 (defun org-link-try-special-completion (type)
10240 "If there is completion support for link type TYPE, offer it."
10241 (let ((fun (intern (concat "org-" type "-complete-link"))))
10242 (if (functionp fun)
10243 (funcall fun)
10244 (read-string "Link (no completion support): " (concat type ":")))))
10246 (defun org-file-complete-link (&optional arg)
10247 "Create a file link using completion."
10248 (let (file link)
10249 (setq file (org-iread-file-name "File: "))
10250 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10251 (pwd1 (file-name-as-directory (abbreviate-file-name
10252 (expand-file-name ".")))))
10253 (cond
10254 ((equal arg '(16))
10255 (setq link (concat
10256 "file:"
10257 (abbreviate-file-name (expand-file-name file)))))
10258 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10259 (setq link (concat "file:" (match-string 1 file))))
10260 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10261 (expand-file-name file))
10262 (setq link (concat
10263 "file:" (match-string 1 (expand-file-name file)))))
10264 (t (setq link (concat "file:" file)))))
10265 link))
10267 (defun org-iread-file-name (&rest args)
10268 "Read-file-name using `ido-mode' speedup if available.
10269 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10270 See `read-file-name' for a description of parameters."
10271 (org-without-partial-completion
10272 (if (and org-completion-use-ido
10273 (fboundp 'ido-read-file-name)
10274 (boundp 'ido-mode) ido-mode
10275 (listp (second args)))
10276 (let ((ido-enter-matching-directory nil))
10277 (apply 'ido-read-file-name args))
10278 (apply 'read-file-name args))))
10280 (defun org-completing-read (&rest args)
10281 "Completing-read with SPACE being a normal character."
10282 (let ((enable-recursive-minibuffers t)
10283 (minibuffer-local-completion-map
10284 (copy-keymap minibuffer-local-completion-map)))
10285 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10286 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10287 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10288 (apply 'org-icompleting-read args)))
10290 (defun org-completing-read-no-i (&rest args)
10291 (let (org-completion-use-ido org-completion-use-iswitchb)
10292 (apply 'org-completing-read args)))
10294 (defun org-iswitchb-completing-read (prompt choices &rest args)
10295 "Use iswitch as a completing-read replacement to choose from choices.
10296 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10297 from."
10298 (let* ((iswitchb-use-virtual-buffers nil)
10299 (iswitchb-make-buflist-hook
10300 (lambda ()
10301 (setq iswitchb-temp-buflist choices))))
10302 (iswitchb-read-buffer prompt)))
10304 (defun org-icompleting-read (&rest args)
10305 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10306 (org-without-partial-completion
10307 (if (and org-completion-use-ido
10308 (fboundp 'ido-completing-read)
10309 (boundp 'ido-mode) ido-mode
10310 (listp (second args)))
10311 (let ((ido-enter-matching-directory nil))
10312 (apply 'ido-completing-read (concat (car args))
10313 (if (consp (car (nth 1 args)))
10314 (mapcar 'car (nth 1 args))
10315 (nth 1 args))
10316 (cddr args)))
10317 (if (and org-completion-use-iswitchb
10318 (boundp 'iswitchb-mode) iswitchb-mode
10319 (listp (second args)))
10320 (apply 'org-iswitchb-completing-read (concat (car args))
10321 (if (consp (car (nth 1 args)))
10322 (mapcar 'car (nth 1 args))
10323 (nth 1 args))
10324 (cddr args))
10325 (apply 'completing-read args)))))
10327 (defun org-extract-attributes (s)
10328 "Extract the attributes cookie from a string and set as text property."
10329 (let (a attr (start 0) key value)
10330 (save-match-data
10331 (when (string-match "{{\\([^}]+\\)}}$" s)
10332 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10333 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10334 (setq key (match-string 1 a) value (match-string 2 a)
10335 start (match-end 0)
10336 attr (plist-put attr (intern key) value))))
10337 (org-add-props s nil 'org-attr attr))
10340 ;;; Opening/following a link
10342 (defvar org-link-search-failed nil)
10344 (defvar org-open-link-functions nil
10345 "Hook for functions finding a plain text link.
10346 These functions must take a single argument, the link content.
10347 They will be called for links that look like [[link text][description]]
10348 when LINK TEXT does not have a protocol like \"http:\" and does not look
10349 like a filename (e.g. \"./blue.png\").
10351 These functions will be called *before* Org attempts to resolve the
10352 link by doing text searches in the current buffer - so if you want a
10353 link \"[[target]]\" to still find \"<<target>>\", your function should
10354 handle this as a special case.
10356 When the function does handle the link, it must return a non-nil value.
10357 If it decides that it is not responsible for this link, it must return
10358 nil to indicate that that Org-mode can continue with other options
10359 like exact and fuzzy text search.")
10361 (defun org-next-link (&optional search-backward)
10362 "Move forward to the next link.
10363 If the link is in hidden text, expose it."
10364 (interactive "P")
10365 (when (and org-link-search-failed (eq this-command last-command))
10366 (goto-char (point-min))
10367 (message "Link search wrapped back to beginning of buffer"))
10368 (setq org-link-search-failed nil)
10369 (let* ((pos (point))
10370 (ct (org-context))
10371 (a (assoc :link ct))
10372 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10373 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10374 ((looking-at org-any-link-re)
10375 ;; Don't stay stuck at link without an org-link face
10376 (forward-char (if search-backward -1 1))))
10377 (if (funcall srch-fun org-any-link-re nil t)
10378 (progn
10379 (goto-char (match-beginning 0))
10380 (if (outline-invisible-p) (org-show-context)))
10381 (goto-char pos)
10382 (setq org-link-search-failed t)
10383 (message "No further link found"))))
10385 (defun org-previous-link ()
10386 "Move backward to the previous link.
10387 If the link is in hidden text, expose it."
10388 (interactive)
10389 (funcall 'org-next-link t))
10391 (defun org-translate-link (s)
10392 "Translate a link string if a translation function has been defined."
10393 (if (and org-link-translation-function
10394 (fboundp org-link-translation-function)
10395 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10396 (progn
10397 (setq s (funcall org-link-translation-function
10398 (match-string 1 s) (match-string 2 s)))
10399 (concat (car s) ":" (cdr s)))
10402 (defun org-translate-link-from-planner (type path)
10403 "Translate a link from Emacs Planner syntax so that Org can follow it.
10404 This is still an experimental function, your mileage may vary."
10405 (cond
10406 ((member type '("http" "https" "news" "ftp"))
10407 ;; standard Internet links are the same.
10408 nil)
10409 ((and (equal type "irc") (string-match "^//" path))
10410 ;; Planner has two / at the beginning of an irc link, we have 1.
10411 ;; We should have zero, actually....
10412 (setq path (substring path 1)))
10413 ((and (equal type "lisp") (string-match "^/" path))
10414 ;; Planner has a slash, we do not.
10415 (setq type "elisp" path (substring path 1)))
10416 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10417 ;; A typical message link. Planner has the id after the final slash,
10418 ;; we separate it with a hash mark
10419 (setq path (concat (match-string 1 path) "#"
10420 (org-remove-angle-brackets (match-string 2 path))))))
10421 (cons type path))
10423 (defun org-find-file-at-mouse (ev)
10424 "Open file link or URL at mouse."
10425 (interactive "e")
10426 (mouse-set-point ev)
10427 (org-open-at-point 'in-emacs))
10429 (defun org-open-at-mouse (ev)
10430 "Open file link or URL at mouse.
10431 See the docstring of `org-open-file' for details."
10432 (interactive "e")
10433 (mouse-set-point ev)
10434 (if (eq major-mode 'org-agenda-mode)
10435 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10436 (org-open-at-point))
10438 (defvar org-window-config-before-follow-link nil
10439 "The window configuration before following a link.
10440 This is saved in case the need arises to restore it.")
10442 (defvar org-open-link-marker (make-marker)
10443 "Marker pointing to the location where `org-open-at-point' was called.")
10445 ;;;###autoload
10446 (defun org-open-at-point-global ()
10447 "Follow a link like Org-mode does.
10448 This command can be called in any mode to follow a link that has
10449 Org-mode syntax."
10450 (interactive)
10451 (org-run-like-in-org-mode 'org-open-at-point))
10453 ;;;###autoload
10454 (defun org-open-link-from-string (s &optional arg reference-buffer)
10455 "Open a link in the string S, as if it was in Org-mode."
10456 (interactive "sLink: \nP")
10457 (let ((reference-buffer (or reference-buffer (current-buffer))))
10458 (with-temp-buffer
10459 (let ((org-inhibit-startup (not reference-buffer)))
10460 (org-mode)
10461 (insert s)
10462 (goto-char (point-min))
10463 (when reference-buffer
10464 (setq org-link-abbrev-alist-local
10465 (with-current-buffer reference-buffer
10466 org-link-abbrev-alist-local)))
10467 (org-open-at-point arg reference-buffer)))))
10469 (defvar org-open-at-point-functions nil
10470 "Hook that is run when following a link at point.
10472 Functions in this hook must return t if they identify and follow
10473 a link at point. If they don't find anything interesting at point,
10474 they must return nil.")
10476 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10477 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10478 (defun org-open-at-point (&optional arg reference-buffer)
10479 "Open link, timestamp, footnote or tags at point.
10481 When point is on a link, follow it. Normally, files will be
10482 opened by an appropriate application. If the optional prefix
10483 argument ARG is non-nil, Emacs will visit the file. With
10484 a double prefix argument, try to open outside of Emacs, in the
10485 application the system uses for this file type.
10487 When point is on a timestamp, open the agenda at the day
10488 specified.
10490 When point is a footnote definition, move to the first reference
10491 found. If it is on a reference, move to the associated
10492 definition.
10494 When point is on a headline, display a list of every link in the
10495 entry, so it is possible to pick one, or all, of them. If point
10496 is on a tag, call `org-tags-view' instead.
10498 When optional argument REFERENCE-BUFFER is non-nil, it should
10499 specify a buffer from where the link search should happen. This
10500 is used internally by `org-open-link-from-string'."
10501 (interactive "P")
10502 ;; On a code block, open block's results.
10503 (unless (call-interactively #'org-babel-open-src-block-result)
10504 (org-load-modules-maybe)
10505 (move-marker org-open-link-marker (point))
10506 (setq org-window-config-before-follow-link (current-window-configuration))
10507 (org-remove-occur-highlights nil nil t)
10508 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10509 (let* ((context (org-element-context)) type)
10510 ;; On an unsupported type, check if point is contained within
10511 ;; a support one.
10512 (while (and (not (memq (setq type (org-element-type context))
10513 '(headline inlinetask link footnote-definition
10514 footnote-reference timestamp)))
10515 (setq context (org-element-property :parent context))))
10516 (cond
10517 ;; Unsupported context: return an error.
10518 ((not context) (user-error "No link found"))
10519 ;; On a headline or an inlinetask, but not on a timestamp,
10520 ;; a link, a footnote reference or on tags.
10521 ((and (memq type '(headline inlinetask))
10522 ;; Not on tags.
10523 (progn (save-excursion (beginning-of-line)
10524 (looking-at org-complex-heading-regexp))
10525 (or (not (match-beginning 5))
10526 (< (point) (match-beginning 5)))))
10527 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10528 (links (car data))
10529 (links-end (cdr data)))
10530 (if links
10531 (dolist (link (if (stringp links) (list links) links))
10532 (search-forward link nil links-end)
10533 (goto-char (match-beginning 0))
10534 (org-open-at-point))
10535 (require 'org-attach)
10536 (org-attach-reveal 'if-exists))))
10537 ;; Do nothing on white spaces after an object, unless point
10538 ;; is right after it.
10539 ((> (point)
10540 (save-excursion
10541 (goto-char (org-element-property :end context))
10542 (skip-chars-backward " \t")
10543 (point)))
10544 (user-error "No link found"))
10545 ((eq type 'timestamp) (org-follow-timestamp-link))
10546 ;; On tags within a headline or an inlinetask.
10547 ((and (memq type '(headline inlinetask))
10548 (progn (save-excursion (beginning-of-line)
10549 (looking-at org-complex-heading-regexp))
10550 (and (match-beginning 5)
10551 (>= (point) (match-beginning 5)))))
10552 (org-tags-view arg (substring (match-string 5) 0 -1)))
10553 ((eq type 'link)
10554 (let ((type (org-element-property :type context))
10555 (path (org-link-unescape (org-element-property :path context))))
10556 ;; Switch back to REFERENCE-BUFFER needed when called in
10557 ;; a temporary buffer through `org-open-link-from-string'.
10558 (with-current-buffer (or reference-buffer (current-buffer))
10559 (cond
10560 ((equal type "file")
10561 (if (string-match "[*?{]" (file-name-nondirectory path))
10562 (dired path)
10563 ;; Look into `org-link-protocols' in order to find
10564 ;; a DEDICATED-FUNCTION to open file. The function
10565 ;; will be applied on raw link instead of parsed
10566 ;; link due to the limitation in `org-add-link-type'
10567 ;; ("open" function called with a single argument).
10568 ;; If no such function is found, fallback to
10569 ;; `org-open-file'.
10571 ;; Note : "file+emacs" and "file+sys" types are
10572 ;; hard-coded in order to escape the previous
10573 ;; limitation.
10574 (let* ((option (org-element-property :search-option context))
10575 (app (org-element-property :application context))
10576 (dedicated-function
10577 (nth 1 (assoc app org-link-protocols))))
10578 (if dedicated-function
10579 (funcall dedicated-function
10580 (concat path
10581 (and option (concat "::" option))))
10582 (apply #'org-open-file
10583 path
10584 (cond (arg)
10585 ((equal app "emacs") 'emacs)
10586 ((equal app "sys") 'system))
10587 (cond ((not option) nil)
10588 ((org-string-match-p "\\`[0-9]+\\'" option)
10589 (list (string-to-number option)))
10590 (t (list nil
10591 (org-link-unescape option)))))))))
10592 ((assoc type org-link-protocols)
10593 (funcall (nth 1 (assoc type org-link-protocols)) path))
10594 ((equal type "help")
10595 (let ((f-or-v (intern path)))
10596 (cond ((fboundp f-or-v) (describe-function f-or-v))
10597 ((boundp f-or-v) (describe-variable f-or-v))
10598 (t (error "Not a known function or variable")))))
10599 ((equal type "mailto")
10600 (let ((cmd (car org-link-mailto-program))
10601 (args (cdr org-link-mailto-program))
10602 (spec
10603 (format-spec-make
10604 ?a path ; %a is address.
10605 ?s (let ((option ; %s is subject.
10606 (org-element-property
10607 :search-option context)))
10608 (if (not option) "" (org-link-escape option)))))
10609 final-args)
10610 (apply cmd
10611 (dolist (arg args (nreverse final-args))
10612 (if (not (stringp arg)) (push arg final-args)
10613 (push (format-spec arg spec) final-args))))))
10614 ((member type '("http" "https" "ftp" "news"))
10615 (browse-url (org-link-escape-browser (concat type ":" path))))
10616 ((equal type "doi")
10617 (browse-url
10618 (org-link-escape-browser (concat org-doi-server-url path))))
10619 ((equal type "message") (browse-url (concat type ":" path)))
10620 ((equal type "shell")
10621 (let ((buf (generate-new-buffer "*Org Shell Output"))
10622 (cmd path))
10623 (if (or (and (org-string-nw-p
10624 org-confirm-shell-link-not-regexp)
10625 (string-match
10626 org-confirm-shell-link-not-regexp cmd))
10627 (not org-confirm-shell-link-function)
10628 (funcall org-confirm-shell-link-function
10629 (format "Execute \"%s\" in shell? "
10630 (org-add-props cmd nil
10631 'face 'org-warning))))
10632 (progn
10633 (message "Executing %s" cmd)
10634 (shell-command cmd buf)
10635 (when (featurep 'midnight)
10636 (setq clean-buffer-list-kill-buffer-names
10637 (cons buf
10638 clean-buffer-list-kill-buffer-names))))
10639 (error "Abort"))))
10640 ((equal type "elisp")
10641 (let ((cmd path))
10642 (if (or (and (org-string-nw-p
10643 org-confirm-elisp-link-not-regexp)
10644 (org-string-match-p
10645 org-confirm-elisp-link-not-regexp cmd))
10646 (not org-confirm-elisp-link-function)
10647 (funcall org-confirm-elisp-link-function
10648 (format "Execute \"%s\" as elisp? "
10649 (org-add-props cmd nil
10650 'face 'org-warning))))
10651 (message "%s => %s" cmd
10652 (if (eq (string-to-char cmd) ?\()
10653 (eval (read cmd))
10654 (call-interactively (read cmd))))
10655 (error "Abort"))))
10656 ((equal type "id")
10657 (require 'ord-id)
10658 (funcall (nth 1 (assoc "id" org-link-protocols)) path))
10659 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10660 (unless (run-hook-with-args-until-success
10661 'org-open-link-functions path)
10662 (if (not arg) (org-mark-ring-push)
10663 (switch-to-buffer-other-window
10664 (org-get-buffer-for-internal-link (current-buffer))))
10665 (let ((cmd `(org-link-search
10666 ,(if (member type '("custom-id" "coderef"))
10667 (org-element-property :raw-link context)
10668 path)
10669 ,(cond ((equal arg '(4)) 'occur)
10670 ((equal arg '(16)) 'org-occur))
10671 ,(org-element-property :begin context))))
10672 (condition-case nil
10673 (let ((org-link-search-inhibit-query t))
10674 (eval cmd))
10675 (error (progn (widen) (eval cmd)))))))
10676 (t (browse-url-at-point))))))
10677 ;; On a footnote reference or at a footnote definition's label.
10678 ((or (eq type 'footnote-reference)
10679 (and (eq type 'footnote-definition)
10680 (save-excursion
10681 ;; Do not validate action when point is on the
10682 ;; spaces right after the footnote label, in
10683 ;; order to be on par with behaviour on links.
10684 (skip-chars-forward " \t")
10685 (let ((begin
10686 (org-element-property :contents-begin context)))
10687 (if begin (< (point) begin)
10688 (= (org-element-property :post-affiliated context)
10689 (line-beginning-position)))))))
10690 (org-footnote-action))
10691 (t (user-error "No link found")))))
10692 (move-marker org-open-link-marker nil)
10693 (run-hook-with-args 'org-follow-link-hook)))
10695 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10696 "Offer links in the current entry and return the selected link.
10697 If there is only one link, return it.
10698 If NTH is an integer, return the NTH link found.
10699 If ZERO is a string, check also this string for a link, and if
10700 there is one, return it."
10701 (with-current-buffer buffer
10702 (save-excursion
10703 (save-restriction
10704 (widen)
10705 (goto-char marker)
10706 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10707 "\\(" org-angle-link-re "\\)\\|"
10708 "\\(" org-plain-link-re "\\)"))
10709 (cnt ?0)
10710 (in-emacs (if (integerp nth) nil nth))
10711 have-zero end links link c)
10712 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10713 (push (match-string 0 zero) links)
10714 (setq cnt (1- cnt) have-zero t))
10715 (save-excursion
10716 (org-back-to-heading t)
10717 (setq end (save-excursion (outline-next-heading) (point)))
10718 (while (re-search-forward re end t)
10719 (push (match-string 0) links))
10720 (setq links (org-uniquify (reverse links))))
10721 (cond
10722 ((null links)
10723 (message "No links"))
10724 ((equal (length links) 1)
10725 (setq link (car links)))
10726 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10727 (setq link (nth (if have-zero nth (1- nth)) links)))
10728 (t ; we have to select a link
10729 (save-excursion
10730 (save-window-excursion
10731 (delete-other-windows)
10732 (with-output-to-temp-buffer "*Select Link*"
10733 (mapc (lambda (l)
10734 (if (not (string-match org-bracket-link-regexp l))
10735 (princ (format "[%c] %s\n" (incf cnt)
10736 (org-remove-angle-brackets l)))
10737 (if (match-end 3)
10738 (princ (format "[%c] %s (%s)\n" (incf cnt)
10739 (match-string 3 l) (match-string 1 l)))
10740 (princ (format "[%c] %s\n" (incf cnt)
10741 (match-string 1 l))))))
10742 links))
10743 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10744 (message "Select link to open, RET to open all:")
10745 (setq c (read-char-exclusive))
10746 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10747 (when (equal c ?q) (error "Abort"))
10748 (if (equal c ?\C-m)
10749 (setq link links)
10750 (setq nth (- c ?0))
10751 (if have-zero (setq nth (1+ nth)))
10752 (unless (and (integerp nth) (>= (length links) nth))
10753 (user-error "Invalid link selection"))
10754 (setq link (nth (1- nth) links)))))
10755 (cons link end))))))
10757 ;; TODO: These functions are deprecated since `org-open-at-point'
10758 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10759 (defun org-open-file-with-system (path)
10760 "Open file at PATH using the system way of opening it."
10761 (org-open-file path 'system))
10762 (defun org-open-file-with-emacs (path)
10763 "Open file at PATH in Emacs."
10764 (org-open-file path 'emacs))
10767 ;;; File search
10769 (defvar org-create-file-search-functions nil
10770 "List of functions to construct the right search string for a file link.
10771 These functions are called in turn with point at the location to
10772 which the link should point.
10774 A function in the hook should first test if it would like to
10775 handle this file type, for example by checking the `major-mode'
10776 or the file extension. If it decides not to handle this file, it
10777 should just return nil to give other functions a chance. If it
10778 does handle the file, it must return the search string to be used
10779 when following the link. The search string will be part of the
10780 file link, given after a double colon, and `org-open-at-point'
10781 will automatically search for it. If special measures must be
10782 taken to make the search successful, another function should be
10783 added to the companion hook `org-execute-file-search-functions',
10784 which see.
10786 A function in this hook may also use `setq' to set the variable
10787 `description' to provide a suggestion for the descriptive text to
10788 be used for this link when it gets inserted into an Org-mode
10789 buffer with \\[org-insert-link].")
10791 (defvar org-execute-file-search-functions nil
10792 "List of functions to execute a file search triggered by a link.
10794 Functions added to this hook must accept a single argument, the
10795 search string that was part of the file link, the part after the
10796 double colon. The function must first check if it would like to
10797 handle this search, for example by checking the `major-mode' or
10798 the file extension. If it decides not to handle this search, it
10799 should just return nil to give other functions a chance. If it
10800 does handle the search, it must return a non-nil value to keep
10801 other functions from trying.
10803 Each function can access the current prefix argument through the
10804 variable `current-prefix-arg'. Note that a single prefix is used
10805 to force opening a link in Emacs, so it may be good to only use a
10806 numeric or double prefix to guide the search function.
10808 In case this is needed, a function in this hook can also restore
10809 the window configuration before `org-open-at-point' was called using:
10811 (set-window-configuration org-window-config-before-follow-link)")
10813 (defun org-link-search (s &optional type avoid-pos stealth)
10814 "Search for a link search option.
10815 If S is surrounded by forward slashes, it is interpreted as a
10816 regular expression. In org-mode files, this will create an `org-occur'
10817 sparse tree. In ordinary files, `occur' will be used to list matches.
10818 If the current buffer is in `dired-mode', grep will be used to search
10819 in all files. If AVOID-POS is given, ignore matches near that position.
10821 When optional argument STEALTH is non-nil, do not modify
10822 visibility around point, thus ignoring
10823 `org-show-hierarchy-above', `org-show-following-heading' and
10824 `org-show-siblings' variables."
10825 (let ((case-fold-search t)
10826 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10827 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10828 (append '(("") (" ") ("\t") ("\n"))
10829 org-emphasis-alist)
10830 "\\|") "\\)"))
10831 (pos (point))
10832 (pre nil) (post nil)
10833 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10834 (cond
10835 ;; First check if there are any special search functions
10836 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10837 ;; Now try the builtin stuff
10838 ((and (equal (string-to-char s0) ?#)
10839 (> (length s0) 1)
10840 (save-excursion
10841 (goto-char (point-min))
10842 (and
10843 (re-search-forward
10844 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10845 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10846 (setq type 'dedicated
10847 pos (match-beginning 0))))
10848 ;; There is an exact target for this
10849 (goto-char pos)
10850 (org-back-to-heading t)))
10851 ((save-excursion
10852 (goto-char (point-min))
10853 (and
10854 (re-search-forward
10855 (concat "<<" (regexp-quote s0) ">>") nil t)
10856 (setq type 'dedicated
10857 pos (match-beginning 0))))
10858 ;; There is an exact target for this
10859 (goto-char pos))
10860 ((save-excursion
10861 (goto-char (point-min))
10862 (and
10863 (re-search-forward
10864 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10865 (setq type 'dedicated pos (match-beginning 0))))
10866 ;; Found an element with a matching #+name affiliated keyword.
10867 (goto-char pos))
10868 ((and (string-match "^(\\(.*\\))$" s0)
10869 (save-excursion
10870 (goto-char (point-min))
10871 (and
10872 (re-search-forward
10873 (concat "[^[]" (regexp-quote
10874 (format org-coderef-label-format
10875 (match-string 1 s0))))
10876 nil t)
10877 (setq type 'dedicated
10878 pos (1+ (match-beginning 0))))))
10879 ;; There is a coderef target for this
10880 (goto-char pos))
10881 ((string-match "^/\\(.*\\)/$" s)
10882 ;; A regular expression
10883 (cond
10884 ((derived-mode-p 'org-mode)
10885 (org-occur (match-string 1 s)))
10886 (t (org-do-occur (match-string 1 s)))))
10887 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10888 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10889 (goto-char (point-min))
10890 (cond
10891 ((let (case-fold-search)
10892 (re-search-forward (format org-complex-heading-regexp-format
10893 (regexp-quote s))
10894 nil t))
10895 ;; OK, found a match
10896 (setq type 'dedicated)
10897 (goto-char (match-beginning 0)))
10898 ((and (not org-link-search-inhibit-query)
10899 (eq org-link-search-must-match-exact-headline 'query-to-create)
10900 (y-or-n-p "No match - create this as a new heading? "))
10901 (goto-char (point-max))
10902 (or (bolp) (newline))
10903 (insert "* " s "\n")
10904 (beginning-of-line 0))
10906 (goto-char pos)
10907 (error "No match"))))
10909 ;; A normal search string
10910 (when (equal (string-to-char s) ?*)
10911 ;; Anchor on headlines, post may include tags.
10912 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10913 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10914 s (substring s 1)))
10915 (remove-text-properties
10916 0 (length s)
10917 '(face nil mouse-face nil keymap nil fontified nil) s)
10918 ;; Make a series of regular expressions to find a match
10919 (setq words (org-split-string s "[ \n\r\t]+")
10921 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10922 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10923 "\\)" markers)
10924 re2a_ (concat "\\(" (mapconcat 'downcase words
10925 "[ \t\r\n]+") "\\)[ \t\r\n]")
10926 re2a (concat "[ \t\r\n]" re2a_)
10927 re4_ (concat "\\(" (mapconcat 'downcase words
10928 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10929 re4 (concat "[^a-zA-Z_]" re4_)
10931 re1 (concat pre re2 post)
10932 re3 (concat pre (if pre re4_ re4) post)
10933 re5 (concat pre ".*" re4)
10934 re2 (concat pre re2)
10935 re2a (concat pre (if pre re2a_ re2a))
10936 re4 (concat pre (if pre re4_ re4))
10937 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10938 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10939 re5 "\\)"))
10940 (cond
10941 ((eq type 'org-occur) (org-occur reall))
10942 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10943 (t (goto-char (point-min))
10944 (setq type 'fuzzy)
10945 (if (or (and (org-search-not-self 1 re0 nil t)
10946 (setq type 'dedicated))
10947 (org-search-not-self 1 re1 nil t)
10948 (org-search-not-self 1 re2 nil t)
10949 (org-search-not-self 1 re2a nil t)
10950 (org-search-not-self 1 re3 nil t)
10951 (org-search-not-self 1 re4 nil t)
10952 (org-search-not-self 1 re5 nil t))
10953 (goto-char (match-beginning 1))
10954 (goto-char pos)
10955 (error "No match"))))))
10956 (and (derived-mode-p 'org-mode)
10957 (not stealth)
10958 (org-show-context 'link-search))
10959 type))
10961 (defun org-search-not-self (group &rest args)
10962 "Execute `re-search-forward', but only accept matches that do not
10963 enclose the position of `org-open-link-marker'."
10964 (let ((m org-open-link-marker))
10965 (catch 'exit
10966 (while (apply 're-search-forward args)
10967 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10968 (goto-char (match-end group))
10969 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10970 (> (match-beginning 0) (marker-position m))
10971 (< (match-end 0) (marker-position m)))
10972 (save-match-data
10973 (or (not (org-in-regexp
10974 org-bracket-link-analytic-regexp 1))
10975 (not (match-end 4)) ; no description
10976 (and (<= (match-beginning 4) (point))
10977 (>= (match-end 4) (point))))))
10978 (throw 'exit (point))))))))
10980 (defun org-get-buffer-for-internal-link (buffer)
10981 "Return a buffer to be used for displaying the link target of internal links."
10982 (cond
10983 ((not org-display-internal-link-with-indirect-buffer)
10984 buffer)
10985 ((string-match "(Clone)$" (buffer-name buffer))
10986 (message "Buffer is already a clone, not making another one")
10987 ;; we also do not modify visibility in this case
10988 buffer)
10989 (t ; make a new indirect buffer for displaying the link
10990 (let* ((bn (buffer-name buffer))
10991 (ibn (concat bn "(Clone)"))
10992 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10993 (with-current-buffer ib (org-overview))
10994 ib))))
10996 (defun org-do-occur (regexp &optional cleanup)
10997 "Call the Emacs command `occur'.
10998 If CLEANUP is non-nil, remove the printout of the regular expression
10999 in the *Occur* buffer. This is useful if the regex is long and not useful
11000 to read."
11001 (occur regexp)
11002 (when cleanup
11003 (let ((cwin (selected-window)) win beg end)
11004 (when (setq win (get-buffer-window "*Occur*"))
11005 (select-window win))
11006 (goto-char (point-min))
11007 (when (re-search-forward "match[a-z]+" nil t)
11008 (setq beg (match-end 0))
11009 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
11010 (setq end (1- (match-beginning 0)))))
11011 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11012 (goto-char (point-min))
11013 (select-window cwin))))
11015 ;;; The mark ring for links jumps
11017 (defvar org-mark-ring nil
11018 "Mark ring for positions before jumps in Org-mode.")
11019 (defvar org-mark-ring-last-goto nil
11020 "Last position in the mark ring used to go back.")
11021 ;; Fill and close the ring
11022 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11023 (loop for i from 1 to org-mark-ring-length do
11024 (push (make-marker) org-mark-ring))
11025 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11026 org-mark-ring)
11028 (defun org-mark-ring-push (&optional pos buffer)
11029 "Put the current position or POS into the mark ring and rotate it."
11030 (interactive)
11031 (setq pos (or pos (point)))
11032 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11033 (move-marker (car org-mark-ring)
11034 (or pos (point))
11035 (or buffer (current-buffer)))
11036 (message "%s"
11037 (substitute-command-keys
11038 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
11040 (defun org-mark-ring-goto (&optional n)
11041 "Jump to the previous position in the mark ring.
11042 With prefix arg N, jump back that many stored positions. When
11043 called several times in succession, walk through the entire ring.
11044 Org-mode commands jumping to a different position in the current file,
11045 or to another Org-mode file, automatically push the old position
11046 onto the ring."
11047 (interactive "p")
11048 (let (p m)
11049 (if (eq last-command this-command)
11050 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11051 (setq p org-mark-ring))
11052 (setq org-mark-ring-last-goto p)
11053 (setq m (car p))
11054 (org-pop-to-buffer-same-window (marker-buffer m))
11055 (goto-char m)
11056 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11058 (defun org-remove-angle-brackets (s)
11059 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
11060 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
11062 (defun org-add-angle-brackets (s)
11063 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
11064 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
11066 (defun org-remove-double-quotes (s)
11067 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
11068 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
11071 ;;; Following specific links
11073 (defun org-follow-timestamp-link ()
11074 "Open an agenda view for the time-stamp date/range at point."
11075 (cond
11076 ((org-at-date-range-p t)
11077 (let ((org-agenda-start-on-weekday)
11078 (t1 (match-string 1))
11079 (t2 (match-string 2)) tt1 tt2)
11080 (setq tt1 (time-to-days (org-time-string-to-time t1))
11081 tt2 (time-to-days (org-time-string-to-time t2)))
11082 (let ((org-agenda-buffer-tmp-name
11083 (format "*Org Agenda(a:%s)"
11084 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11085 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11086 ((org-at-timestamp-p t)
11087 (let ((org-agenda-buffer-tmp-name
11088 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11089 (org-agenda-list nil (time-to-days (org-time-string-to-time
11090 (substring (match-string 1) 0 10)))
11091 1)))
11092 (t (error "This should not happen"))))
11095 ;;; Following file links
11096 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11097 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11098 (declare-function mailcap-mime-info
11099 "mailcap" (string &optional request no-decode))
11100 (defvar org-wait nil)
11101 (defun org-open-file (path &optional in-emacs line search)
11102 "Open the file at PATH.
11103 First, this expands any special file name abbreviations. Then the
11104 configuration variable `org-file-apps' is checked if it contains an
11105 entry for this file type, and if yes, the corresponding command is launched.
11107 If no application is found, Emacs simply visits the file.
11109 With optional prefix argument IN-EMACS, Emacs will visit the file.
11110 With a double \\[universal-argument] \\[universal-argument] \
11111 prefix arg, Org tries to avoid opening in Emacs
11112 and to use an external application to visit the file.
11114 Optional LINE specifies a line to go to, optional SEARCH a string
11115 to search for. If LINE or SEARCH is given, the file will be
11116 opened in Emacs, unless an entry from org-file-apps that makes
11117 use of groups in a regexp matches.
11119 If you want to change the way frames are used when following a
11120 link, please customize `org-link-frame-setup'.
11122 If the file does not exist, an error is thrown."
11123 (let* ((file (if (equal path "")
11124 buffer-file-name
11125 (substitute-in-file-name (expand-file-name path))))
11126 (file-apps (append org-file-apps (org-default-apps)))
11127 (apps (org-remove-if
11128 'org-file-apps-entry-match-against-dlink-p file-apps))
11129 (apps-dlink (org-remove-if-not
11130 'org-file-apps-entry-match-against-dlink-p file-apps))
11131 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11132 (dirp (if remp nil (file-directory-p file)))
11133 (file (if (and dirp org-open-directory-means-index-dot-org)
11134 (concat (file-name-as-directory file) "index.org")
11135 file))
11136 (a-m-a-p (assq 'auto-mode apps))
11137 (dfile (downcase file))
11138 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
11139 (link (cond ((and (eq line nil)
11140 (eq search nil))
11141 file)
11142 (line
11143 (concat file "::" (number-to-string line)))
11144 (search
11145 (concat file "::" search))))
11146 (dlink (downcase link))
11147 (old-buffer (current-buffer))
11148 (old-pos (point))
11149 (old-mode major-mode)
11150 ext cmd link-match-data)
11151 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11152 (setq ext (match-string 1 dfile))
11153 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11154 (setq ext (match-string 1 dfile))))
11155 (cond
11156 ((member in-emacs '((16) system))
11157 (setq cmd (cdr (assoc 'system apps))))
11158 (in-emacs (setq cmd 'emacs))
11160 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11161 (and dirp (cdr (assoc 'directory apps)))
11162 ; first, try matching against apps-dlink
11163 ; if we get a match here, store the match data for later
11164 (let ((match (assoc-default dlink apps-dlink
11165 'string-match)))
11166 (if match
11167 (progn (setq link-match-data (match-data))
11168 match)
11169 (progn (setq in-emacs (or in-emacs line search))
11170 nil))) ; if we have no match in apps-dlink,
11171 ; always open the file in emacs if line or search
11172 ; is given (for backwards compatibility)
11173 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11174 'string-match)
11175 (cdr (assoc ext apps))
11176 (cdr (assoc t apps))))))
11177 (when (eq cmd 'system)
11178 (setq cmd (cdr (assoc 'system apps))))
11179 (when (eq cmd 'default)
11180 (setq cmd (cdr (assoc t apps))))
11181 (when (eq cmd 'mailcap)
11182 (require 'mailcap)
11183 (mailcap-parse-mailcaps)
11184 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11185 (command (mailcap-mime-info mime-type)))
11186 (if (stringp command)
11187 (setq cmd command)
11188 (setq cmd 'emacs))))
11189 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11190 (not (file-exists-p file))
11191 (not org-open-non-existing-files))
11192 (user-error "No such file: %s" file))
11193 (cond
11194 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11195 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11196 (while (string-match "['\"]%s['\"]" cmd)
11197 (setq cmd (replace-match "%s" t t cmd)))
11198 (while (string-match "%s" cmd)
11199 (setq cmd (replace-match
11200 (save-match-data
11201 (shell-quote-argument
11202 (convert-standard-filename file)))
11203 t t cmd)))
11205 ;; Replace "%1", "%2" etc. in command with group matches from regex
11206 (save-match-data
11207 (let ((match-index 1)
11208 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11209 (set-match-data link-match-data)
11210 (while (<= match-index number-of-groups)
11211 (let ((regex (concat "%" (number-to-string match-index)))
11212 (replace-with (match-string match-index dlink)))
11213 (while (string-match regex cmd)
11214 (setq cmd (replace-match replace-with t t cmd))))
11215 (setq match-index (+ match-index 1)))))
11217 (save-window-excursion
11218 (message "Running %s...done" cmd)
11219 (start-process-shell-command cmd nil cmd)
11220 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11221 ((or (stringp cmd)
11222 (eq cmd 'emacs))
11223 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11224 (widen)
11225 (if line (progn (org-goto-line line)
11226 (if (derived-mode-p 'org-mode)
11227 (org-reveal)))
11228 (if search (org-link-search search))))
11229 ((consp cmd)
11230 (let ((file (convert-standard-filename file)))
11231 (save-match-data
11232 (set-match-data link-match-data)
11233 (eval cmd))))
11234 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11235 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11236 (or (not (equal old-buffer (current-buffer)))
11237 (not (equal old-pos (point))))
11238 (org-mark-ring-push old-pos old-buffer))))
11240 (defun org-file-apps-entry-match-against-dlink-p (entry)
11241 "This function returns non-nil if `entry' uses a regular
11242 expression which should be matched against the whole link by
11243 org-open-file.
11245 It assumes that is the case when the entry uses a regular
11246 expression which has at least one grouping construct and the
11247 action is either a lisp form or a command string containing
11248 '%1', i.e. using at least one subexpression match as a
11249 parameter."
11250 (let ((selector (car entry))
11251 (action (cdr entry)))
11252 (if (stringp selector)
11253 (and (> (regexp-opt-depth selector) 0)
11254 (or (and (stringp action)
11255 (string-match "%[0-9]" action))
11256 (consp action)))
11257 nil)))
11259 (defun org-default-apps ()
11260 "Return the default applications for this operating system."
11261 (cond
11262 ((eq system-type 'darwin)
11263 org-file-apps-defaults-macosx)
11264 ((eq system-type 'windows-nt)
11265 org-file-apps-defaults-windowsnt)
11266 (t org-file-apps-defaults-gnu)))
11268 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11269 "Convert extensions to regular expressions in the cars of LIST.
11270 Also, weed out any non-string entries, because the return value is used
11271 only for regexp matching.
11272 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11273 point to the symbol `emacs', indicating that the file should
11274 be opened in Emacs."
11275 (append
11276 (delq nil
11277 (mapcar (lambda (x)
11278 (if (not (stringp (car x)))
11280 (if (string-match "\\W" (car x))
11282 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11283 list))
11284 (if add-auto-mode
11285 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11287 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11288 (defun org-file-remote-p (file)
11289 "Test whether FILE specifies a location on a remote system.
11290 Return non-nil if the location is indeed remote.
11292 For example, the filename \"/user@host:/foo\" specifies a location
11293 on the system \"/user@host:\"."
11294 (cond ((fboundp 'file-remote-p)
11295 (file-remote-p file))
11296 ((fboundp 'tramp-handle-file-remote-p)
11297 (tramp-handle-file-remote-p file))
11298 ((and (boundp 'ange-ftp-name-format)
11299 (string-match (car ange-ftp-name-format) file))
11300 t)))
11303 ;;;; Refiling
11305 (defun org-get-org-file ()
11306 "Read a filename, with default directory `org-directory'."
11307 (let ((default (or org-default-notes-file remember-data-file)))
11308 (read-file-name (format "File name [%s]: " default)
11309 (file-name-as-directory org-directory)
11310 default)))
11312 (defun org-notes-order-reversed-p ()
11313 "Check if the current file should receive notes in reversed order."
11314 (cond
11315 ((not org-reverse-note-order) nil)
11316 ((eq t org-reverse-note-order) t)
11317 ((not (listp org-reverse-note-order)) nil)
11318 (t (catch 'exit
11319 (let ((all org-reverse-note-order)
11320 entry)
11321 (while (setq entry (pop all))
11322 (if (string-match (car entry) buffer-file-name)
11323 (throw 'exit (cdr entry))))
11324 nil)))))
11326 (defvar org-refile-target-table nil
11327 "The list of refile targets, created by `org-refile'.")
11329 (defvar org-agenda-new-buffers nil
11330 "Buffers created to visit agenda files.")
11332 (defvar org-refile-cache nil
11333 "Cache for refile targets.")
11335 (defvar org-refile-markers nil
11336 "All the markers used for caching refile locations.")
11338 (defun org-refile-marker (pos)
11339 "Get a new refile marker, but only if caching is in use."
11340 (if (not org-refile-use-cache)
11342 (let ((m (make-marker)))
11343 (move-marker m pos)
11344 (push m org-refile-markers)
11345 m)))
11347 (defun org-refile-cache-clear ()
11348 "Clear the refile cache and disable all the markers."
11349 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11350 (setq org-refile-markers nil)
11351 (setq org-refile-cache nil)
11352 (message "Refile cache has been cleared"))
11354 (defun org-refile-cache-check-set (set)
11355 "Check if all the markers in the cache still have live buffers."
11356 (let (marker)
11357 (catch 'exit
11358 (while (and set (setq marker (nth 3 (pop set))))
11359 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11360 (when (and marker (null (marker-buffer marker)))
11361 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11362 (sit-for 3)
11363 (throw 'exit nil)))
11364 t)))
11366 (defun org-refile-cache-put (set &rest identifiers)
11367 "Push the refile targets SET into the cache, under IDENTIFIERS."
11368 (let* ((key (sha1 (prin1-to-string identifiers)))
11369 (entry (assoc key org-refile-cache)))
11370 (if entry
11371 (setcdr entry set)
11372 (push (cons key set) org-refile-cache))))
11374 (defun org-refile-cache-get (&rest identifiers)
11375 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11376 (cond
11377 ((not org-refile-cache) nil)
11378 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11380 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11381 org-refile-cache))))
11382 (and set (org-refile-cache-check-set set) set)))))
11384 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11385 "Produce a table with refile targets."
11386 (let ((case-fold-search nil)
11387 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11388 (entries (or org-refile-targets '((nil . (:level . 1)))))
11389 targets tgs txt re files f desc descre fast-path-p level pos0)
11390 (message "Getting targets...")
11391 (with-current-buffer (or default-buffer (current-buffer))
11392 (while (setq entry (pop entries))
11393 (setq files (car entry) desc (cdr entry))
11394 (setq fast-path-p nil)
11395 (cond
11396 ((null files) (setq files (list (current-buffer))))
11397 ((eq files 'org-agenda-files)
11398 (setq files (org-agenda-files 'unrestricted)))
11399 ((and (symbolp files) (fboundp files))
11400 (setq files (funcall files)))
11401 ((and (symbolp files) (boundp files))
11402 (setq files (symbol-value files))))
11403 (if (stringp files) (setq files (list files)))
11404 (cond
11405 ((eq (car desc) :tag)
11406 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11407 ((eq (car desc) :todo)
11408 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11409 ((eq (car desc) :regexp)
11410 (setq descre (cdr desc)))
11411 ((eq (car desc) :level)
11412 (setq descre (concat "^\\*\\{" (number-to-string
11413 (if org-odd-levels-only
11414 (1- (* 2 (cdr desc)))
11415 (cdr desc)))
11416 "\\}[ \t]")))
11417 ((eq (car desc) :maxlevel)
11418 (setq fast-path-p t)
11419 (setq descre (concat "^\\*\\{1," (number-to-string
11420 (if org-odd-levels-only
11421 (1- (* 2 (cdr desc)))
11422 (cdr desc)))
11423 "\\}[ \t]")))
11424 (t (error "Bad refiling target description %s" desc)))
11425 (while (setq f (pop files))
11426 (with-current-buffer
11427 (if (bufferp f) f (org-get-agenda-file-buffer f))
11429 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11430 (progn
11431 (if (bufferp f) (setq f (buffer-file-name
11432 (buffer-base-buffer f))))
11433 (setq f (and f (expand-file-name f)))
11434 (if (eq org-refile-use-outline-path 'file)
11435 (push (list (file-name-nondirectory f) f nil nil) tgs))
11436 (save-excursion
11437 (save-restriction
11438 (widen)
11439 (goto-char (point-min))
11440 (while (re-search-forward descre nil t)
11441 (goto-char (setq pos0 (point-at-bol)))
11442 (catch 'next
11443 (when org-refile-target-verify-function
11444 (save-match-data
11445 (or (funcall org-refile-target-verify-function)
11446 (throw 'next t))))
11447 (when (and (looking-at org-complex-heading-regexp)
11448 (not (member (match-string 4) excluded-entries))
11449 (match-string 4))
11450 (setq level (org-reduced-level
11451 (- (match-end 1) (match-beginning 1)))
11452 txt (org-link-display-format (match-string 4))
11453 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11454 re (format org-complex-heading-regexp-format
11455 (regexp-quote (match-string 4))))
11456 (when org-refile-use-outline-path
11457 (setq txt (mapconcat
11458 'org-protect-slash
11459 (append
11460 (if (eq org-refile-use-outline-path
11461 'file)
11462 (list (file-name-nondirectory
11463 (buffer-file-name
11464 (buffer-base-buffer))))
11465 (if (eq org-refile-use-outline-path
11466 'full-file-path)
11467 (list (buffer-file-name
11468 (buffer-base-buffer)))))
11469 (org-get-outline-path fast-path-p
11470 level txt)
11471 (list txt))
11472 "/")))
11473 (push (list txt f re (org-refile-marker (point)))
11474 tgs)))
11475 (when (= (point) pos0)
11476 ;; verification function has not moved point
11477 (goto-char (point-at-eol))))))))
11478 (when org-refile-use-cache
11479 (org-refile-cache-put tgs (buffer-file-name) descre))
11480 (setq targets (append tgs targets))))))
11481 (message "Getting targets...done")
11482 (nreverse targets)))
11484 (defun org-protect-slash (s)
11485 (while (string-match "/" s)
11486 (setq s (replace-match "\\" t t s)))
11489 (defvar org-olpa (make-vector 20 nil))
11491 (defun org-get-outline-path (&optional fastp level heading)
11492 "Return the outline path to the current entry, as a list.
11494 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11495 routine which makes outline path derivations for an entire file,
11496 avoiding backtracing. Refile target collection makes use of that."
11497 (if fastp
11498 (progn
11499 (if (> level 19)
11500 (error "Outline path failure, more than 19 levels"))
11501 (loop for i from level upto 19 do
11502 (aset org-olpa i nil))
11503 (prog1
11504 (delq nil (append org-olpa nil))
11505 (aset org-olpa level heading)))
11506 (let (rtn case-fold-search)
11507 (save-excursion
11508 (save-restriction
11509 (widen)
11510 (while (org-up-heading-safe)
11511 (when (looking-at org-complex-heading-regexp)
11512 (push (org-trim
11513 (replace-regexp-in-string
11514 ;; Remove statistical/checkboxes cookies
11515 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11516 (org-match-string-no-properties 4)))
11517 rtn)))
11518 rtn)))))
11520 (defun org-format-outline-path (path &optional width prefix separator)
11521 "Format the outline path PATH for display.
11522 WIDTH is the maximum number of characters that is available.
11523 PREFIX is a prefix to be included in the returned string,
11524 such as the file name.
11525 SEPARATOR is inserted between the different parts of the path,
11526 the default is \"/\"."
11527 (setq width (or width 79))
11528 (if prefix (setq width (- width (length prefix))))
11529 (if (not path)
11530 (or prefix "")
11531 (let* ((nsteps (length path))
11532 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11533 (maxwidth (if (<= total-width width)
11534 10000 ;; everything fits
11535 ;; we need to shorten the level headings
11536 (/ (- width nsteps) nsteps)))
11537 (org-odd-levels-only nil)
11538 (n 0)
11539 (total (1+ (length prefix))))
11540 (setq maxwidth (max maxwidth 10))
11541 (concat prefix
11542 (if prefix (or separator "/"))
11543 (mapconcat
11544 (lambda (h)
11545 (setq n (1+ n))
11546 (if (and (= n nsteps) (< maxwidth 10000))
11547 (setq maxwidth (- total-width total)))
11548 (if (< (length h) maxwidth)
11549 (progn (setq total (+ total (length h) 1)) h)
11550 (setq h (substring h 0 (- maxwidth 2))
11551 total (+ total maxwidth 1))
11552 (if (string-match "[ \t]+\\'" h)
11553 (setq h (substring h 0 (match-beginning 0))))
11554 (setq h (concat h "..")))
11555 (org-add-props h nil 'face
11556 (nth (% (1- n) org-n-level-faces)
11557 org-level-faces))
11559 path (or separator "/"))))))
11561 (defun org-display-outline-path (&optional file current separator just-return-string)
11562 "Display the current outline path in the echo area.
11564 If FILE is non-nil, prepend the output with the file name.
11565 If CURRENT is non-nil, append the current heading to the output.
11566 SEPARATOR is passed through to `org-format-outline-path'. It separates
11567 the different parts of the path and defaults to \"/\".
11568 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11569 (interactive "P")
11570 (let* (case-fold-search
11571 (bfn (buffer-file-name (buffer-base-buffer)))
11572 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11573 res)
11574 (if current (setq path (append path
11575 (save-excursion
11576 (org-back-to-heading t)
11577 (if (looking-at org-complex-heading-regexp)
11578 (list (match-string 4)))))))
11579 (setq res
11580 (org-format-outline-path
11581 path
11582 (1- (frame-width))
11583 (and file bfn (concat (file-name-nondirectory bfn) separator))
11584 separator))
11585 (if just-return-string
11586 (org-no-properties res)
11587 (org-unlogged-message "%s" res))))
11589 (defvar org-refile-history nil
11590 "History for refiling operations.")
11592 (defvar org-after-refile-insert-hook nil
11593 "Hook run after `org-refile' has inserted its stuff at the new location.
11594 Note that this is still *before* the stuff will be removed from
11595 the *old* location.")
11597 (defvar org-capture-last-stored-marker)
11598 (defvar org-refile-keep nil
11599 "Non-nil means `org-refile' will copy instead of refile.")
11601 (defun org-copy ()
11602 "Like `org-refile', but copy."
11603 (interactive)
11604 (let ((org-refile-keep t))
11605 (funcall 'org-refile nil nil nil "Copy")))
11607 (defun org-refile (&optional arg default-buffer rfloc msg)
11608 "Move the entry or entries at point to another heading.
11609 The list of target headings is compiled using the information in
11610 `org-refile-targets', which see.
11612 At the target location, the entry is filed as a subitem of the
11613 target heading. Depending on `org-reverse-note-order', the new
11614 subitem will either be the first or the last subitem.
11616 If there is an active region, all entries in that region will be
11617 refiled. However, the region must fulfill the requirement that
11618 the first heading sets the top-level of the moved text.
11620 With prefix arg ARG, the command will only visit the target
11621 location and not actually move anything.
11623 With a double prefix arg \\[universal-argument] \\[universal-argument], go to the location where the last
11624 refiling operation has put the subtree.
11626 With a numeric prefix argument of `2', refile to the running clock.
11628 With a numeric prefix argument of `3', emulate `org-refile-keep'
11629 being set to `t' and copy to the target location, don't move it.
11630 Beware that keeping refiled entries may result in duplicated ID
11631 properties.
11633 RFLOC can be a refile location obtained in a different way.
11635 MSG is a string to replace \"Refile\" in the default prompt with
11636 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11638 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11640 If you are using target caching (see `org-refile-use-cache'), you
11641 have to clear the target cache in order to find new targets.
11642 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11643 prefix argument (`C-u C-u C-u C-c C-w')."
11644 (interactive "P")
11645 (if (member arg '(0 (64)))
11646 (org-refile-cache-clear)
11647 (let* ((actionmsg (cond (msg msg)
11648 ((equal arg 3) "Refile (and keep)")
11649 (t "Refile")))
11650 (cbuf (current-buffer))
11651 (regionp (org-region-active-p))
11652 (region-start (and regionp (region-beginning)))
11653 (region-end (and regionp (region-end)))
11654 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11655 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11656 pos it nbuf file re level reversed)
11657 (setq last-command nil)
11658 (when regionp
11659 (goto-char region-start)
11660 (or (bolp) (goto-char (point-at-bol)))
11661 (setq region-start (point))
11662 (unless (or (org-kill-is-subtree-p
11663 (buffer-substring region-start region-end))
11664 (prog1 org-refile-active-region-within-subtree
11665 (let ((s (point-at-eol)))
11666 (org-toggle-heading)
11667 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11668 (user-error "The region is not a (sequence of) subtree(s)")))
11669 (if (equal arg '(16))
11670 (org-refile-goto-last-stored)
11671 (when (or
11672 (and (equal arg 2)
11673 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11674 (prog1
11675 (setq it (list (or org-clock-heading "running clock")
11676 (buffer-file-name
11677 (marker-buffer org-clock-hd-marker))
11679 (marker-position org-clock-hd-marker)))
11680 (setq arg nil)))
11681 (setq it (or rfloc
11682 (let (heading-text)
11683 (save-excursion
11684 (unless (or arg (listp arg))
11685 (org-back-to-heading t)
11686 (setq heading-text
11687 (replace-regexp-in-string
11688 org-bracket-link-regexp
11689 "\\3"
11690 (nth 4 (org-heading-components)))))
11691 (org-refile-get-location
11692 (cond ((or arg (listp arg)) "Goto")
11693 (regionp (concat actionmsg " region to"))
11694 (t (concat actionmsg " subtree \""
11695 heading-text "\" to")))
11696 default-buffer
11697 (and (not (equal '(4) arg))
11698 org-refile-allow-creating-parent-nodes)
11699 arg))))))
11700 (setq file (nth 1 it)
11701 re (nth 2 it)
11702 pos (nth 3 it))
11703 (if (and (not arg)
11705 (equal (buffer-file-name) file)
11706 (if regionp
11707 (and (>= pos region-start)
11708 (<= pos region-end))
11709 (and (>= pos (point))
11710 (< pos (save-excursion
11711 (org-end-of-subtree t t))))))
11712 (error "Cannot refile to position inside the tree or region"))
11713 (setq nbuf (or (find-buffer-visiting file)
11714 (find-file-noselect file)))
11715 (if (and arg (not (equal arg 3)))
11716 (progn
11717 (org-pop-to-buffer-same-window nbuf)
11718 (goto-char pos)
11719 (org-show-context 'org-goto))
11720 (if regionp
11721 (progn
11722 (org-kill-new (buffer-substring region-start region-end))
11723 (org-save-markers-in-region region-start region-end))
11724 (org-copy-subtree 1 nil t))
11725 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11726 (find-file-noselect file)))
11727 (setq reversed (org-notes-order-reversed-p))
11728 (save-excursion
11729 (save-restriction
11730 (widen)
11731 (if pos
11732 (progn
11733 (goto-char pos)
11734 (looking-at org-outline-regexp)
11735 (setq level (org-get-valid-level (funcall outline-level) 1))
11736 (goto-char
11737 (if reversed
11738 (or (outline-next-heading) (point-max))
11739 (or (save-excursion (org-get-next-sibling))
11740 (org-end-of-subtree t t)
11741 (point-max)))))
11742 (setq level 1)
11743 (if (not reversed)
11744 (goto-char (point-max))
11745 (goto-char (point-min))
11746 (or (outline-next-heading) (goto-char (point-max)))))
11747 (if (not (bolp)) (newline))
11748 (org-paste-subtree level)
11749 (when org-log-refile
11750 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11751 (unless (eq org-log-refile 'note)
11752 (save-excursion (org-add-log-note))))
11753 (and org-auto-align-tags
11754 (let ((org-loop-over-headlines-in-active-region nil))
11755 (org-set-tags nil t)))
11756 (let ((bookmark-name (plist-get org-bookmark-names-plist
11757 :last-refile)))
11758 (when bookmark-name
11759 (with-demoted-errors
11760 (bookmark-set bookmark-name))))
11761 ;; If we are refiling for capture, make sure that the
11762 ;; last-capture pointers point here
11763 (when (org-bound-and-true-p org-refile-for-capture)
11764 (let ((bookmark-name (plist-get org-bookmark-names-plist
11765 :last-capture-marker)))
11766 (when bookmark-name
11767 (with-demoted-errors
11768 (bookmark-set bookmark-name))))
11769 (move-marker org-capture-last-stored-marker (point)))
11770 (if (fboundp 'deactivate-mark) (deactivate-mark))
11771 (run-hooks 'org-after-refile-insert-hook))))
11772 (unless org-refile-keep
11773 (if regionp
11774 (delete-region (point) (+ (point) (- region-end region-start)))
11775 (delete-region
11776 (and (org-back-to-heading t) (point))
11777 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11778 (when (featurep 'org-inlinetask)
11779 (org-inlinetask-remove-END-maybe))
11780 (setq org-markers-to-move nil)
11781 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11783 (defun org-refile-goto-last-stored ()
11784 "Go to the location where the last refile was stored."
11785 (interactive)
11786 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11787 (message "This is the location of the last refile"))
11789 (defun org-refile--get-location (refloc tbl)
11790 "When user refile to REFLOC, find the associated target in TBL.
11791 Also check `org-refile-target-table'."
11792 (car (delq
11794 (mapcar
11795 (lambda (r) (or (assoc r tbl)
11796 (assoc r org-refile-target-table)))
11797 (list (replace-regexp-in-string "/$" "" refloc)
11798 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11800 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11801 no-exclude)
11802 "Prompt the user for a refile location, using PROMPT.
11803 PROMPT should not be suffixed with a colon and a space, because
11804 this function appends the default value from
11805 `org-refile-history' automatically, if that is not empty.
11806 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11807 this is used for the GOTO interface."
11808 (let ((org-refile-targets org-refile-targets)
11809 (org-refile-use-outline-path org-refile-use-outline-path)
11810 excluded-entries)
11811 (when (and (derived-mode-p 'org-mode)
11812 (not org-refile-use-cache)
11813 (not no-exclude))
11814 (org-map-tree
11815 (lambda()
11816 (setq excluded-entries
11817 (append excluded-entries (list (org-get-heading t t)))))))
11818 (setq org-refile-target-table
11819 (org-refile-get-targets default-buffer excluded-entries)))
11820 (unless org-refile-target-table
11821 (user-error "No refile targets"))
11822 (let* ((cbuf (current-buffer))
11823 (partial-completion-mode nil)
11824 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11825 (cfunc (if (and org-refile-use-outline-path
11826 org-outline-path-complete-in-steps)
11827 'org-olpath-completing-read
11828 'org-icompleting-read))
11829 (extra (if org-refile-use-outline-path "/" ""))
11830 (cbnex (concat (buffer-name) extra))
11831 (filename (and cfn (expand-file-name cfn)))
11832 (tbl (mapcar
11833 (lambda (x)
11834 (if (and (not (member org-refile-use-outline-path
11835 '(file full-file-path)))
11836 (not (equal filename (nth 1 x))))
11837 (cons (concat (car x) extra " ("
11838 (file-name-nondirectory (nth 1 x)) ")")
11839 (cdr x))
11840 (cons (concat (car x) extra) (cdr x))))
11841 org-refile-target-table))
11842 (completion-ignore-case t)
11843 cdef
11844 (prompt (concat prompt
11845 (or (and (car org-refile-history)
11846 (concat " (default " (car org-refile-history) ")"))
11847 (and (assoc cbnex tbl) (setq cdef cbnex)
11848 (concat " (default " cbnex ")"))) ": "))
11849 pa answ parent-target child parent old-hist)
11850 (setq old-hist org-refile-history)
11851 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11852 nil 'org-refile-history (or cdef (car org-refile-history))))
11853 (if (setq pa (org-refile--get-location answ tbl))
11854 (progn
11855 (org-refile-check-position pa)
11856 (when (or (not org-refile-history)
11857 (not (eq old-hist org-refile-history))
11858 (not (equal (car pa) (car org-refile-history))))
11859 (setq org-refile-history
11860 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11861 org-refile-history
11862 (cdr org-refile-history))))
11863 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11864 (pop org-refile-history)))
11866 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11867 (progn
11868 (setq parent (match-string 1 answ)
11869 child (match-string 2 answ))
11870 (setq parent-target (org-refile--get-location parent tbl))
11871 (when (and parent-target
11872 (or (eq new-nodes t)
11873 (and (eq new-nodes 'confirm)
11874 (y-or-n-p (format "Create new node \"%s\"? "
11875 child)))))
11876 (org-refile-new-child parent-target child)))
11877 (user-error "Invalid target location")))))
11879 (declare-function org-string-nw-p "org-macs" (s))
11880 (defun org-refile-check-position (refile-pointer)
11881 "Check if the refile pointer matches the headline to which it points."
11882 (let* ((file (nth 1 refile-pointer))
11883 (re (nth 2 refile-pointer))
11884 (pos (nth 3 refile-pointer))
11885 buffer)
11886 (if (and (not (markerp pos)) (not file))
11887 (if file
11888 (user-error "Please save the buffer to a file before refiling")
11889 (user-error "Please indicate a target file in the refile path"))
11890 (when (org-string-nw-p re)
11891 (setq buffer (if (markerp pos)
11892 (marker-buffer pos)
11893 (or (find-buffer-visiting file)
11894 (find-file-noselect file))))
11895 (with-current-buffer buffer
11896 (save-excursion
11897 (save-restriction
11898 (widen)
11899 (goto-char pos)
11900 (beginning-of-line 1)
11901 (unless (org-looking-at-p re)
11902 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11904 (defun org-refile-new-child (parent-target child)
11905 "Use refile target PARENT-TARGET to add new CHILD below it."
11906 (unless parent-target
11907 (error "Cannot find parent for new node"))
11908 (let ((file (nth 1 parent-target))
11909 (pos (nth 3 parent-target))
11910 level)
11911 (with-current-buffer (or (find-buffer-visiting file)
11912 (find-file-noselect file))
11913 (save-excursion
11914 (save-restriction
11915 (widen)
11916 (if pos
11917 (goto-char pos)
11918 (goto-char (point-max))
11919 (if (not (bolp)) (newline)))
11920 (when (looking-at org-outline-regexp)
11921 (setq level (funcall outline-level))
11922 (org-end-of-subtree t t))
11923 (org-back-over-empty-lines)
11924 (insert "\n" (make-string
11925 (if pos (org-get-valid-level level 1) 1) ?*)
11926 " " child "\n")
11927 (beginning-of-line 0)
11928 (list (concat (car parent-target) "/" child) file "" (point)))))))
11930 (defun org-olpath-completing-read (prompt collection &rest args)
11931 "Read an outline path like a file name."
11932 (let ((thetable collection)
11933 (org-completion-use-ido nil) ; does not work with ido.
11934 (org-completion-use-iswitchb nil)) ; or iswitchb
11935 (apply
11936 'org-icompleting-read prompt
11937 (lambda (string predicate &optional flag)
11938 (let (rtn r f (l (length string)))
11939 (cond
11940 ((eq flag nil)
11941 ;; try completion
11942 (try-completion string thetable))
11943 ((eq flag t)
11944 ;; all-completions
11945 (setq rtn (all-completions string thetable predicate))
11946 (mapcar
11947 (lambda (x)
11948 (setq r (substring x l))
11949 (if (string-match " ([^)]*)$" x)
11950 (setq f (match-string 0 x))
11951 (setq f ""))
11952 (if (string-match "/" r)
11953 (concat string (substring r 0 (match-end 0)) f)
11955 rtn))
11956 ((eq flag 'lambda)
11957 ;; exact match?
11958 (assoc string thetable)))))
11959 args)))
11961 ;;;; Dynamic blocks
11963 (defun org-find-dblock (name)
11964 "Find the first dynamic block with name NAME in the buffer.
11965 If not found, stay at current position and return nil."
11966 (let ((case-fold-search t) pos)
11967 (save-excursion
11968 (goto-char (point-min))
11969 (setq pos (and (re-search-forward
11970 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11971 (match-beginning 0))))
11972 (if pos (goto-char pos))
11973 pos))
11975 (defun org-create-dblock (plist)
11976 "Create a dynamic block section, with parameters taken from PLIST.
11977 PLIST must contain a :name entry which is used as the name of the block."
11978 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11979 (end-of-line 1)
11980 (newline))
11981 (let ((col (current-column))
11982 (name (plist-get plist :name)))
11983 (insert "#+BEGIN: " name)
11984 (while plist
11985 (if (eq (car plist) :name)
11986 (setq plist (cddr plist))
11987 (insert " " (prin1-to-string (pop plist)))))
11988 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11989 (beginning-of-line -2)))
11991 (defun org-prepare-dblock ()
11992 "Prepare dynamic block for refresh.
11993 This empties the block, puts the cursor at the insert position and returns
11994 the property list including an extra property :name with the block name."
11995 (unless (looking-at org-dblock-start-re)
11996 (user-error "Not at a dynamic block"))
11997 (let* ((begdel (1+ (match-end 0)))
11998 (name (org-no-properties (match-string 1)))
11999 (params (append (list :name name)
12000 (read (concat "(" (match-string 3) ")")))))
12001 (save-excursion
12002 (beginning-of-line 1)
12003 (skip-chars-forward " \t")
12004 (setq params (plist-put params :indentation-column (current-column))))
12005 (unless (re-search-forward org-dblock-end-re nil t)
12006 (error "Dynamic block not terminated"))
12007 (setq params
12008 (append params
12009 (list :content (buffer-substring
12010 begdel (match-beginning 0)))))
12011 (delete-region begdel (match-beginning 0))
12012 (goto-char begdel)
12013 (open-line 1)
12014 params))
12016 (defun org-map-dblocks (&optional command)
12017 "Apply COMMAND to all dynamic blocks in the current buffer.
12018 If COMMAND is not given, use `org-update-dblock'."
12019 (let ((cmd (or command 'org-update-dblock)))
12020 (save-excursion
12021 (goto-char (point-min))
12022 (while (re-search-forward org-dblock-start-re nil t)
12023 (goto-char (match-beginning 0))
12024 (save-excursion
12025 (condition-case nil
12026 (funcall cmd)
12027 (error (message "Error during update of dynamic block"))))
12028 (unless (re-search-forward org-dblock-end-re nil t)
12029 (error "Dynamic block not terminated"))))))
12031 (defun org-dblock-update (&optional arg)
12032 "User command for updating dynamic blocks.
12033 Update the dynamic block at point. With prefix ARG, update all dynamic
12034 blocks in the buffer."
12035 (interactive "P")
12036 (if arg
12037 (org-update-all-dblocks)
12038 (or (looking-at org-dblock-start-re)
12039 (org-beginning-of-dblock))
12040 (org-update-dblock)))
12042 (defun org-update-dblock ()
12043 "Update the dynamic block at point.
12044 This means to empty the block, parse for parameters and then call
12045 the correct writing function."
12046 (interactive)
12047 (save-excursion
12048 (let* ((win (selected-window))
12049 (pos (point))
12050 (line (org-current-line))
12051 (params (org-prepare-dblock))
12052 (name (plist-get params :name))
12053 (indent (plist-get params :indentation-column))
12054 (cmd (intern (concat "org-dblock-write:" name))))
12055 (message "Updating dynamic block `%s' at line %d..." name line)
12056 (funcall cmd params)
12057 (message "Updating dynamic block `%s' at line %d...done" name line)
12058 (goto-char pos)
12059 (when (and indent (> indent 0))
12060 (setq indent (make-string indent ?\ ))
12061 (save-excursion
12062 (select-window win)
12063 (org-beginning-of-dblock)
12064 (forward-line 1)
12065 (while (not (looking-at org-dblock-end-re))
12066 (insert indent)
12067 (beginning-of-line 2))
12068 (when (looking-at org-dblock-end-re)
12069 (and (looking-at "[ \t]+")
12070 (replace-match ""))
12071 (insert indent)))))))
12073 (defun org-beginning-of-dblock ()
12074 "Find the beginning of the dynamic block at point.
12075 Error if there is no such block at point."
12076 (let ((pos (point))
12077 beg)
12078 (end-of-line 1)
12079 (if (and (re-search-backward org-dblock-start-re nil t)
12080 (setq beg (match-beginning 0))
12081 (re-search-forward org-dblock-end-re nil t)
12082 (> (match-end 0) pos))
12083 (goto-char beg)
12084 (goto-char pos)
12085 (error "Not in a dynamic block"))))
12087 (defun org-update-all-dblocks ()
12088 "Update all dynamic blocks in the buffer.
12089 This function can be used in a hook."
12090 (interactive)
12091 (when (derived-mode-p 'org-mode)
12092 (org-map-dblocks 'org-update-dblock)))
12095 ;;;; Completion
12097 (declare-function org-export-backend-name "org-export" (cl-x))
12098 (declare-function org-export-backend-options "org-export" (cl-x))
12099 (defun org-get-export-keywords ()
12100 "Return a list of all currently understood export keywords.
12101 Export keywords include options, block names, attributes and
12102 keywords relative to each registered export back-end."
12103 (let (keywords)
12104 (dolist (backend
12105 (org-bound-and-true-p org-export--registered-backends)
12106 (delq nil keywords))
12107 ;; Back-end name (for keywords, like #+LATEX:)
12108 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12109 (dolist (option-entry (org-export-backend-options backend))
12110 ;; Back-end options.
12111 (push (nth 1 option-entry) keywords)))))
12113 (defconst org-options-keywords
12114 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12115 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12116 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12117 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12118 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12120 (defcustom org-structure-template-alist
12121 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC" "<src lang=\"?\">\n\n</src>")
12122 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE" "<example>\n?\n</example>")
12123 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE" "<quote>\n?\n</quote>")
12124 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE" "<verse>\n?\n</verse>")
12125 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM" "<verbatim>\n?\n</verbatim>")
12126 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER" "<center>\n?\n</center>")
12127 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
12128 "<literal style=\"latex\">\n?\n</literal>")
12129 ("L" "#+LaTeX: " "<literal style=\"latex\">?</literal>")
12130 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
12131 "<literal style=\"html\">\n?\n</literal>")
12132 ("H" "#+HTML: " "<literal style=\"html\">?</literal>")
12133 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII" "")
12134 ("A" "#+ASCII: " "")
12135 ("i" "#+INDEX: ?" "#+INDEX: ?")
12136 ("I" "#+INCLUDE: %file ?"
12137 "<include file=%file markup=\"?\">"))
12138 "Structure completion elements.
12139 This is a list of abbreviation keys and values. The value gets inserted
12140 if you type `<' followed by the key and then press the completion key,
12141 usually `M-TAB'. %file will be replaced by a file name after prompting
12142 for the file using completion. The cursor will be placed at the position
12143 of the `?` in the template.
12144 There are two templates for each key, the first uses the original Org syntax,
12145 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12146 the default when the /org-mtags.el/ module has been loaded. See also the
12147 variable `org-mtags-prefer-muse-templates'."
12148 :group 'org-completion
12149 :type '(repeat
12150 (list
12151 (string :tag "Key")
12152 (string :tag "Template")
12153 (string :tag "Muse Template"))))
12155 (defun org-try-structure-completion ()
12156 "Try to complete a structure template before point.
12157 This looks for strings like \"<e\" on an otherwise empty line and
12158 expands them."
12159 (let ((l (buffer-substring (point-at-bol) (point)))
12161 (when (and (looking-at "[ \t]*$")
12162 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12163 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12164 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12165 (match-beginning 1)) a)
12166 t)))
12168 (defun org-complete-expand-structure-template (start cell)
12169 "Expand a structure template."
12170 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
12171 (rpl (nth (if musep 2 1) cell))
12172 (ind ""))
12173 (delete-region start (point))
12174 (when (string-match "\\`[ \t]*#\\+" rpl)
12175 (cond
12176 ((bolp))
12177 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12178 (setq ind (buffer-substring (point-at-bol) (point))))
12179 (t (newline))))
12180 (setq start (point))
12181 (if (string-match "%file" rpl)
12182 (setq rpl (replace-match
12183 (concat
12184 "\""
12185 (save-match-data
12186 (abbreviate-file-name (read-file-name "Include file: ")))
12187 "\"")
12188 t t rpl)))
12189 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12190 (concat "\n" ind)))
12191 (insert rpl)
12192 (if (re-search-backward "\\?" start t) (delete-char 1))))
12194 ;;;; TODO, DEADLINE, Comments
12196 (defun org-toggle-comment ()
12197 "Change the COMMENT state of an entry."
12198 (interactive)
12199 (save-excursion
12200 (org-back-to-heading)
12201 (looking-at org-complex-heading-regexp)
12202 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12203 (skip-chars-forward " \t")
12204 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12205 (if (org-in-commented-heading-p t)
12206 (delete-region (point)
12207 (progn (search-forward " " (line-end-position) 'move)
12208 (skip-chars-forward " \t")
12209 (point)))
12210 (insert org-comment-string)
12211 (unless (eolp) (insert " ")))))
12213 (defvar org-last-todo-state-is-todo nil
12214 "This is non-nil when the last TODO state change led to a TODO state.
12215 If the last change removed the TODO tag or switched to DONE, then
12216 this is nil.")
12218 (defvar org-setting-tags nil) ; dynamically skipped
12220 (defvar org-todo-setup-filter-hook nil
12221 "Hook for functions that pre-filter todo specs.
12222 Each function takes a todo spec and returns either nil or the spec
12223 transformed into canonical form." )
12225 (defvar org-todo-get-default-hook nil
12226 "Hook for functions that get a default item for todo.
12227 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12228 nil or a string to be used for the todo mark." )
12230 (defvar org-agenda-headline-snapshot-before-repeat)
12232 (defun org-current-effective-time ()
12233 "Return current time adjusted for `org-extend-today-until' variable."
12234 (let* ((ct (org-current-time))
12235 (dct (decode-time ct))
12236 (ct1
12237 (cond
12238 (org-use-last-clock-out-time-as-effective-time
12239 (or (org-clock-get-last-clock-out-time) ct))
12240 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12241 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12242 (t ct))))
12243 ct1))
12245 (defun org-todo-yesterday (&optional arg)
12246 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12247 (interactive "P")
12248 (if (eq major-mode 'org-agenda-mode)
12249 (apply 'org-agenda-todo-yesterday arg)
12250 (let* ((hour (third (decode-time
12251 (org-current-time))))
12252 (org-extend-today-until (1+ hour)))
12253 (org-todo arg))))
12255 (defvar org-block-entry-blocking ""
12256 "First entry preventing the TODO state change.")
12258 (defun org-cancel-repeater ()
12259 "Cancel a repeater by setting its numeric value to zero."
12260 (interactive)
12261 (save-excursion
12262 (org-back-to-heading t)
12263 (let ((bound1 (point))
12264 (bound0 (save-excursion (outline-next-heading) (point))))
12265 (when (re-search-forward
12266 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12267 org-deadline-time-regexp "\\)\\|\\("
12268 org-ts-regexp "\\)")
12269 bound0 t)
12270 (if (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]" bound1 t)
12271 (replace-match "0" t nil nil 1))))))
12273 (defun org-todo (&optional arg)
12274 "Change the TODO state of an item.
12275 The state of an item is given by a keyword at the start of the heading,
12276 like
12277 *** TODO Write paper
12278 *** DONE Call mom
12280 The different keywords are specified in the variable `org-todo-keywords'.
12281 By default the available states are \"TODO\" and \"DONE\".
12282 So for this example: when the item starts with TODO, it is changed to DONE.
12283 When it starts with DONE, the DONE is removed. And when neither TODO nor
12284 DONE are present, add TODO at the beginning of the heading.
12286 With \\[universal-argument] prefix arg, use completion to determine the new \
12287 state.
12288 With numeric prefix arg, switch to that state.
12289 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12290 keywords (nextset).
12291 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12292 With a numeric prefix arg of 0, inhibit note taking for the change.
12293 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12295 When called through ELisp, arg is also interpreted in the following way:
12296 'none -> empty state
12297 \"\"(empty string) -> switch to empty state
12298 'done -> switch to DONE
12299 'nextset -> switch to the next set of keywords
12300 'previousset -> switch to the previous set of keywords
12301 \"WAITING\" -> switch to the specified keyword, but only if it
12302 really is a member of `org-todo-keywords'."
12303 (interactive "P")
12304 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12305 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12306 'region-start-level 'region))
12307 org-loop-over-headlines-in-active-region)
12308 (org-map-entries
12309 `(org-todo ,arg)
12310 org-loop-over-headlines-in-active-region
12311 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12312 (if (equal arg '(16)) (setq arg 'nextset))
12313 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12314 (let ((org-blocker-hook org-blocker-hook)
12315 commentp
12316 case-fold-search)
12317 (when (equal arg '(64))
12318 (setq arg nil org-blocker-hook nil))
12319 (when (and org-blocker-hook
12320 (or org-inhibit-blocking
12321 (org-entry-get nil "NOBLOCKING")))
12322 (setq org-blocker-hook nil))
12323 (save-excursion
12324 (catch 'exit
12325 (org-back-to-heading t)
12326 (when (org-in-commented-heading-p t)
12327 (org-toggle-comment)
12328 (setq commentp t))
12329 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12330 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12331 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12332 (let* ((match-data (match-data))
12333 (startpos (point-at-bol))
12334 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12335 (org-log-done org-log-done)
12336 (org-log-repeat org-log-repeat)
12337 (org-todo-log-states org-todo-log-states)
12338 (org-inhibit-logging
12339 (if (equal arg 0)
12340 (progn (setq arg nil) 'note) org-inhibit-logging))
12341 (this (match-string 1))
12342 (hl-pos (match-beginning 0))
12343 (head (org-get-todo-sequence-head this))
12344 (ass (assoc head org-todo-kwd-alist))
12345 (interpret (nth 1 ass))
12346 (done-word (nth 3 ass))
12347 (final-done-word (nth 4 ass))
12348 (org-last-state (or this ""))
12349 (completion-ignore-case t)
12350 (member (member this org-todo-keywords-1))
12351 (tail (cdr member))
12352 (org-state (cond
12353 ((and org-todo-key-trigger
12354 (or (and (equal arg '(4))
12355 (eq org-use-fast-todo-selection 'prefix))
12356 (and (not arg) org-use-fast-todo-selection
12357 (not (eq org-use-fast-todo-selection
12358 'prefix)))))
12359 ;; Use fast selection
12360 (org-fast-todo-selection))
12361 ((and (equal arg '(4))
12362 (or (not org-use-fast-todo-selection)
12363 (not org-todo-key-trigger)))
12364 ;; Read a state with completion
12365 (org-icompleting-read
12366 "State: " (mapcar 'list org-todo-keywords-1)
12367 nil t))
12368 ((eq arg 'right)
12369 (if this
12370 (if tail (car tail) nil)
12371 (car org-todo-keywords-1)))
12372 ((eq arg 'left)
12373 (if (equal member org-todo-keywords-1)
12375 (if this
12376 (nth (- (length org-todo-keywords-1)
12377 (length tail) 2)
12378 org-todo-keywords-1)
12379 (org-last org-todo-keywords-1))))
12380 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12381 (setq arg nil))) ; hack to fall back to cycling
12382 (arg
12383 ;; user or caller requests a specific state
12384 (cond
12385 ((equal arg "") nil)
12386 ((eq arg 'none) nil)
12387 ((eq arg 'done) (or done-word (car org-done-keywords)))
12388 ((eq arg 'nextset)
12389 (or (car (cdr (member head org-todo-heads)))
12390 (car org-todo-heads)))
12391 ((eq arg 'previousset)
12392 (let ((org-todo-heads (reverse org-todo-heads)))
12393 (or (car (cdr (member head org-todo-heads)))
12394 (car org-todo-heads))))
12395 ((car (member arg org-todo-keywords-1)))
12396 ((stringp arg)
12397 (user-error "State `%s' not valid in this file" arg))
12398 ((nth (1- (prefix-numeric-value arg))
12399 org-todo-keywords-1))))
12400 ((null member) (or head (car org-todo-keywords-1)))
12401 ((equal this final-done-word) nil) ;; -> make empty
12402 ((null tail) nil) ;; -> first entry
12403 ((memq interpret '(type priority))
12404 (if (eq this-command last-command)
12405 (car tail)
12406 (if (> (length tail) 0)
12407 (or done-word (car org-done-keywords))
12408 nil)))
12410 (car tail))))
12411 (org-state (or
12412 (run-hook-with-args-until-success
12413 'org-todo-get-default-hook org-state org-last-state)
12414 org-state))
12415 (next (if org-state (concat " " org-state " ") " "))
12416 (change-plist (list :type 'todo-state-change :from this :to org-state
12417 :position startpos))
12418 dolog now-done-p)
12419 (when org-blocker-hook
12420 (setq org-last-todo-state-is-todo
12421 (not (member this org-done-keywords)))
12422 (unless (save-excursion
12423 (save-match-data
12424 (org-with-wide-buffer
12425 (run-hook-with-args-until-failure
12426 'org-blocker-hook change-plist))))
12427 (if (org-called-interactively-p 'interactive)
12428 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12429 this org-state org-block-entry-blocking)
12430 ;; fail silently
12431 (message "TODO state change from %s to %s blocked (by \"%s\")"
12432 this org-state org-block-entry-blocking)
12433 (throw 'exit nil))))
12434 (store-match-data match-data)
12435 (replace-match next t t)
12436 (unless (pos-visible-in-window-p hl-pos)
12437 (message "TODO state changed to %s" (org-trim next)))
12438 (unless head
12439 (setq head (org-get-todo-sequence-head org-state)
12440 ass (assoc head org-todo-kwd-alist)
12441 interpret (nth 1 ass)
12442 done-word (nth 3 ass)
12443 final-done-word (nth 4 ass)))
12444 (when (memq arg '(nextset previousset))
12445 (message "Keyword-Set %d/%d: %s"
12446 (- (length org-todo-sets) -1
12447 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12448 (length org-todo-sets)
12449 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12450 (setq org-last-todo-state-is-todo
12451 (not (member org-state org-done-keywords)))
12452 (setq now-done-p (and (member org-state org-done-keywords)
12453 (not (member this org-done-keywords))))
12454 (and logging (org-local-logging logging))
12455 (when (and (or org-todo-log-states org-log-done)
12456 (not (eq org-inhibit-logging t))
12457 (not (memq arg '(nextset previousset))))
12458 ;; we need to look at recording a time and note
12459 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12460 (nth 2 (assoc this org-todo-log-states))))
12461 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12462 (setq dolog 'time))
12463 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12464 (and org-state
12465 (member org-state org-not-done-keywords)
12466 (not (member this org-not-done-keywords))))
12467 ;; This is now a todo state and was not one before
12468 ;; If there was a CLOSED time stamp, get rid of it.
12469 (org-add-planning-info nil nil 'closed))
12470 (when (and now-done-p org-log-done)
12471 ;; It is now done, and it was not done before
12472 (org-add-planning-info 'closed (org-current-effective-time))
12473 (if (and (not dolog) (eq 'note org-log-done))
12474 (org-add-log-setup 'done org-state this 'findpos 'note)))
12475 (when (and org-state dolog)
12476 ;; This is a non-nil state, and we need to log it
12477 (org-add-log-setup 'state org-state this 'findpos dolog)))
12478 ;; Fixup tag positioning
12479 (org-todo-trigger-tag-changes org-state)
12480 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12481 (when org-provide-todo-statistics
12482 (org-update-parent-todo-statistics))
12483 (run-hooks 'org-after-todo-state-change-hook)
12484 (if (and arg (not (member org-state org-done-keywords)))
12485 (setq head (org-get-todo-sequence-head org-state)))
12486 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12487 ;; Do we need to trigger a repeat?
12488 (when now-done-p
12489 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12490 ;; This is for the agenda, take a snapshot of the headline.
12491 (save-match-data
12492 (setq org-agenda-headline-snapshot-before-repeat
12493 (org-get-heading))))
12494 (org-auto-repeat-maybe org-state))
12495 ;; Fixup cursor location if close to the keyword
12496 (if (and (outline-on-heading-p)
12497 (not (bolp))
12498 (save-excursion (beginning-of-line 1)
12499 (looking-at org-todo-line-regexp))
12500 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12501 (progn
12502 (goto-char (or (match-end 2) (match-end 1)))
12503 (and (looking-at " ") (just-one-space))))
12504 (when org-trigger-hook
12505 (save-excursion
12506 (run-hook-with-args 'org-trigger-hook change-plist)))
12507 (when commentp (org-toggle-comment))))))))
12509 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12510 "Block turning an entry into a TODO, using the hierarchy.
12511 This checks whether the current task should be blocked from state
12512 changes. Such blocking occurs when:
12514 1. The task has children which are not all in a completed state.
12516 2. A task has a parent with the property :ORDERED:, and there
12517 are siblings prior to the current task with incomplete
12518 status.
12520 3. The parent of the task is blocked because it has siblings that should
12521 be done first, or is child of a block grandparent TODO entry."
12523 (if (not org-enforce-todo-dependencies)
12524 t ; if locally turned off don't block
12525 (catch 'dont-block
12526 ;; If this is not a todo state change, or if this entry is already DONE,
12527 ;; do not block
12528 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12529 (member (plist-get change-plist :from)
12530 (cons 'done org-done-keywords))
12531 (member (plist-get change-plist :to)
12532 (cons 'todo org-not-done-keywords))
12533 (not (plist-get change-plist :to)))
12534 (throw 'dont-block t))
12535 ;; If this task has children, and any are undone, it's blocked
12536 (save-excursion
12537 (org-back-to-heading t)
12538 (let ((this-level (funcall outline-level)))
12539 (outline-next-heading)
12540 (let ((child-level (funcall outline-level)))
12541 (while (and (not (eobp))
12542 (> child-level this-level))
12543 ;; this todo has children, check whether they are all
12544 ;; completed
12545 (if (and (not (org-entry-is-done-p))
12546 (org-entry-is-todo-p))
12547 (progn (setq org-block-entry-blocking (org-get-heading))
12548 (throw 'dont-block nil)))
12549 (outline-next-heading)
12550 (setq child-level (funcall outline-level))))))
12551 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12552 ;; any previous siblings are undone, it's blocked
12553 (save-excursion
12554 (org-back-to-heading t)
12555 (let* ((pos (point))
12556 (parent-pos (and (org-up-heading-safe) (point))))
12557 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12558 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12559 (forward-line 1)
12560 (re-search-forward org-not-done-heading-regexp pos t))
12561 (setq org-block-entry-blocking (match-string 0))
12562 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12563 ;; Search further up the hierarchy, to see if an ancestor is blocked
12564 (while t
12565 (goto-char parent-pos)
12566 (if (not (looking-at org-not-done-heading-regexp))
12567 (throw 'dont-block t)) ; do not block, parent is not a TODO
12568 (setq pos (point))
12569 (setq parent-pos (and (org-up-heading-safe) (point)))
12570 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12571 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12572 (forward-line 1)
12573 (re-search-forward org-not-done-heading-regexp pos t)
12574 (setq org-block-entry-blocking (org-get-heading)))
12575 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12577 (defcustom org-track-ordered-property-with-tag nil
12578 "Should the ORDERED property also be shown as a tag?
12579 The ORDERED property decides if an entry should require subtasks to be
12580 completed in sequence. Since a property is not very visible, setting
12581 this option means that toggling the ORDERED property with the command
12582 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12583 not relevant for the behavior, but it makes things more visible.
12585 Note that toggling the tag with tags commands will not change the property
12586 and therefore not influence behavior!
12588 This can be t, meaning the tag ORDERED should be used, It can also be a
12589 string to select a different tag for this task."
12590 :group 'org-todo
12591 :type '(choice
12592 (const :tag "No tracking" nil)
12593 (const :tag "Track with ORDERED tag" t)
12594 (string :tag "Use other tag")))
12596 (defun org-toggle-ordered-property ()
12597 "Toggle the ORDERED property of the current entry.
12598 For better visibility, you can track the value of this property with a tag.
12599 See variable `org-track-ordered-property-with-tag'."
12600 (interactive)
12601 (let* ((t1 org-track-ordered-property-with-tag)
12602 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12603 (save-excursion
12604 (org-back-to-heading)
12605 (if (org-entry-get nil "ORDERED")
12606 (progn
12607 (org-delete-property "ORDERED")
12608 (and tag (org-toggle-tag tag 'off))
12609 (message "Subtasks can be completed in arbitrary order"))
12610 (org-entry-put nil "ORDERED" "t")
12611 (and tag (org-toggle-tag tag 'on))
12612 (message "Subtasks must be completed in sequence")))))
12614 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12615 (defun org-block-todo-from-checkboxes (change-plist)
12616 "Block turning an entry into a TODO, using checkboxes.
12617 This checks whether the current task should be blocked from state
12618 changes because there are unchecked boxes in this entry."
12619 (if (not org-enforce-todo-checkbox-dependencies)
12620 t ; if locally turned off don't block
12621 (catch 'dont-block
12622 ;; If this is not a todo state change, or if this entry is already DONE,
12623 ;; do not block
12624 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12625 (member (plist-get change-plist :from)
12626 (cons 'done org-done-keywords))
12627 (member (plist-get change-plist :to)
12628 (cons 'todo org-not-done-keywords))
12629 (not (plist-get change-plist :to)))
12630 (throw 'dont-block t))
12631 ;; If this task has checkboxes that are not checked, it's blocked
12632 (save-excursion
12633 (org-back-to-heading t)
12634 (let ((beg (point)) end)
12635 (outline-next-heading)
12636 (setq end (point))
12637 (goto-char beg)
12638 (if (org-list-search-forward
12639 (concat (org-item-beginning-re)
12640 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12641 "\\[[- ]\\]")
12642 end t)
12643 (progn
12644 (if (boundp 'org-blocked-by-checkboxes)
12645 (setq org-blocked-by-checkboxes t))
12646 (throw 'dont-block nil)))))
12647 t))) ; do not block
12649 (defun org-entry-blocked-p ()
12650 "Is the current entry blocked?"
12651 (org-with-silent-modifications
12652 (if (org-entry-get nil "NOBLOCKING")
12653 nil ;; Never block this entry
12654 (not (run-hook-with-args-until-failure
12655 'org-blocker-hook
12656 (list :type 'todo-state-change
12657 :position (point)
12658 :from 'todo
12659 :to 'done))))))
12661 (defun org-update-statistics-cookies (all)
12662 "Update the statistics cookie, either from TODO or from checkboxes.
12663 This should be called with the cursor in a line with a statistics cookie."
12664 (interactive "P")
12665 (if all
12666 (progn
12667 (org-update-checkbox-count 'all)
12668 (org-map-entries 'org-update-parent-todo-statistics))
12669 (if (not (org-at-heading-p))
12670 (org-update-checkbox-count)
12671 (let ((pos (point-marker))
12672 end l1 l2)
12673 (ignore-errors (org-back-to-heading t))
12674 (if (not (org-at-heading-p))
12675 (org-update-checkbox-count)
12676 (setq l1 (org-outline-level))
12677 (setq end (save-excursion
12678 (outline-next-heading)
12679 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12680 (point)))
12681 (if (and (save-excursion
12682 (re-search-forward
12683 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12684 (not (save-excursion (re-search-forward
12685 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12686 (org-update-checkbox-count)
12687 (if (and l2 (> l2 l1))
12688 (progn
12689 (goto-char end)
12690 (org-update-parent-todo-statistics))
12691 (goto-char pos)
12692 (beginning-of-line 1)
12693 (while (re-search-forward
12694 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12695 (point-at-eol) t)
12696 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12697 (goto-char pos)
12698 (move-marker pos nil)))))
12700 (defvar org-entry-property-inherited-from) ;; defined below
12701 (defun org-update-parent-todo-statistics ()
12702 "Update any statistics cookie in the parent of the current headline.
12703 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12704 the entire subtree and this will travel up the hierarchy and update
12705 statistics everywhere."
12706 (let* ((prop (save-excursion (org-up-heading-safe)
12707 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12708 (recursive (or (not org-hierarchical-todo-statistics)
12709 (and prop (string-match "\\<recursive\\>" prop))))
12710 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12712 (first t)
12713 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12714 level ltoggle l1 new ndel
12715 (cnt-all 0) (cnt-done 0) is-percent kwd
12716 checkbox-beg ov ovs ove cookie-present)
12717 (catch 'exit
12718 (save-excursion
12719 (beginning-of-line 1)
12720 (setq ltoggle (funcall outline-level))
12721 ;; Three situations are to consider:
12723 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12724 ;; to the top-level ancestor on the headline;
12726 ;; 2. If parent has "recursive" property, repeat up to the
12727 ;; headline setting that property, taking inheritance into
12728 ;; account;
12730 ;; 3. Else, move up to direct parent and proceed only once.
12731 (while (and (setq level (org-up-heading-safe))
12732 (or recursive first)
12733 (>= (point) lim))
12734 (setq first nil cookie-present nil)
12735 (unless (and level
12736 (not (string-match
12737 "\\<checkbox\\>"
12738 (downcase (or (org-entry-get nil "COOKIE_DATA")
12739 "")))))
12740 (throw 'exit nil))
12741 (while (re-search-forward box-re (point-at-eol) t)
12742 (setq cnt-all 0 cnt-done 0 cookie-present t)
12743 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12744 (save-match-data
12745 (unless (outline-next-heading) (throw 'exit nil))
12746 (while (and (looking-at org-complex-heading-regexp)
12747 (> (setq l1 (length (match-string 1))) level))
12748 (setq kwd (and (or recursive (= l1 ltoggle))
12749 (match-string 2)))
12750 (if (or (eq org-provide-todo-statistics 'all-headlines)
12751 (and (eq org-provide-todo-statistics t)
12752 (or (member kwd org-done-keywords)))
12753 (and (listp org-provide-todo-statistics)
12754 (stringp (car org-provide-todo-statistics))
12755 (or (member kwd org-provide-todo-statistics)
12756 (member kwd org-done-keywords)))
12757 (and (listp org-provide-todo-statistics)
12758 (listp (car org-provide-todo-statistics))
12759 (or (member kwd (car org-provide-todo-statistics))
12760 (and (member kwd org-done-keywords)
12761 (member kwd (cadr org-provide-todo-statistics))))))
12762 (setq cnt-all (1+ cnt-all))
12763 (if (eq org-provide-todo-statistics t)
12764 (and kwd (setq cnt-all (1+ cnt-all)))))
12765 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12766 (member kwd org-done-keywords))
12767 (and (listp org-provide-todo-statistics)
12768 (listp (car org-provide-todo-statistics))
12769 (member kwd org-done-keywords)
12770 (member kwd (cadr org-provide-todo-statistics)))
12771 (and (listp org-provide-todo-statistics)
12772 (stringp (car org-provide-todo-statistics))
12773 (member kwd org-done-keywords)))
12774 (setq cnt-done (1+ cnt-done)))
12775 (outline-next-heading)))
12776 (setq new
12777 (if is-percent
12778 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12779 (format "[%d/%d]" cnt-done cnt-all))
12780 ndel (- (match-end 0) checkbox-beg))
12781 ;; handle overlays when updating cookie from column view
12782 (when (setq ov (car (overlays-at checkbox-beg)))
12783 (setq ovs (overlay-start ov) ove (overlay-end ov))
12784 (delete-overlay ov))
12785 (goto-char checkbox-beg)
12786 (insert new)
12787 (delete-region (point) (+ (point) ndel))
12788 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12789 (when ov (move-overlay ov ovs ove)))
12790 (when cookie-present
12791 (run-hook-with-args 'org-after-todo-statistics-hook
12792 cnt-done (- cnt-all cnt-done))))))
12793 (run-hooks 'org-todo-statistics-hook)))
12795 (defvar org-after-todo-statistics-hook nil
12796 "Hook that is called after a TODO statistics cookie has been updated.
12797 Each function is called with two arguments: the number of not-done entries
12798 and the number of done entries.
12800 For example, the following function, when added to this hook, will switch
12801 an entry to DONE when all children are done, and back to TODO when new
12802 entries are set to a TODO status. Note that this hook is only called
12803 when there is a statistics cookie in the headline!
12805 (defun org-summary-todo (n-done n-not-done)
12806 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12807 (let (org-log-done org-log-states) ; turn off logging
12808 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12811 (defvar org-todo-statistics-hook nil
12812 "Hook that is run whenever Org thinks TODO statistics should be updated.
12813 This hook runs even if there is no statistics cookie present, in which case
12814 `org-after-todo-statistics-hook' would not run.")
12816 (defun org-todo-trigger-tag-changes (state)
12817 "Apply the changes defined in `org-todo-state-tags-triggers'."
12818 (let ((l org-todo-state-tags-triggers)
12819 changes)
12820 (when (or (not state) (equal state ""))
12821 (setq changes (append changes (cdr (assoc "" l)))))
12822 (when (and (stringp state) (> (length state) 0))
12823 (setq changes (append changes (cdr (assoc state l)))))
12824 (when (member state org-not-done-keywords)
12825 (setq changes (append changes (cdr (assoc 'todo l)))))
12826 (when (member state org-done-keywords)
12827 (setq changes (append changes (cdr (assoc 'done l)))))
12828 (dolist (c changes)
12829 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12831 (defun org-local-logging (value)
12832 "Get logging settings from a property VALUE."
12833 (let* (words w a)
12834 ;; directly set the variables, they are already local.
12835 (setq org-log-done nil
12836 org-log-repeat nil
12837 org-todo-log-states nil)
12838 (setq words (org-split-string value))
12839 (while (setq w (pop words))
12840 (cond
12841 ((setq a (assoc w org-startup-options))
12842 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12843 (set (nth 1 a) (nth 2 a))))
12844 ((setq a (org-extract-log-state-settings w))
12845 (and (member (car a) org-todo-keywords-1)
12846 (push a org-todo-log-states)))))))
12848 (defun org-get-todo-sequence-head (kwd)
12849 "Return the head of the TODO sequence to which KWD belongs.
12850 If KWD is not set, check if there is a text property remembering the
12851 right sequence."
12852 (let (p)
12853 (cond
12854 ((not kwd)
12855 (or (get-text-property (point-at-bol) 'org-todo-head)
12856 (progn
12857 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12858 nil (point-at-eol)))
12859 (get-text-property p 'org-todo-head))))
12860 ((not (member kwd org-todo-keywords-1))
12861 (car org-todo-keywords-1))
12862 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12864 (defun org-fast-todo-selection ()
12865 "Fast TODO keyword selection with single keys.
12866 Returns the new TODO keyword, or nil if no state change should occur."
12867 (let* ((fulltable org-todo-key-alist)
12868 (done-keywords org-done-keywords) ;; needed for the faces.
12869 (maxlen (apply 'max (mapcar
12870 (lambda (x)
12871 (if (stringp (car x)) (string-width (car x)) 0))
12872 fulltable)))
12873 (expert nil)
12874 (fwidth (+ maxlen 3 1 3))
12875 (ncol (/ (- (window-width) 4) fwidth))
12876 tg cnt e c tbl
12877 groups ingroup)
12878 (save-excursion
12879 (save-window-excursion
12880 (if expert
12881 (set-buffer (get-buffer-create " *Org todo*"))
12882 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12883 (erase-buffer)
12884 (org-set-local 'org-done-keywords done-keywords)
12885 (setq tbl fulltable cnt 0)
12886 (while (setq e (pop tbl))
12887 (cond
12888 ((equal e '(:startgroup))
12889 (push '() groups) (setq ingroup t)
12890 (when (not (= cnt 0))
12891 (setq cnt 0)
12892 (insert "\n"))
12893 (insert "{ "))
12894 ((equal e '(:endgroup))
12895 (setq ingroup nil cnt 0)
12896 (insert "}\n"))
12897 ((equal e '(:newline))
12898 (when (not (= cnt 0))
12899 (setq cnt 0)
12900 (insert "\n")
12901 (setq e (car tbl))
12902 (while (equal (car tbl) '(:newline))
12903 (insert "\n")
12904 (setq tbl (cdr tbl)))))
12906 (setq tg (car e) c (cdr e))
12907 (if ingroup (push tg (car groups)))
12908 (setq tg (org-add-props tg nil 'face
12909 (org-get-todo-face tg)))
12910 (if (and (= cnt 0) (not ingroup)) (insert " "))
12911 (insert "[" c "] " tg (make-string
12912 (- fwidth 4 (length tg)) ?\ ))
12913 (when (= (setq cnt (1+ cnt)) ncol)
12914 (insert "\n")
12915 (if ingroup (insert " "))
12916 (setq cnt 0)))))
12917 (insert "\n")
12918 (goto-char (point-min))
12919 (if (not expert) (org-fit-window-to-buffer))
12920 (message "[a-z..]:Set [SPC]:clear")
12921 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12922 (cond
12923 ((or (= c ?\C-g)
12924 (and (= c ?q) (not (rassoc c fulltable))))
12925 (setq quit-flag t))
12926 ((= c ?\ ) nil)
12927 ((setq e (rassoc c fulltable) tg (car e))
12929 (t (setq quit-flag t)))))))
12931 (defun org-entry-is-todo-p ()
12932 (member (org-get-todo-state) org-not-done-keywords))
12934 (defun org-entry-is-done-p ()
12935 (member (org-get-todo-state) org-done-keywords))
12937 (defun org-get-todo-state ()
12938 "Return the TODO keyword of the current subtree."
12939 (save-excursion
12940 (org-back-to-heading t)
12941 (and (looking-at org-todo-line-regexp)
12942 (match-end 2)
12943 (match-string 2))))
12945 (defun org-at-date-range-p (&optional inactive-ok)
12946 "Is the cursor inside a date range?"
12947 (interactive)
12948 (save-excursion
12949 (catch 'exit
12950 (let ((pos (point)))
12951 (skip-chars-backward "^[<\r\n")
12952 (skip-chars-backward "<[")
12953 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12954 (>= (match-end 0) pos)
12955 (throw 'exit t))
12956 (skip-chars-backward "^<[\r\n")
12957 (skip-chars-backward "<[")
12958 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12959 (>= (match-end 0) pos)
12960 (throw 'exit t)))
12961 nil)))
12963 (defun org-get-repeat (&optional tagline)
12964 "Check if there is a deadline/schedule with repeater in this entry."
12965 (save-match-data
12966 (save-excursion
12967 (org-back-to-heading t)
12968 (and (re-search-forward (if tagline
12969 (concat tagline "\\s-*" org-repeat-re)
12970 org-repeat-re)
12971 (org-entry-end-position) t)
12972 (match-string-no-properties 1)))))
12974 (defvar org-last-changed-timestamp)
12975 (defvar org-last-inserted-timestamp)
12976 (defvar org-log-post-message)
12977 (defvar org-log-note-purpose)
12978 (defvar org-log-note-how)
12979 (defvar org-log-note-extra)
12980 (defun org-auto-repeat-maybe (done-word)
12981 "Check if the current headline contains a repeated deadline/schedule.
12982 If yes, set TODO state back to what it was and change the base date
12983 of repeating deadline/scheduled time stamps to new date.
12984 This function is run automatically after each state change to a DONE state."
12985 ;; last-state is dynamically scoped into this function
12986 (let* ((repeat (org-get-repeat))
12987 (aa (assoc org-last-state org-todo-kwd-alist))
12988 (interpret (nth 1 aa))
12989 (head (nth 2 aa))
12990 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12991 (msg "Entry repeats: ")
12992 (org-log-done nil)
12993 (org-todo-log-states nil)
12994 re type n what ts time to-state)
12995 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
12996 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12997 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12998 org-todo-repeat-to-state))
12999 (unless (and to-state (member to-state org-todo-keywords-1))
13000 (setq to-state (if (eq interpret 'type) org-last-state head)))
13001 (org-todo to-state)
13002 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
13003 (org-entry-put nil "LAST_REPEAT" (format-time-string
13004 (org-time-stamp-format t t))))
13005 (when org-log-repeat
13006 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13007 (memq 'org-add-log-note post-command-hook))
13008 ;; OK, we are already setup for some record
13009 (if (eq org-log-repeat 'note)
13010 ;; make sure we take a note, not only a time stamp
13011 (setq org-log-note-how 'note))
13012 ;; Set up for taking a record
13013 (org-add-log-setup 'state (or done-word (car org-done-keywords))
13014 org-last-state
13015 'findpos org-log-repeat)))
13016 (org-back-to-heading t)
13017 (org-add-planning-info nil nil 'closed)
13018 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
13019 org-deadline-time-regexp "\\)\\|\\("
13020 org-ts-regexp "\\)"))
13021 (while (re-search-forward
13022 re (save-excursion (outline-next-heading) (point)) t)
13023 (setq type (if (match-end 1) org-scheduled-string
13024 (if (match-end 3) org-deadline-string "Plain:"))
13025 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
13026 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
13027 (setq n (string-to-number (match-string 2 ts))
13028 what (match-string 3 ts))
13029 (if (equal what "w") (setq n (* n 7) what "d"))
13030 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
13031 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
13032 ;; Preparation, see if we need to modify the start date for the change
13033 (when (match-end 1)
13034 (setq time (save-match-data (org-time-string-to-time ts)))
13035 (cond
13036 ((equal (match-string 1 ts) ".")
13037 ;; Shift starting date to today
13038 (org-timestamp-change
13039 (- (org-today) (time-to-days time))
13040 'day))
13041 ((equal (match-string 1 ts) "+")
13042 (let ((nshiftmax 10) (nshift 0))
13043 (while (or (= nshift 0)
13044 (<= (time-to-days time)
13045 (time-to-days (current-time))))
13046 (when (= (incf nshift) nshiftmax)
13047 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
13048 (error "Abort")))
13049 (org-timestamp-change n (cdr (assoc what whata)))
13050 (org-at-timestamp-p t)
13051 (setq ts (match-string 1))
13052 (setq time (save-match-data (org-time-string-to-time ts)))))
13053 (org-timestamp-change (- n) (cdr (assoc what whata)))
13054 ;; rematch, so that we have everything in place for the real shift
13055 (org-at-timestamp-p t)
13056 (setq ts (match-string 1))
13057 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
13058 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
13059 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
13060 (setq org-log-post-message msg)
13061 (message "%s" msg))))
13063 (defun org-show-todo-tree (arg)
13064 "Make a compact tree which shows all headlines marked with TODO.
13065 The tree will show the lines where the regexp matches, and all higher
13066 headlines above the match.
13067 With a \\[universal-argument] prefix, prompt for a regexp to match.
13068 With a numeric prefix N, construct a sparse tree for the Nth element
13069 of `org-todo-keywords-1'."
13070 (interactive "P")
13071 (let ((case-fold-search nil)
13072 (kwd-re
13073 (cond ((null arg) org-not-done-regexp)
13074 ((equal arg '(4))
13075 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
13076 (mapcar 'list org-todo-keywords-1))))
13077 (concat "\\("
13078 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13079 "\\)\\>")))
13080 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13081 (regexp-quote (nth (1- (prefix-numeric-value arg))
13082 org-todo-keywords-1)))
13083 (t (user-error "Invalid prefix argument: %s" arg)))))
13084 (message "%d TODO entries found"
13085 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13087 (defun org-deadline (arg &optional time)
13088 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13089 With one universal prefix argument, remove any deadline from the item.
13090 With two universal prefix arguments, prompt for a warning delay.
13091 With argument TIME, set the deadline at the corresponding date. TIME
13092 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13093 (interactive "P")
13094 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13095 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13096 'region-start-level 'region))
13097 org-loop-over-headlines-in-active-region)
13098 (org-map-entries
13099 `(org-deadline ',arg ,time)
13100 org-loop-over-headlines-in-active-region
13101 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13102 (let* ((old-date (org-entry-get nil "DEADLINE"))
13103 (old-date-time (if old-date (org-time-string-to-time old-date)))
13104 (repeater (and old-date
13105 (string-match
13106 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13107 old-date)
13108 (match-string 1 old-date))))
13109 (cond
13110 ((equal arg '(4))
13111 (when (and old-date org-log-redeadline)
13112 (org-add-log-setup 'deldeadline nil old-date 'findpos
13113 org-log-redeadline))
13114 (org-remove-timestamp-with-keyword org-deadline-string)
13115 (message "Item no longer has a deadline."))
13116 ((equal arg '(16))
13117 (save-excursion
13118 (org-back-to-heading t)
13119 (if (re-search-forward
13120 org-deadline-time-regexp
13121 (save-excursion (outline-next-heading) (point)) t)
13122 (let* ((rpl0 (match-string 1))
13123 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13124 (replace-match
13125 (concat org-deadline-string
13126 " <" rpl
13127 (format " -%dd"
13128 (abs
13129 (- (time-to-days
13130 (save-match-data
13131 (org-read-date nil t nil "Warn starting from" old-date-time)))
13132 (time-to-days old-date-time))))
13133 ">") t t))
13134 (user-error "No deadline information to update"))))
13136 (org-add-planning-info 'deadline time 'closed)
13137 (when (and old-date org-log-redeadline
13138 (not (equal old-date
13139 (substring org-last-inserted-timestamp 1 -1))))
13140 (org-add-log-setup 'redeadline nil old-date 'findpos
13141 org-log-redeadline))
13142 (when repeater
13143 (save-excursion
13144 (org-back-to-heading t)
13145 (when (re-search-forward (concat org-deadline-string " "
13146 org-last-inserted-timestamp)
13147 (save-excursion
13148 (outline-next-heading) (point)) t)
13149 (goto-char (1- (match-end 0)))
13150 (insert " " repeater)
13151 (setq org-last-inserted-timestamp
13152 (concat (substring org-last-inserted-timestamp 0 -1)
13153 " " repeater
13154 (substring org-last-inserted-timestamp -1))))))
13155 (message "Deadline on %s" org-last-inserted-timestamp))))))
13157 (defun org-schedule (arg &optional time)
13158 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13159 With one universal prefix argument, remove any scheduling date from the item.
13160 With two universal prefix arguments, prompt for a delay cookie.
13161 With argument TIME, scheduled at the corresponding date. TIME can
13162 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13163 (interactive "P")
13164 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13165 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13166 'region-start-level 'region))
13167 org-loop-over-headlines-in-active-region)
13168 (org-map-entries
13169 `(org-schedule ',arg ,time)
13170 org-loop-over-headlines-in-active-region
13171 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13172 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13173 (old-date-time (if old-date (org-time-string-to-time old-date)))
13174 (repeater (and old-date
13175 (string-match
13176 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13177 old-date)
13178 (match-string 1 old-date))))
13179 (cond
13180 ((equal arg '(4))
13181 (progn
13182 (when (and old-date org-log-reschedule)
13183 (org-add-log-setup 'delschedule nil old-date 'findpos
13184 org-log-reschedule))
13185 (org-remove-timestamp-with-keyword org-scheduled-string)
13186 (message "Item is no longer scheduled.")))
13187 ((equal arg '(16))
13188 (save-excursion
13189 (org-back-to-heading t)
13190 (if (re-search-forward
13191 org-scheduled-time-regexp
13192 (save-excursion (outline-next-heading) (point)) t)
13193 (let* ((rpl0 (match-string 1))
13194 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13195 (replace-match
13196 (concat org-scheduled-string
13197 " <" rpl
13198 (format " -%dd"
13199 (abs
13200 (- (time-to-days
13201 (save-match-data
13202 (org-read-date nil t nil "Delay until" old-date-time)))
13203 (time-to-days old-date-time))))
13204 ">") t t))
13205 (user-error "No scheduled information to update"))))
13207 (org-add-planning-info 'scheduled time 'closed)
13208 (when (and old-date org-log-reschedule
13209 (not (equal old-date
13210 (substring org-last-inserted-timestamp 1 -1))))
13211 (org-add-log-setup 'reschedule nil old-date 'findpos
13212 org-log-reschedule))
13213 (when repeater
13214 (save-excursion
13215 (org-back-to-heading t)
13216 (when (re-search-forward (concat org-scheduled-string " "
13217 org-last-inserted-timestamp)
13218 (save-excursion
13219 (outline-next-heading) (point)) t)
13220 (goto-char (1- (match-end 0)))
13221 (insert " " repeater)
13222 (setq org-last-inserted-timestamp
13223 (concat (substring org-last-inserted-timestamp 0 -1)
13224 " " repeater
13225 (substring org-last-inserted-timestamp -1))))))
13226 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13228 (defun org-get-scheduled-time (pom &optional inherit)
13229 "Get the scheduled time as a time tuple, of a format suitable
13230 for calling org-schedule with, or if there is no scheduling,
13231 returns nil."
13232 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13233 (when time
13234 (apply 'encode-time (org-parse-time-string time)))))
13236 (defun org-get-deadline-time (pom &optional inherit)
13237 "Get the deadline as a time tuple, of a format suitable for
13238 calling org-deadline with, or if there is no scheduling, returns
13239 nil."
13240 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13241 (when time
13242 (apply 'encode-time (org-parse-time-string time)))))
13244 (defun org-remove-timestamp-with-keyword (keyword)
13245 "Remove all time stamps with KEYWORD in the current entry."
13246 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13247 beg)
13248 (save-excursion
13249 (org-back-to-heading t)
13250 (setq beg (point))
13251 (outline-next-heading)
13252 (while (re-search-backward re beg t)
13253 (replace-match "")
13254 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13255 (equal (char-before) ?\ ))
13256 (backward-delete-char 1)
13257 (if (string-match "^[ \t]*$" (buffer-substring
13258 (point-at-bol) (point-at-eol)))
13259 (delete-region (point-at-bol)
13260 (min (point-max) (1+ (point-at-eol))))))))))
13262 (defvar org-time-was-given) ; dynamically scoped parameter
13263 (defvar org-end-time-was-given) ; dynamically scoped parameter
13265 (defun org-add-planning-info (what &optional time &rest remove)
13266 "Insert new timestamp with keyword in the line directly after the headline.
13267 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13268 If non is given, the user is prompted for a date.
13269 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13270 be removed."
13271 (interactive)
13272 (let (org-time-was-given org-end-time-was-given ts
13273 end default-time default-input)
13275 (catch 'exit
13276 (when (and (memq what '(scheduled deadline))
13277 (or (not time)
13278 (and (stringp time)
13279 (string-match "^[-+]+[0-9]" time))))
13280 ;; Try to get a default date/time from existing timestamp
13281 (save-excursion
13282 (org-back-to-heading t)
13283 (setq end (save-excursion (outline-next-heading) (point)))
13284 (when (re-search-forward (if (eq what 'scheduled)
13285 org-scheduled-time-regexp
13286 org-deadline-time-regexp)
13287 end t)
13288 (setq ts (match-string 1)
13289 default-time
13290 (apply 'encode-time (org-parse-time-string ts))
13291 default-input (and ts (org-get-compact-tod ts))))))
13292 (when what
13293 (setq time
13294 (if (stringp time)
13295 ;; This is a string (relative or absolute), set proper date
13296 (apply 'encode-time
13297 (org-read-date-analyze
13298 time default-time (decode-time default-time)))
13299 ;; If necessary, get the time from the user
13300 (or time (org-read-date nil 'to-time nil nil
13301 default-time default-input)))))
13303 (when (and org-insert-labeled-timestamps-at-point
13304 (member what '(scheduled deadline)))
13305 (insert
13306 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13307 (org-insert-time-stamp time org-time-was-given
13308 nil nil nil (list org-end-time-was-given))
13309 (setq what nil))
13310 (save-excursion
13311 (save-restriction
13312 (let (col list elt ts buffer-invisibility-spec)
13313 (org-back-to-heading t)
13314 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13315 (goto-char (match-end 1))
13316 (setq col (current-column))
13317 (goto-char (match-end 0))
13318 (if (eobp) (insert "\n") (forward-char 1))
13319 (when (and (not what)
13320 (not (looking-at
13321 (concat "[ \t]*"
13322 org-keyword-time-not-clock-regexp))))
13323 ;; Nothing to add, nothing to remove...... :-)
13324 (throw 'exit nil))
13325 (if (and (not (looking-at org-outline-regexp))
13326 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13327 "[^\r\n]*"))
13328 (not (equal (match-string 1) org-clock-string)))
13329 (narrow-to-region (match-beginning 0) (match-end 0))
13330 (insert-before-markers "\n")
13331 (backward-char 1)
13332 (narrow-to-region (point) (point))
13333 (and org-adapt-indentation (org-indent-to-column col)))
13334 ;; Check if we have to remove something.
13335 (setq list (cons what remove))
13336 (while list
13337 (setq elt (pop list))
13338 (when (or (and (eq elt 'scheduled)
13339 (re-search-forward org-scheduled-time-regexp nil t))
13340 (and (eq elt 'deadline)
13341 (re-search-forward org-deadline-time-regexp nil t))
13342 (and (eq elt 'closed)
13343 (re-search-forward org-closed-time-regexp nil t)))
13344 (replace-match "")
13345 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13346 (and (looking-at "[ \t]+") (replace-match ""))
13347 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13348 (when what
13349 (insert
13350 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13351 (cond ((eq what 'scheduled) org-scheduled-string)
13352 ((eq what 'deadline) org-deadline-string)
13353 ((eq what 'closed) org-closed-string))
13354 " ")
13355 (setq ts (org-insert-time-stamp
13356 time
13357 (or org-time-was-given
13358 (and (eq what 'closed) org-log-done-with-time))
13359 (eq what 'closed)
13360 nil nil (list org-end-time-was-given)))
13361 (insert
13362 (if (not (or (bolp) (eq (char-before) ?\ )
13363 (memq (char-after) '(32 10))
13364 (eobp))) " " ""))
13365 (end-of-line 1))
13366 (goto-char (point-min))
13367 (widen)
13368 (if (and (looking-at "[ \t]*\n")
13369 (equal (char-before) ?\n))
13370 (delete-region (1- (point)) (point-at-eol)))
13371 ts))))))
13373 (defvar org-log-note-marker (make-marker))
13374 (defvar org-log-note-purpose nil)
13375 (defvar org-log-note-state nil)
13376 (defvar org-log-note-previous-state nil)
13377 (defvar org-log-note-how nil)
13378 (defvar org-log-note-extra nil)
13379 (defvar org-log-note-window-configuration nil)
13380 (defvar org-log-note-return-to (make-marker))
13381 (defvar org-log-note-effective-time nil
13382 "Remembered current time so that dynamically scoped
13383 `org-extend-today-until' affects tha timestamps in state change
13384 log")
13386 (defvar org-log-post-message nil
13387 "Message to be displayed after a log note has been stored.
13388 The auto-repeater uses this.")
13390 (defun org-add-note ()
13391 "Add a note to the current entry.
13392 This is done in the same way as adding a state change note."
13393 (interactive)
13394 (org-add-log-setup 'note nil nil 'findpos nil))
13396 (defvar org-property-end-re)
13397 (defun org-add-log-setup (&optional purpose state prev-state
13398 findpos how extra)
13399 "Set up the post command hook to take a note.
13400 If this is about to TODO state change, the new state is expected in STATE.
13401 When FINDPOS is non-nil, find the correct position for the note in
13402 the current entry. If not, assume that it can be inserted at point.
13403 HOW is an indicator what kind of note should be created.
13404 EXTRA is additional text that will be inserted into the notes buffer."
13405 (let* ((org-log-into-drawer (org-log-into-drawer))
13406 (drawer (cond ((stringp org-log-into-drawer)
13407 org-log-into-drawer)
13408 (org-log-into-drawer "LOGBOOK"))))
13409 (save-restriction
13410 (save-excursion
13411 (when findpos
13412 (org-back-to-heading t)
13413 (narrow-to-region (point) (save-excursion
13414 (outline-next-heading) (point)))
13415 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13416 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13417 "[^\r\n]*\\)?"))
13418 (goto-char (match-end 0))
13419 (cond
13420 (drawer
13421 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13422 nil t)
13423 (progn
13424 (goto-char (match-end 0))
13425 (or org-log-states-order-reversed
13426 (and (re-search-forward org-property-end-re nil t)
13427 (goto-char (1- (match-beginning 0))))))
13428 (insert "\n:" drawer ":\n:END:")
13429 (beginning-of-line 0)
13430 (org-indent-line)
13431 (beginning-of-line 2)
13432 (org-indent-line)
13433 (end-of-line 0)))
13434 ((and org-log-state-notes-insert-after-drawers
13435 (save-excursion
13436 (forward-line) (looking-at org-drawer-regexp)))
13437 (forward-line)
13438 (while (looking-at org-drawer-regexp)
13439 (goto-char (match-end 0))
13440 (re-search-forward org-property-end-re (point-max) t)
13441 (forward-line))
13442 (forward-line -1)))
13443 (unless org-log-states-order-reversed
13444 (and (= (char-after) ?\n) (forward-char 1))
13445 (org-skip-over-state-notes)
13446 (skip-chars-backward " \t\n\r")))
13447 (move-marker org-log-note-marker (point))
13448 (setq org-log-note-purpose purpose
13449 org-log-note-state state
13450 org-log-note-previous-state prev-state
13451 org-log-note-how how
13452 org-log-note-extra extra
13453 org-log-note-effective-time (org-current-effective-time))
13454 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13456 (defun org-skip-over-state-notes ()
13457 "Skip past the list of State notes in an entry."
13458 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13459 (when (ignore-errors (goto-char (org-in-item-p)))
13460 (let* ((struct (org-list-struct))
13461 (prevs (org-list-prevs-alist struct)))
13462 (while (looking-at "[ \t]*- State")
13463 (goto-char (or (org-list-get-next-item (point) struct prevs)
13464 (org-list-get-item-end (point) struct)))))))
13466 (defun org-add-log-note (&optional purpose)
13467 "Pop up a window for taking a note, and add this note later at point."
13468 (remove-hook 'post-command-hook 'org-add-log-note)
13469 (setq org-log-note-window-configuration (current-window-configuration))
13470 (delete-other-windows)
13471 (move-marker org-log-note-return-to (point))
13472 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13473 (goto-char org-log-note-marker)
13474 (org-switch-to-buffer-other-window "*Org Note*")
13475 (erase-buffer)
13476 (if (memq org-log-note-how '(time state))
13477 (let (current-prefix-arg) (org-store-log-note))
13478 (let ((org-inhibit-startup t)) (org-mode))
13479 (insert (format "# Insert note for %s.
13480 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13481 (cond
13482 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13483 ((eq org-log-note-purpose 'done) "closed todo item")
13484 ((eq org-log-note-purpose 'state)
13485 (format "state change from \"%s\" to \"%s\""
13486 (or org-log-note-previous-state "")
13487 (or org-log-note-state "")))
13488 ((eq org-log-note-purpose 'reschedule)
13489 "rescheduling")
13490 ((eq org-log-note-purpose 'delschedule)
13491 "no longer scheduled")
13492 ((eq org-log-note-purpose 'redeadline)
13493 "changing deadline")
13494 ((eq org-log-note-purpose 'deldeadline)
13495 "removing deadline")
13496 ((eq org-log-note-purpose 'refile)
13497 "refiling")
13498 ((eq org-log-note-purpose 'note)
13499 "this entry")
13500 (t (error "This should not happen")))))
13501 (if org-log-note-extra (insert org-log-note-extra))
13502 (org-set-local 'org-finish-function 'org-store-log-note)
13503 (run-hooks 'org-log-buffer-setup-hook)))
13505 (defvar org-note-abort nil) ; dynamically scoped
13506 (defun org-store-log-note ()
13507 "Finish taking a log note, and insert it to where it belongs."
13508 (let ((txt (buffer-string)))
13509 (kill-buffer (current-buffer))
13510 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13511 lines ind bul)
13512 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13513 (setq txt (replace-match "" t t txt)))
13514 (if (string-match "\\s-+\\'" txt)
13515 (setq txt (replace-match "" t t txt)))
13516 (setq lines (org-split-string txt "\n"))
13517 (when (and note (string-match "\\S-" note))
13518 (setq note
13519 (org-replace-escapes
13520 note
13521 (list (cons "%u" (user-login-name))
13522 (cons "%U" user-full-name)
13523 (cons "%t" (format-time-string
13524 (org-time-stamp-format 'long 'inactive)
13525 org-log-note-effective-time))
13526 (cons "%T" (format-time-string
13527 (org-time-stamp-format 'long nil)
13528 org-log-note-effective-time))
13529 (cons "%d" (format-time-string
13530 (org-time-stamp-format nil 'inactive)
13531 org-log-note-effective-time))
13532 (cons "%D" (format-time-string
13533 (org-time-stamp-format nil nil)
13534 org-log-note-effective-time))
13535 (cons "%s" (if org-log-note-state
13536 (concat "\"" org-log-note-state "\"")
13537 ""))
13538 (cons "%S" (if org-log-note-previous-state
13539 (concat "\"" org-log-note-previous-state "\"")
13540 "\"\"")))))
13541 (if lines (setq note (concat note " \\\\")))
13542 (push note lines))
13543 (when (or current-prefix-arg org-note-abort)
13544 (when org-log-into-drawer
13545 (org-remove-empty-drawer-at org-log-note-marker))
13546 (setq lines nil))
13547 (when lines
13548 (with-current-buffer (marker-buffer org-log-note-marker)
13549 (save-excursion
13550 (goto-char org-log-note-marker)
13551 (move-marker org-log-note-marker nil)
13552 (end-of-line 1)
13553 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13554 (setq ind (save-excursion
13555 (if (ignore-errors (goto-char (org-in-item-p)))
13556 (let ((struct (org-list-struct)))
13557 (org-list-get-ind
13558 (org-list-get-top-point struct) struct))
13559 (skip-chars-backward " \r\t\n")
13560 (cond
13561 ((and (org-at-heading-p)
13562 org-adapt-indentation)
13563 (1+ (org-current-level)))
13564 ((org-at-heading-p) 0)
13565 (t (org-get-indentation))))))
13566 (setq bul (org-list-bullet-string "-"))
13567 (org-indent-line-to ind)
13568 (insert bul (pop lines))
13569 (let ((ind-body (+ (length bul) ind)))
13570 (while lines
13571 (insert "\n")
13572 (org-indent-line-to ind-body)
13573 (insert (pop lines))))
13574 (message "Note stored")
13575 (org-back-to-heading t)
13576 (org-cycle-hide-drawers 'children))
13577 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13578 ;; from within `org-add-log-note' because `buffer-undo-list'
13579 ;; is then modified outside of `org-with-remote-undo'.
13580 (when (eq this-command 'org-agenda-todo)
13581 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13582 ;; Don't add undo information when called from `org-agenda-todo'
13583 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13584 (set-window-configuration org-log-note-window-configuration)
13585 (with-current-buffer (marker-buffer org-log-note-return-to)
13586 (goto-char org-log-note-return-to))
13587 (move-marker org-log-note-return-to nil)
13588 (and org-log-post-message (message "%s" org-log-post-message))))
13590 (defun org-remove-empty-drawer-at (pos)
13591 "Remove an empty drawer at position POS.
13592 POS may also be a marker."
13593 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13594 (org-with-wide-buffer
13595 (goto-char pos)
13596 (let ((drawer (org-element-at-point)))
13597 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13598 (not (org-element-property :contents-begin drawer)))
13599 (delete-region (org-element-property :begin drawer)
13600 (progn (goto-char (org-element-property :end drawer))
13601 (skip-chars-backward " \r\t\n")
13602 (forward-line)
13603 (point))))))))
13605 (defvar org-ts-type nil)
13606 (defun org-sparse-tree (&optional arg type)
13607 "Create a sparse tree, prompt for the details.
13608 This command can create sparse trees. You first need to select the type
13609 of match used to create the tree:
13611 t Show all TODO entries.
13612 T Show entries with a specific TODO keyword.
13613 m Show entries selected by a tags/property match.
13614 p Enter a property name and its value (both with completion on existing
13615 names/values) and show entries with that property.
13616 r Show entries matching a regular expression (`/' can be used as well).
13617 b Show deadlines and scheduled items before a date.
13618 a Show deadlines and scheduled items after a date.
13619 d Show deadlines due within `org-deadline-warning-days'.
13620 D Show deadlines and scheduled items between a date range."
13621 (interactive "P")
13622 (let (ans kwd value ts-type)
13623 (setq type (or type org-sparse-tree-default-date-type))
13624 (setq org-ts-type type)
13625 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty\n [d]eadlines [b]efore-date [a]fter-date [D]ates range\n [c]ycle through date types: %s"
13626 (cond ((eq type 'all) "all timestamps")
13627 ((eq type 'scheduled) "only scheduled")
13628 ((eq type 'deadline) "only deadline")
13629 ((eq type 'active) "only active timestamps")
13630 ((eq type 'inactive) "only inactive timestamps")
13631 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13632 ((eq type 'closed) "with a closed time-stamp")
13633 (t "scheduled/deadline")))
13634 (setq ans (read-char-exclusive))
13635 (cond
13636 ((equal ans ?c)
13637 (org-sparse-tree
13638 arg (cadr (member type '(scheduled-or-deadline
13639 all scheduled deadline active inactive closed)))))
13640 ((equal ans ?d)
13641 (call-interactively 'org-check-deadlines))
13642 ((equal ans ?b)
13643 (call-interactively 'org-check-before-date))
13644 ((equal ans ?a)
13645 (call-interactively 'org-check-after-date))
13646 ((equal ans ?D)
13647 (call-interactively 'org-check-dates-range))
13648 ((equal ans ?t)
13649 (call-interactively 'org-show-todo-tree))
13650 ((equal ans ?T)
13651 (org-show-todo-tree '(4)))
13652 ((member ans '(?T ?m))
13653 (call-interactively 'org-match-sparse-tree))
13654 ((member ans '(?p ?P))
13655 (setq kwd (org-icompleting-read "Property: "
13656 (mapcar 'list (org-buffer-property-keys))))
13657 (setq value (org-icompleting-read "Value: "
13658 (mapcar 'list (org-property-values kwd))))
13659 (unless (string-match "\\`{.*}\\'" value)
13660 (setq value (concat "\"" value "\"")))
13661 (org-match-sparse-tree arg (concat kwd "=" value)))
13662 ((member ans '(?r ?R ?/))
13663 (call-interactively 'org-occur))
13664 (t (user-error "No such sparse tree command \"%c\"" ans)))))
13666 (defvar org-occur-highlights nil
13667 "List of overlays used for occur matches.")
13668 (make-variable-buffer-local 'org-occur-highlights)
13669 (defvar org-occur-parameters nil
13670 "Parameters of the active org-occur calls.
13671 This is a list, each call to org-occur pushes as cons cell,
13672 containing the regular expression and the callback, onto the list.
13673 The list can contain several entries if `org-occur' has been called
13674 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13675 will only contain one set of parameters. When the highlights are
13676 removed (for example with `C-c C-c', or with the next edit (depending
13677 on `org-remove-highlights-with-change'), this variable is emptied
13678 as well.")
13679 (make-variable-buffer-local 'org-occur-parameters)
13681 (defun org-occur (regexp &optional keep-previous callback)
13682 "Make a compact tree which shows all matches of REGEXP.
13683 The tree will show the lines where the regexp matches, and all higher
13684 headlines above the match. It will also show the heading after the match,
13685 to make sure editing the matching entry is easy.
13686 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13687 call to `org-occur' will be kept, to allow stacking of calls to this
13688 command.
13689 If CALLBACK is non-nil, it is a function which is called to confirm
13690 that the match should indeed be shown."
13691 (interactive "sRegexp: \nP")
13692 (when (equal regexp "")
13693 (user-error "Regexp cannot be empty"))
13694 (unless keep-previous
13695 (org-remove-occur-highlights nil nil t))
13696 (push (cons regexp callback) org-occur-parameters)
13697 (let ((cnt 0))
13698 (save-excursion
13699 (goto-char (point-min))
13700 (if (or (not keep-previous) ; do not want to keep
13701 (not org-occur-highlights)) ; no previous matches
13702 ;; hide everything
13703 (org-overview))
13704 (while (re-search-forward regexp nil t)
13705 (when (or (not callback)
13706 (save-match-data (funcall callback)))
13707 (setq cnt (1+ cnt))
13708 (when org-highlight-sparse-tree-matches
13709 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13710 (org-show-context 'occur-tree))))
13711 (when org-remove-highlights-with-change
13712 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13713 nil 'local))
13714 (unless org-sparse-tree-open-archived-trees
13715 (org-hide-archived-subtrees (point-min) (point-max)))
13716 (run-hooks 'org-occur-hook)
13717 (if (org-called-interactively-p 'interactive)
13718 (message "%d match(es) for regexp %s" cnt regexp))
13719 cnt))
13721 (defun org-occur-next-match (&optional n reset)
13722 "Function for `next-error-function' to find sparse tree matches.
13723 N is the number of matches to move, when negative move backwards.
13724 RESET is entirely ignored - this function always goes back to the
13725 starting point when no match is found."
13726 (let* ((limit (if (< n 0) (point-min) (point-max)))
13727 (search-func (if (< n 0)
13728 'previous-single-char-property-change
13729 'next-single-char-property-change))
13730 (n (abs n))
13731 (pos (point))
13733 (catch 'exit
13734 (while (setq p1 (funcall search-func (point) 'org-type))
13735 (when (equal p1 limit)
13736 (goto-char pos)
13737 (error "No more matches"))
13738 (when (equal (get-char-property p1 'org-type) 'org-occur)
13739 (setq n (1- n))
13740 (when (= n 0)
13741 (goto-char p1)
13742 (throw 'exit (point))))
13743 (goto-char p1))
13744 (goto-char p1)
13745 (error "No more matches"))))
13747 (defun org-show-context (&optional key)
13748 "Make sure point and context are visible.
13749 How much context is shown depends upon the variables
13750 `org-show-hierarchy-above', `org-show-following-heading',
13751 `org-show-entry-below' and `org-show-siblings'."
13752 (let ((heading-p (org-at-heading-p t))
13753 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13754 (following-p (org-get-alist-option org-show-following-heading key))
13755 (entry-p (org-get-alist-option org-show-entry-below key))
13756 (siblings-p (org-get-alist-option org-show-siblings key)))
13757 ;; Show heading or entry text
13758 (if (and heading-p (not entry-p))
13759 (org-flag-heading nil) ; only show the heading
13760 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13761 (org-show-hidden-entry))) ; show entire entry
13762 (when following-p
13763 ;; Show next sibling, or heading below text
13764 (save-excursion
13765 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13766 (org-flag-heading nil))))
13767 (when siblings-p (org-show-siblings))
13768 (when hierarchy-p
13769 ;; show all higher headings, possibly with siblings
13770 (save-excursion
13771 (while (and (condition-case nil
13772 (progn (org-up-heading-all 1) t)
13773 (error nil))
13774 (not (bobp)))
13775 (org-flag-heading nil)
13776 (when siblings-p (org-show-siblings)))))
13777 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13779 (defvar org-reveal-start-hook nil
13780 "Hook run before revealing a location.")
13782 (defun org-reveal (&optional siblings)
13783 "Show current entry, hierarchy above it, and the following headline.
13784 This can be used to show a consistent set of context around locations
13785 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13786 not t for the search context.
13788 With optional argument SIBLINGS, on each level of the hierarchy all
13789 siblings are shown. This repairs the tree structure to what it would
13790 look like when opened with hierarchical calls to `org-cycle'.
13791 With double optional argument \\[universal-argument] \\[universal-argument], \
13792 go to the parent and show the
13793 entire tree."
13794 (interactive "P")
13795 (run-hooks 'org-reveal-start-hook)
13796 (let ((org-show-hierarchy-above t)
13797 (org-show-following-heading t)
13798 (org-show-siblings (if siblings t org-show-siblings)))
13799 (org-show-context nil))
13800 (when (equal siblings '(16))
13801 (save-excursion
13802 (when (org-up-heading-safe)
13803 (org-show-subtree)
13804 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13806 (defun org-highlight-new-match (beg end)
13807 "Highlight from BEG to END and mark the highlight is an occur headline."
13808 (let ((ov (make-overlay beg end)))
13809 (overlay-put ov 'face 'secondary-selection)
13810 (overlay-put ov 'org-type 'org-occur)
13811 (push ov org-occur-highlights)))
13813 (defun org-remove-occur-highlights (&optional beg end noremove)
13814 "Remove the occur highlights from the buffer.
13815 BEG and END are ignored. If NOREMOVE is nil, remove this function
13816 from the `before-change-functions' in the current buffer."
13817 (interactive)
13818 (unless org-inhibit-highlight-removal
13819 (mapc 'delete-overlay org-occur-highlights)
13820 (setq org-occur-highlights nil)
13821 (setq org-occur-parameters nil)
13822 (unless noremove
13823 (remove-hook 'before-change-functions
13824 'org-remove-occur-highlights 'local))))
13826 ;;;; Priorities
13828 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13829 "Regular expression matching the priority indicator.")
13831 (defvar org-remove-priority-next-time nil)
13833 (defun org-priority-up ()
13834 "Increase the priority of the current item."
13835 (interactive)
13836 (org-priority 'up))
13838 (defun org-priority-down ()
13839 "Decrease the priority of the current item."
13840 (interactive)
13841 (org-priority 'down))
13843 (defun org-priority (&optional action show)
13844 "Change the priority of an item.
13845 ACTION can be `set', `up', `down', or a character."
13846 (interactive "P")
13847 (if (equal action '(4))
13848 (org-show-priority)
13849 (unless org-enable-priority-commands
13850 (user-error "Priority commands are disabled"))
13851 (setq action (or action 'set))
13852 (let (current new news have remove)
13853 (save-excursion
13854 (org-back-to-heading t)
13855 (if (looking-at org-priority-regexp)
13856 (setq current (string-to-char (match-string 2))
13857 have t))
13858 (cond
13859 ((eq action 'remove)
13860 (setq remove t new ?\ ))
13861 ((or (eq action 'set)
13862 (if (featurep 'xemacs) (characterp action) (integerp action)))
13863 (if (not (eq action 'set))
13864 (setq new action)
13865 (message "Priority %c-%c, SPC to remove: "
13866 org-highest-priority org-lowest-priority)
13867 (save-match-data
13868 (setq new (read-char-exclusive))))
13869 (if (and (= (upcase org-highest-priority) org-highest-priority)
13870 (= (upcase org-lowest-priority) org-lowest-priority))
13871 (setq new (upcase new)))
13872 (cond ((equal new ?\ ) (setq remove t))
13873 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13874 (user-error "Priority must be between `%c' and `%c'"
13875 org-highest-priority org-lowest-priority))))
13876 ((eq action 'up)
13877 (setq new (if have
13878 (1- current) ; normal cycling
13879 ;; last priority was empty
13880 (if (eq last-command this-command)
13881 org-lowest-priority ; wrap around empty to lowest
13882 ;; default
13883 (if org-priority-start-cycle-with-default
13884 org-default-priority
13885 (1- org-default-priority))))))
13886 ((eq action 'down)
13887 (setq new (if have
13888 (1+ current) ; normal cycling
13889 ;; last priority was empty
13890 (if (eq last-command this-command)
13891 org-highest-priority ; wrap around empty to highest
13892 ;; default
13893 (if org-priority-start-cycle-with-default
13894 org-default-priority
13895 (1+ org-default-priority))))))
13896 (t (user-error "Invalid action")))
13897 (if (or (< (upcase new) org-highest-priority)
13898 (> (upcase new) org-lowest-priority))
13899 (if (and (memq action '(up down))
13900 (not have) (not (eq last-command this-command)))
13901 ;; `new' is from default priority
13902 (error
13903 "The default can not be set, see `org-default-priority' why")
13904 ;; normal cycling: `new' is beyond highest/lowest priority
13905 ;; and is wrapped around to the empty priority
13906 (setq remove t)))
13907 (setq news (format "%c" new))
13908 (if have
13909 (if remove
13910 (replace-match "" t t nil 1)
13911 (replace-match news t t nil 2))
13912 (if remove
13913 (user-error "No priority cookie found in line")
13914 (let ((case-fold-search nil))
13915 (looking-at org-todo-line-regexp))
13916 (if (match-end 2)
13917 (progn
13918 (goto-char (match-end 2))
13919 (insert " [#" news "]"))
13920 (goto-char (match-beginning 3))
13921 (insert "[#" news "] "))))
13922 (org-set-tags nil 'align))
13923 (if remove
13924 (message "Priority removed")
13925 (message "Priority of current item set to %s" news)))))
13927 (defun org-show-priority ()
13928 "Show the priority of the current item.
13929 This priority is composed of the main priority given with the [#A] cookies,
13930 and by additional input from the age of a schedules or deadline entry."
13931 (interactive)
13932 (let ((pri (if (eq major-mode 'org-agenda-mode)
13933 (org-get-at-bol 'priority)
13934 (save-excursion
13935 (save-match-data
13936 (beginning-of-line)
13937 (and (looking-at org-heading-regexp)
13938 (org-get-priority (match-string 0))))))))
13939 (message "Priority is %d" (if pri pri -1000))))
13941 (defun org-get-priority (s)
13942 "Find priority cookie and return priority."
13943 (save-match-data
13944 (if (functionp org-get-priority-function)
13945 (funcall org-get-priority-function)
13946 (if (not (string-match org-priority-regexp s))
13947 (* 1000 (- org-lowest-priority org-default-priority))
13948 (* 1000 (- org-lowest-priority
13949 (string-to-char (match-string 2 s))))))))
13951 ;;;; Tags
13953 (defvar org-agenda-archives-mode)
13954 (defvar org-map-continue-from nil
13955 "Position from where mapping should continue.
13956 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13958 (defvar org-scanner-tags nil
13959 "The current tag list while the tags scanner is running.")
13960 (defvar org-trust-scanner-tags nil
13961 "Should `org-get-tags-at' use the tags for the scanner.
13962 This is for internal dynamical scoping only.
13963 When this is non-nil, the function `org-get-tags-at' will return the value
13964 of `org-scanner-tags' instead of building the list by itself. This
13965 can lead to large speed-ups when the tags scanner is used in a file with
13966 many entries, and when the list of tags is retrieved, for example to
13967 obtain a list of properties. Building the tags list for each entry in such
13968 a file becomes an N^2 operation - but with this variable set, it scales
13969 as N.")
13971 (defun org-scan-tags (action matcher todo-only &optional start-level)
13972 "Sca headline tags with inheritance and produce output ACTION.
13974 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13975 or `agenda' to produce an entry list for an agenda view. It can also be
13976 a Lisp form or a function that should be called at each matched headline, in
13977 this case the return value is a list of all return values from these calls.
13979 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13980 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13981 only lines with a not-done TODO keyword are included in the output.
13982 This should be the same variable that was scoped into
13983 and set by `org-make-tags-matcher' when it constructed MATCHER.
13985 START-LEVEL can be a string with asterisks, reducing the scope to
13986 headlines matching this string."
13987 (require 'org-agenda)
13988 (let* ((re (concat "^"
13989 (if start-level
13990 ;; Get the correct level to match
13991 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13992 org-outline-regexp)
13993 " *\\(\\<\\("
13994 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13995 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13996 (props (list 'face 'default
13997 'done-face 'org-agenda-done
13998 'undone-face 'default
13999 'mouse-face 'highlight
14000 'org-not-done-regexp org-not-done-regexp
14001 'org-todo-regexp org-todo-regexp
14002 'org-complex-heading-regexp org-complex-heading-regexp
14003 'help-echo
14004 (format "mouse-2 or RET jump to org file %s"
14005 (abbreviate-file-name
14006 (or (buffer-file-name (buffer-base-buffer))
14007 (buffer-name (buffer-base-buffer)))))))
14008 (org-map-continue-from nil)
14009 lspos tags tags-list
14010 (tags-alist (list (cons 0 org-file-tags)))
14011 (llast 0) rtn rtn1 level category i txt
14012 todo marker entry priority)
14013 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
14014 (setq action (list 'lambda nil action)))
14015 (save-excursion
14016 (goto-char (point-min))
14017 (when (eq action 'sparse-tree)
14018 (org-overview)
14019 (org-remove-occur-highlights))
14020 (while (let (case-fold-search)
14021 (re-search-forward re nil t))
14022 (setq org-map-continue-from nil)
14023 (catch :skip
14024 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
14025 tags (if (match-end 4) (org-match-string-no-properties 4)))
14026 (goto-char (setq lspos (match-beginning 0)))
14027 (setq level (org-reduced-level (org-outline-level))
14028 category (org-get-category))
14029 (setq i llast llast level)
14030 ;; remove tag lists from same and sublevels
14031 (while (>= i level)
14032 (when (setq entry (assoc i tags-alist))
14033 (setq tags-alist (delete entry tags-alist)))
14034 (setq i (1- i)))
14035 ;; add the next tags
14036 (when tags
14037 (setq tags (org-split-string tags ":")
14038 tags-alist
14039 (cons (cons level tags) tags-alist)))
14040 ;; compile tags for current headline
14041 (setq tags-list
14042 (if org-use-tag-inheritance
14043 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14044 tags)
14045 org-scanner-tags tags-list)
14046 (when org-use-tag-inheritance
14047 (setcdr (car tags-alist)
14048 (mapcar (lambda (x)
14049 (setq x (copy-sequence x))
14050 (org-add-prop-inherited x))
14051 (cdar tags-alist))))
14052 (when (and tags org-use-tag-inheritance
14053 (or (not (eq t org-use-tag-inheritance))
14054 org-tags-exclude-from-inheritance))
14055 ;; selective inheritance, remove uninherited ones
14056 (setcdr (car tags-alist)
14057 (org-remove-uninherited-tags (cdar tags-alist))))
14058 (when (and
14060 ;; eval matcher only when the todo condition is OK
14061 (and (or (not todo-only) (member todo org-not-done-keywords))
14062 (let ((case-fold-search t) (org-trust-scanner-tags t))
14063 (eval matcher)))
14065 ;; Call the skipper, but return t if it does not skip,
14066 ;; so that the `and' form continues evaluating
14067 (progn
14068 (unless (eq action 'sparse-tree) (org-agenda-skip))
14071 ;; Check if timestamps are deselecting this entry
14072 (or (not todo-only)
14073 (and (member todo org-not-done-keywords)
14074 (or (not org-agenda-tags-todo-honor-ignore-options)
14075 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14077 ;; select this headline
14078 (cond
14079 ((eq action 'sparse-tree)
14080 (and org-highlight-sparse-tree-matches
14081 (org-get-heading) (match-end 0)
14082 (org-highlight-new-match
14083 (match-beginning 1) (match-end 1)))
14084 (org-show-context 'tags-tree))
14085 ((eq action 'agenda)
14086 (setq txt (org-agenda-format-item
14088 (concat
14089 (if (eq org-tags-match-list-sublevels 'indented)
14090 (make-string (1- level) ?.) "")
14091 (org-get-heading))
14092 level category
14093 tags-list)
14094 priority (org-get-priority txt))
14095 (goto-char lspos)
14096 (setq marker (org-agenda-new-marker))
14097 (org-add-props txt props
14098 'org-marker marker 'org-hd-marker marker 'org-category category
14099 'todo-state todo
14100 'priority priority 'type "tagsmatch")
14101 (push txt rtn))
14102 ((functionp action)
14103 (setq org-map-continue-from nil)
14104 (save-excursion
14105 (setq rtn1 (funcall action))
14106 (push rtn1 rtn)))
14107 (t (user-error "Invalid action")))
14109 ;; if we are to skip sublevels, jump to end of subtree
14110 (unless org-tags-match-list-sublevels
14111 (org-end-of-subtree t)
14112 (backward-char 1))))
14113 ;; Get the correct position from where to continue
14114 (if org-map-continue-from
14115 (goto-char org-map-continue-from)
14116 (and (= (point) lspos) (end-of-line 1)))))
14117 (when (and (eq action 'sparse-tree)
14118 (not org-sparse-tree-open-archived-trees))
14119 (org-hide-archived-subtrees (point-min) (point-max)))
14120 (nreverse rtn)))
14122 (defun org-remove-uninherited-tags (tags)
14123 "Remove all tags that are not inherited from the list TAGS."
14124 (cond
14125 ((eq org-use-tag-inheritance t)
14126 (if org-tags-exclude-from-inheritance
14127 (org-delete-all org-tags-exclude-from-inheritance tags)
14128 tags))
14129 ((not org-use-tag-inheritance) nil)
14130 ((stringp org-use-tag-inheritance)
14131 (delq nil (mapcar
14132 (lambda (x)
14133 (if (and (string-match org-use-tag-inheritance x)
14134 (not (member x org-tags-exclude-from-inheritance)))
14135 x nil))
14136 tags)))
14137 ((listp org-use-tag-inheritance)
14138 (delq nil (mapcar
14139 (lambda (x)
14140 (if (member x org-use-tag-inheritance) x nil))
14141 tags)))))
14143 (defun org-match-sparse-tree (&optional todo-only match)
14144 "Create a sparse tree according to tags string MATCH.
14145 MATCH can contain positive and negative selection of tags, like
14146 \"+WORK+URGENT-WITHBOSS\".
14147 If optional argument TODO-ONLY is non-nil, only select lines that are
14148 also TODO lines."
14149 (interactive "P")
14150 (org-agenda-prepare-buffers (list (current-buffer)))
14151 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
14153 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14155 (defvar org-cached-props nil)
14156 (defun org-cached-entry-get (pom property)
14157 (if (or (eq t org-use-property-inheritance)
14158 (and (stringp org-use-property-inheritance)
14159 (string-match org-use-property-inheritance property))
14160 (and (listp org-use-property-inheritance)
14161 (member property org-use-property-inheritance)))
14162 ;; Caching is not possible, check it directly
14163 (org-entry-get pom property 'inherit)
14164 ;; Get all properties, so that we can do complicated checks easily
14165 (cdr (assoc property (or org-cached-props
14166 (setq org-cached-props
14167 (org-entry-properties pom)))))))
14169 (defun org-global-tags-completion-table (&optional files)
14170 "Return the list of all tags in all agenda buffer/files.
14171 Optional FILES argument is a list of files which can be used
14172 instead of the agenda files."
14173 (save-excursion
14174 (org-uniquify
14175 (delq nil
14176 (apply 'append
14177 (mapcar
14178 (lambda (file)
14179 (set-buffer (find-file-noselect file))
14180 (append (org-get-buffer-tags)
14181 (mapcar (lambda (x) (if (stringp (car-safe x))
14182 (list (car-safe x)) nil))
14183 org-tag-alist)))
14184 (if (and files (car files))
14185 files
14186 (org-agenda-files))))))))
14188 (defun org-make-tags-matcher (match)
14189 "Create the TAGS/TODO matcher form for the selection string MATCH.
14191 The variable `todo-only' is scoped dynamically into this function.
14192 It will be set to t if the matcher restricts matching to TODO entries,
14193 otherwise will not be touched.
14195 Returns a cons of the selection string MATCH and the constructed
14196 lisp form implementing the matcher. The matcher is to be evaluated
14197 at an Org entry, with point on the headline, and returns t if the
14198 entry matches the selection string MATCH. The returned lisp form
14199 references two variables with information about the entry, which
14200 must be bound around the form's evaluation: todo, the TODO keyword
14201 at the entry (or nil of none); and tags-list, the list of all tags
14202 at the entry including inherited ones. Additionally, the category
14203 of the entry (if any) must be specified as the text property
14204 'org-category on the headline.
14206 See also `org-scan-tags'.
14208 (declare (special todo-only))
14209 (unless (boundp 'todo-only)
14210 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14211 (unless match
14212 ;; Get a new match request, with completion against the global
14213 ;; tags table and the local tags in current buffer
14214 (let ((org-last-tags-completion-table
14215 (org-uniquify
14216 (delq nil (append (org-get-buffer-tags)
14217 (org-global-tags-completion-table))))))
14218 (setq match (org-completing-read-no-i
14219 "Match: " 'org-tags-completion-function nil nil nil
14220 'org-tags-history))))
14222 ;; Parse the string and create a lisp form
14223 (let ((match0 match)
14224 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14225 minus tag mm
14226 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14227 orterms term orlist re-p str-p level-p level-op time-p
14228 prop-p pn pv po gv rest (start 0) (ss 0))
14229 ;; Expand group tags
14230 (setq match (org-tags-expand match))
14232 ;; Check if there is a TODO part of this match, which would be the
14233 ;; part after a "/". TO make sure that this slash is not part of
14234 ;; a property value to be matched against, we also check that there
14235 ;; is no " after that slash.
14236 ;; First, find the last slash
14237 (while (string-match "/+" match ss)
14238 (setq start (match-beginning 0) ss (match-end 0)))
14239 (if (and (string-match "/+" match start)
14240 (not (save-match-data (string-match "\"" match start))))
14241 ;; match contains also a todo-matching request
14242 (progn
14243 (setq tagsmatch (substring match 0 (match-beginning 0))
14244 todomatch (substring match (match-end 0)))
14245 (if (string-match "^!" todomatch)
14246 (setq todo-only t todomatch (substring todomatch 1)))
14247 (if (string-match "^\\s-*$" todomatch)
14248 (setq todomatch nil)))
14249 ;; only matching tags
14250 (setq tagsmatch match todomatch nil))
14252 ;; Make the tags matcher
14253 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14254 (setq tagsmatcher t)
14255 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14256 (while (setq term (pop orterms))
14257 (while (and (equal (substring term -1) "\\") orterms)
14258 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14259 (while (string-match re term)
14260 (setq rest (substring term (match-end 0))
14261 minus (and (match-end 1)
14262 (equal (match-string 1 term) "-"))
14263 tag (save-match-data (replace-regexp-in-string
14264 "\\\\-" "-"
14265 (match-string 2 term)))
14266 re-p (equal (string-to-char tag) ?{)
14267 level-p (match-end 4)
14268 prop-p (match-end 5)
14269 mm (cond
14270 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14271 (level-p
14272 (setq level-op (org-op-to-function (match-string 3 term)))
14273 `(,level-op level ,(string-to-number
14274 (match-string 4 term))))
14275 (prop-p
14276 (setq pn (match-string 5 term)
14277 po (match-string 6 term)
14278 pv (match-string 7 term)
14279 re-p (equal (string-to-char pv) ?{)
14280 str-p (equal (string-to-char pv) ?\")
14281 time-p (save-match-data
14282 (string-match "^\"[[<].*[]>]\"$" pv))
14283 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14284 (if time-p (setq pv (org-matcher-time pv)))
14285 (setq po (org-op-to-function po (if time-p 'time str-p)))
14286 (cond
14287 ((equal pn "CATEGORY")
14288 (setq gv '(get-text-property (point) 'org-category)))
14289 ((equal pn "TODO")
14290 (setq gv 'todo))
14292 (setq gv `(org-cached-entry-get nil ,pn))))
14293 (if re-p
14294 (if (eq po 'org<>)
14295 `(not (string-match ,pv (or ,gv "")))
14296 `(string-match ,pv (or ,gv "")))
14297 (if str-p
14298 `(,po (or ,gv "") ,pv)
14299 `(,po (string-to-number (or ,gv ""))
14300 ,(string-to-number pv) ))))
14301 (t `(member ,tag tags-list)))
14302 mm (if minus (list 'not mm) mm)
14303 term rest)
14304 (push mm tagsmatcher))
14305 (push (if (> (length tagsmatcher) 1)
14306 (cons 'and tagsmatcher)
14307 (car tagsmatcher))
14308 orlist)
14309 (setq tagsmatcher nil))
14310 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14311 (setq tagsmatcher
14312 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14313 ;; Make the todo matcher
14314 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14315 (setq todomatcher t)
14316 (setq orterms (org-split-string todomatch "|") orlist nil)
14317 (while (setq term (pop orterms))
14318 (while (string-match re term)
14319 (setq minus (and (match-end 1)
14320 (equal (match-string 1 term) "-"))
14321 kwd (match-string 2 term)
14322 re-p (equal (string-to-char kwd) ?{)
14323 term (substring term (match-end 0))
14324 mm (if re-p
14325 `(string-match ,(substring kwd 1 -1) todo)
14326 (list 'equal 'todo kwd))
14327 mm (if minus (list 'not mm) mm))
14328 (push mm todomatcher))
14329 (push (if (> (length todomatcher) 1)
14330 (cons 'and todomatcher)
14331 (car todomatcher))
14332 orlist)
14333 (setq todomatcher nil))
14334 (setq todomatcher (if (> (length orlist) 1)
14335 (cons 'or orlist) (car orlist))))
14337 ;; Return the string and lisp forms of the matcher
14338 (setq matcher (if todomatcher
14339 (list 'and tagsmatcher todomatcher)
14340 tagsmatcher))
14341 (when todo-only
14342 (setq matcher (list 'and '(member todo org-not-done-keywords)
14343 matcher)))
14344 (cons match0 matcher)))
14346 (defun org-tags-expand (match &optional single-as-list downcased)
14347 "Expand group tags in MATCH.
14349 This replaces every group tag in MATCH with a regexp tag search.
14350 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14351 will be replaced like this:
14353 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14354 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14355 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14357 Replacing by a regexp preserves the structure of the match.
14358 E.g., this expansion
14360 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14362 will match anything tagged with \"Lab\" and \"Home\", or tagged
14363 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14365 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14366 assumed to be a single group tag, and the function will return
14367 the list of tags in this group.
14369 When DOWNCASE is non-nil, expand downcased TAGS."
14370 (if org-group-tags
14371 (let* ((case-fold-search t)
14372 (stable org-mode-syntax-table)
14373 (tal (or org-tag-groups-alist-for-agenda
14374 org-tag-groups-alist))
14375 (tal (if downcased
14376 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14377 (tml (mapcar 'car tal))
14378 (rtnmatch match) rpl)
14379 ;; @ and _ are allowed as word-components in tags
14380 (modify-syntax-entry ?@ "w" stable)
14381 (modify-syntax-entry ?_ "w" stable)
14382 (while (and tml
14383 (with-syntax-table stable
14384 (string-match
14385 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14386 (regexp-opt tml) "\\>\\)") rtnmatch)))
14387 (let* ((dir (match-string 1 rtnmatch))
14388 (tag (match-string 2 rtnmatch))
14389 (tag (if downcased (downcase tag) tag)))
14390 (setq tml (delete tag tml))
14391 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14392 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14393 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14394 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14395 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14396 (if single-as-list
14397 (or (reverse rpl) (list rtnmatch))
14398 rtnmatch))
14399 (if single-as-list (list (if downcased (downcase match) match))
14400 match)))
14402 (defun org-op-to-function (op &optional stringp)
14403 "Turn an operator into the appropriate function."
14404 (setq op
14405 (cond
14406 ((equal op "<" ) '(< string< org-time<))
14407 ((equal op ">" ) '(> org-string> org-time>))
14408 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14409 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14410 ((member op '("=" "==")) '(= string= org-time=))
14411 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14412 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14414 (defun org<> (a b) (not (= a b)))
14415 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14416 (defun org-string>= (a b) (not (string< a b)))
14417 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14418 (defun org-string<> (a b) (not (string= a b)))
14419 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14420 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14421 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14422 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14423 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14424 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14425 (defun org-2ft (s)
14426 "Convert S to a floating point time.
14427 If S is already a number, just return it. If it is a string, parse
14428 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14429 (cond
14430 ((numberp s) s)
14431 ((stringp s)
14432 (condition-case nil
14433 (float-time (apply 'encode-time (org-parse-time-string s)))
14434 (error 0.)))
14435 (t 0.)))
14437 (defun org-time-today ()
14438 "Time in seconds today at 0:00.
14439 Returns the float number of seconds since the beginning of the
14440 epoch to the beginning of today (00:00)."
14441 (float-time (apply 'encode-time
14442 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14444 (defun org-matcher-time (s)
14445 "Interpret a time comparison value."
14446 (save-match-data
14447 (cond
14448 ((string= s "<now>") (float-time))
14449 ((string= s "<today>") (org-time-today))
14450 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14451 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14452 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14453 (+ (org-time-today)
14454 (* (string-to-number (match-string 1 s))
14455 (cdr (assoc (match-string 2 s)
14456 '(("d" . 86400.0) ("w" . 604800.0)
14457 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14458 (t (org-2ft s)))))
14460 (defun org-match-any-p (re list)
14461 "Does re match any element of list?"
14462 (setq list (mapcar (lambda (x) (string-match re x)) list))
14463 (delq nil list))
14465 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14466 (defvar org-tags-overlay (make-overlay 1 1))
14467 (org-detach-overlay org-tags-overlay)
14469 (defun org-get-local-tags-at (&optional pos)
14470 "Get a list of tags defined in the current headline."
14471 (org-get-tags-at pos 'local))
14473 (defun org-get-local-tags ()
14474 "Get a list of tags defined in the current headline."
14475 (org-get-tags-at nil 'local))
14477 (defun org-get-tags-at (&optional pos local)
14478 "Get a list of all headline tags applicable at POS.
14479 POS defaults to point. If tags are inherited, the list contains
14480 the targets in the same sequence as the headlines appear, i.e.
14481 the tags of the current headline come last.
14482 When LOCAL is non-nil, only return tags from the current headline,
14483 ignore inherited ones."
14484 (interactive)
14485 (if (and org-trust-scanner-tags
14486 (or (not pos) (equal pos (point)))
14487 (not local))
14488 org-scanner-tags
14489 (let (tags ltags lastpos parent)
14490 (save-excursion
14491 (save-restriction
14492 (widen)
14493 (goto-char (or pos (point)))
14494 (save-match-data
14495 (catch 'done
14496 (condition-case nil
14497 (progn
14498 (org-back-to-heading t)
14499 (while (not (equal lastpos (point)))
14500 (setq lastpos (point))
14501 (when (looking-at
14502 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14503 (setq ltags (org-split-string
14504 (org-match-string-no-properties 1) ":"))
14505 (when parent
14506 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14507 (setq tags (append
14508 (if parent
14509 (org-remove-uninherited-tags ltags)
14510 ltags)
14511 tags)))
14512 (or org-use-tag-inheritance (throw 'done t))
14513 (if local (throw 'done t))
14514 (or (org-up-heading-safe) (error nil))
14515 (setq parent t)))
14516 (error nil)))))
14517 (if local
14518 tags
14519 (reverse (delete-dups
14520 (reverse (append
14521 (org-remove-uninherited-tags
14522 org-file-tags) tags)))))))))
14524 (defun org-add-prop-inherited (s)
14525 (add-text-properties 0 (length s) '(inherited t) s)
14528 (defun org-toggle-tag (tag &optional onoff)
14529 "Toggle the tag TAG for the current line.
14530 If ONOFF is `on' or `off', don't toggle but set to this state."
14531 (let (res current)
14532 (save-excursion
14533 (org-back-to-heading t)
14534 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14535 (point-at-eol) t)
14536 (progn
14537 (setq current (match-string 1))
14538 (replace-match ""))
14539 (setq current ""))
14540 (setq current (nreverse (org-split-string current ":")))
14541 (cond
14542 ((eq onoff 'on)
14543 (setq res t)
14544 (or (member tag current) (push tag current)))
14545 ((eq onoff 'off)
14546 (or (not (member tag current)) (setq current (delete tag current))))
14547 (t (if (member tag current)
14548 (setq current (delete tag current))
14549 (setq res t)
14550 (push tag current))))
14551 (end-of-line 1)
14552 (if current
14553 (progn
14554 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14555 (org-set-tags nil t))
14556 (delete-horizontal-space))
14557 (run-hooks 'org-after-tags-change-hook))
14558 res))
14560 (defun org-align-tags-here (to-col)
14561 ;; Assumes that this is a headline
14562 "Align tags on the current headline to TO-COL."
14563 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14564 (beginning-of-line 1)
14565 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14566 (< pos (match-beginning 2)))
14567 (progn
14568 (setq tags-l (- (match-end 2) (match-beginning 2)))
14569 (goto-char (match-beginning 1))
14570 (insert " ")
14571 (delete-region (point) (1+ (match-beginning 2)))
14572 (setq ncol (max (current-column)
14573 (1+ col)
14574 (if (> to-col 0)
14575 to-col
14576 (- (abs to-col) tags-l))))
14577 (setq p (point))
14578 (insert (make-string (- ncol (current-column)) ?\ ))
14579 (setq ncol (current-column))
14580 (when indent-tabs-mode (tabify p (point-at-eol)))
14581 (org-move-to-column (min ncol col)))
14582 (goto-char pos))))
14584 (defun org-set-tags-command (&optional arg just-align)
14585 "Call the set-tags command for the current entry."
14586 (interactive "P")
14587 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14588 (org-set-tags arg just-align)
14589 (save-excursion
14590 (unless (and (org-region-active-p)
14591 org-loop-over-headlines-in-active-region)
14592 (org-back-to-heading t))
14593 (org-set-tags arg just-align))))
14595 (defun org-set-tags-to (data)
14596 "Set the tags of the current entry to DATA, replacing the current tags.
14597 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14598 If DATA is nil or the empty string, any tags will be removed."
14599 (interactive "sTags: ")
14600 (setq data
14601 (cond
14602 ((eq data nil) "")
14603 ((equal data "") "")
14604 ((stringp data)
14605 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14606 ":"))
14607 ((listp data)
14608 (concat ":" (mapconcat 'identity data ":") ":"))))
14609 (when data
14610 (save-excursion
14611 (org-back-to-heading t)
14612 (when (looking-at org-complex-heading-regexp)
14613 (if (match-end 5)
14614 (progn
14615 (goto-char (match-beginning 5))
14616 (insert data)
14617 (delete-region (point) (point-at-eol))
14618 (org-set-tags nil 'align))
14619 (goto-char (point-at-eol))
14620 (insert " " data)
14621 (org-set-tags nil 'align)))
14622 (beginning-of-line 1)
14623 (if (looking-at ".*?\\([ \t]+\\)$")
14624 (delete-region (match-beginning 1) (match-end 1))))))
14626 (defun org-align-all-tags ()
14627 "Align the tags i all headings."
14628 (interactive)
14629 (save-excursion
14630 (or (ignore-errors (org-back-to-heading t))
14631 (outline-next-heading))
14632 (if (org-at-heading-p)
14633 (org-set-tags t)
14634 (message "No headings"))))
14636 (defvar org-indent-indentation-per-level)
14637 (defun org-set-tags (&optional arg just-align)
14638 "Set the tags for the current headline.
14639 With prefix ARG, realign all tags in headings in the current buffer.
14640 When JUST-ALIGN is non-nil, only align tags."
14641 (interactive "P")
14642 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14643 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14644 'region-start-level 'region))
14645 org-loop-over-headlines-in-active-region)
14646 (org-map-entries
14647 ;; We don't use ARG and JUST-ALIGN here because these args
14648 ;; are not useful when looping over headlines.
14649 `(org-set-tags)
14650 org-loop-over-headlines-in-active-region
14651 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14652 (let* ((re org-outline-regexp-bol)
14653 (current (unless arg (org-get-tags-string)))
14654 (col (current-column))
14655 (org-setting-tags t)
14656 table current-tags inherited-tags ; computed below when needed
14657 tags p0 c0 c1 rpl di tc level)
14658 (if arg
14659 (save-excursion
14660 (goto-char (point-min))
14661 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14662 (while (re-search-forward re nil t)
14663 (org-set-tags nil t)
14664 (end-of-line 1)))
14665 (message "All tags realigned to column %d" org-tags-column))
14666 (if just-align
14667 (setq tags current)
14668 ;; Get a new set of tags from the user
14669 (save-excursion
14670 (setq table (append org-tag-persistent-alist
14671 (or org-tag-alist (org-get-buffer-tags))
14672 (and
14673 org-complete-tags-always-offer-all-agenda-tags
14674 (org-global-tags-completion-table
14675 (org-agenda-files))))
14676 org-last-tags-completion-table table
14677 current-tags (org-split-string current ":")
14678 inherited-tags (nreverse
14679 (nthcdr (length current-tags)
14680 (nreverse (org-get-tags-at))))
14681 tags
14682 (if (or (eq t org-use-fast-tag-selection)
14683 (and org-use-fast-tag-selection
14684 (delq nil (mapcar 'cdr table))))
14685 (org-fast-tag-selection
14686 current-tags inherited-tags table
14687 (if org-fast-tag-selection-include-todo
14688 org-todo-key-alist))
14689 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14690 (org-trim
14691 (org-icompleting-read "Tags: "
14692 'org-tags-completion-function
14693 nil nil current 'org-tags-history))))))
14694 (while (string-match "[-+&]+" tags)
14695 ;; No boolean logic, just a list
14696 (setq tags (replace-match ":" t t tags))))
14698 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14700 (if org-tags-sort-function
14701 (setq tags (mapconcat 'identity
14702 (sort (org-split-string
14703 tags (org-re "[^[:alnum:]_@#%]+"))
14704 org-tags-sort-function) ":")))
14706 (if (string-match "\\`[\t ]*\\'" tags)
14707 (setq tags "")
14708 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14709 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14711 ;; Insert new tags at the correct column
14712 (beginning-of-line 1)
14713 (setq level (or (and (looking-at org-outline-regexp)
14714 (- (match-end 0) (point) 1))
14716 (cond
14717 ((and (equal current "") (equal tags "")))
14718 ((re-search-forward
14719 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14720 (point-at-eol) t)
14721 (if (equal tags "")
14722 (setq rpl "")
14723 (goto-char (match-beginning 0))
14724 (setq c0 (current-column)
14725 ;; compute offset for the case of org-indent-mode active
14726 di (if (org-bound-and-true-p org-indent-mode)
14727 (* (1- org-indent-indentation-per-level) (1- level))
14729 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14730 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14731 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (string-width tags))))
14732 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14733 (replace-match rpl t t)
14734 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14735 tags)
14736 (t (error "Tags alignment failed")))
14737 (org-move-to-column col)
14738 (unless just-align
14739 (run-hooks 'org-after-tags-change-hook))))))
14741 (defun org-change-tag-in-region (beg end tag off)
14742 "Add or remove TAG for each entry in the region.
14743 This works in the agenda, and also in an org-mode buffer."
14744 (interactive
14745 (list (region-beginning) (region-end)
14746 (let ((org-last-tags-completion-table
14747 (if (derived-mode-p 'org-mode)
14748 (org-uniquify
14749 (delq nil (append (org-get-buffer-tags)
14750 (org-global-tags-completion-table))))
14751 (org-global-tags-completion-table))))
14752 (org-icompleting-read
14753 "Tag: " 'org-tags-completion-function nil nil nil
14754 'org-tags-history))
14755 (progn
14756 (message "[s]et or [r]emove? ")
14757 (equal (read-char-exclusive) ?r))))
14758 (if (fboundp 'deactivate-mark) (deactivate-mark))
14759 (let ((agendap (equal major-mode 'org-agenda-mode))
14760 l1 l2 m buf pos newhead (cnt 0))
14761 (goto-char end)
14762 (setq l2 (1- (org-current-line)))
14763 (goto-char beg)
14764 (setq l1 (org-current-line))
14765 (loop for l from l1 to l2 do
14766 (org-goto-line l)
14767 (setq m (get-text-property (point) 'org-hd-marker))
14768 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14769 (and agendap m))
14770 (setq buf (if agendap (marker-buffer m) (current-buffer))
14771 pos (if agendap m (point)))
14772 (with-current-buffer buf
14773 (save-excursion
14774 (save-restriction
14775 (goto-char pos)
14776 (setq cnt (1+ cnt))
14777 (org-toggle-tag tag (if off 'off 'on))
14778 (setq newhead (org-get-heading)))))
14779 (and agendap (org-agenda-change-all-lines newhead m))))
14780 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14782 (defun org-tags-completion-function (string predicate &optional flag)
14783 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14784 (confirm (lambda (x) (stringp (car x)))))
14785 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14786 (setq s1 (match-string 1 string)
14787 s2 (match-string 2 string))
14788 (setq s1 "" s2 string))
14789 (cond
14790 ((eq flag nil)
14791 ;; try completion
14792 (setq rtn (try-completion s2 ctable confirm))
14793 (if (stringp rtn)
14794 (setq rtn
14795 (concat s1 s2 (substring rtn (length s2))
14796 (if (and org-add-colon-after-tag-completion
14797 (assoc rtn ctable))
14798 ":" ""))))
14799 rtn)
14800 ((eq flag t)
14801 ;; all-completions
14802 (all-completions s2 ctable confirm))
14803 ((eq flag 'lambda)
14804 ;; exact match?
14805 (assoc s2 ctable)))))
14807 (defun org-fast-tag-insert (kwd tags face &optional end)
14808 "Insert KDW, and the TAGS, the latter with face FACE.
14809 Also insert END."
14810 (insert (format "%-12s" (concat kwd ":"))
14811 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14812 (or end "")))
14814 (defun org-fast-tag-show-exit (flag)
14815 (save-excursion
14816 (org-goto-line 3)
14817 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14818 (replace-match ""))
14819 (when flag
14820 (end-of-line 1)
14821 (org-move-to-column (- (window-width) 19) t)
14822 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14824 (defun org-set-current-tags-overlay (current prefix)
14825 "Add an overlay to CURRENT tag with PREFIX."
14826 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14827 (if (featurep 'xemacs)
14828 (org-overlay-display org-tags-overlay (concat prefix s)
14829 'secondary-selection)
14830 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14831 (org-overlay-display org-tags-overlay (concat prefix s)))))
14833 (defvar org-last-tag-selection-key nil)
14834 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14835 "Fast tag selection with single keys.
14836 CURRENT is the current list of tags in the headline, INHERITED is the
14837 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14838 possibly with grouping information. TODO-TABLE is a similar table with
14839 TODO keywords, should these have keys assigned to them.
14840 If the keys are nil, a-z are automatically assigned.
14841 Returns the new tags string, or nil to not change the current settings."
14842 (let* ((fulltable (append table todo-table))
14843 (maxlen (apply 'max (mapcar
14844 (lambda (x)
14845 (if (stringp (car x)) (string-width (car x)) 0))
14846 fulltable)))
14847 (buf (current-buffer))
14848 (expert (eq org-fast-tag-selection-single-key 'expert))
14849 (buffer-tags nil)
14850 (fwidth (+ maxlen 3 1 3))
14851 (ncol (/ (- (window-width) 4) fwidth))
14852 (i-face 'org-done)
14853 (c-face 'org-todo)
14854 tg cnt e c char c1 c2 ntable tbl rtn
14855 ov-start ov-end ov-prefix
14856 (exit-after-next org-fast-tag-selection-single-key)
14857 (done-keywords org-done-keywords)
14858 groups ingroup)
14859 (save-excursion
14860 (beginning-of-line 1)
14861 (if (looking-at
14862 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14863 (setq ov-start (match-beginning 1)
14864 ov-end (match-end 1)
14865 ov-prefix "")
14866 (setq ov-start (1- (point-at-eol))
14867 ov-end (1+ ov-start))
14868 (skip-chars-forward "^\n\r")
14869 (setq ov-prefix
14870 (concat
14871 (buffer-substring (1- (point)) (point))
14872 (if (> (current-column) org-tags-column)
14874 (make-string (- org-tags-column (current-column)) ?\ ))))))
14875 (move-overlay org-tags-overlay ov-start ov-end)
14876 (save-window-excursion
14877 (if expert
14878 (set-buffer (get-buffer-create " *Org tags*"))
14879 (delete-other-windows)
14880 (split-window-vertically)
14881 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14882 (erase-buffer)
14883 (org-set-local 'org-done-keywords done-keywords)
14884 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14885 (org-fast-tag-insert "Current" current c-face "\n\n")
14886 (org-fast-tag-show-exit exit-after-next)
14887 (org-set-current-tags-overlay current ov-prefix)
14888 (setq tbl fulltable char ?a cnt 0)
14889 (while (setq e (pop tbl))
14890 (cond
14891 ((equal (car e) :startgroup)
14892 (push '() groups) (setq ingroup t)
14893 (when (not (= cnt 0))
14894 (setq cnt 0)
14895 (insert "\n"))
14896 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14897 ((equal (car e) :endgroup)
14898 (setq ingroup nil cnt 0)
14899 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14900 ((equal e '(:newline))
14901 (when (not (= cnt 0))
14902 (setq cnt 0)
14903 (insert "\n")
14904 (setq e (car tbl))
14905 (while (equal (car tbl) '(:newline))
14906 (insert "\n")
14907 (setq tbl (cdr tbl)))))
14908 ((equal e '(:grouptags)) nil)
14910 (setq tg (copy-sequence (car e)) c2 nil)
14911 (if (cdr e)
14912 (setq c (cdr e))
14913 ;; automatically assign a character.
14914 (setq c1 (string-to-char
14915 (downcase (substring
14916 tg (if (= (string-to-char tg) ?@) 1 0)))))
14917 (if (or (rassoc c1 ntable) (rassoc c1 table))
14918 (while (or (rassoc char ntable) (rassoc char table))
14919 (setq char (1+ char)))
14920 (setq c2 c1))
14921 (setq c (or c2 char)))
14922 (if ingroup (push tg (car groups)))
14923 (setq tg (org-add-props tg nil 'face
14924 (cond
14925 ((not (assoc tg table))
14926 (org-get-todo-face tg))
14927 ((member tg current) c-face)
14928 ((member tg inherited) i-face))))
14929 (if (equal (caar tbl) :grouptags)
14930 (org-add-props tg nil 'face 'org-tag-group))
14931 (if (and (= cnt 0) (not ingroup)) (insert " "))
14932 (insert "[" c "] " tg (make-string
14933 (- fwidth 4 (length tg)) ?\ ))
14934 (push (cons tg c) ntable)
14935 (when (= (setq cnt (1+ cnt)) ncol)
14936 (insert "\n")
14937 (if ingroup (insert " "))
14938 (setq cnt 0)))))
14939 (setq ntable (nreverse ntable))
14940 (insert "\n")
14941 (goto-char (point-min))
14942 (if (not expert) (org-fit-window-to-buffer))
14943 (setq rtn
14944 (catch 'exit
14945 (while t
14946 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14947 (if (not groups) "no " "")
14948 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14949 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14950 (setq org-last-tag-selection-key c)
14951 (cond
14952 ((= c ?\r) (throw 'exit t))
14953 ((= c ?!)
14954 (setq groups (not groups))
14955 (goto-char (point-min))
14956 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14957 ((= c ?\C-c)
14958 (if (not expert)
14959 (org-fast-tag-show-exit
14960 (setq exit-after-next (not exit-after-next)))
14961 (setq expert nil)
14962 (delete-other-windows)
14963 (set-window-buffer (split-window-vertically) " *Org tags*")
14964 (org-switch-to-buffer-other-window " *Org tags*")
14965 (org-fit-window-to-buffer)))
14966 ((or (= c ?\C-g)
14967 (and (= c ?q) (not (rassoc c ntable))))
14968 (org-detach-overlay org-tags-overlay)
14969 (setq quit-flag t))
14970 ((= c ?\ )
14971 (setq current nil)
14972 (if exit-after-next (setq exit-after-next 'now)))
14973 ((= c ?\t)
14974 (condition-case nil
14975 (setq tg (org-icompleting-read
14976 "Tag: "
14977 (or buffer-tags
14978 (with-current-buffer buf
14979 (org-get-buffer-tags)))))
14980 (quit (setq tg "")))
14981 (when (string-match "\\S-" tg)
14982 (add-to-list 'buffer-tags (list tg))
14983 (if (member tg current)
14984 (setq current (delete tg current))
14985 (push tg current)))
14986 (if exit-after-next (setq exit-after-next 'now)))
14987 ((setq e (rassoc c todo-table) tg (car e))
14988 (with-current-buffer buf
14989 (save-excursion (org-todo tg)))
14990 (if exit-after-next (setq exit-after-next 'now)))
14991 ((setq e (rassoc c ntable) tg (car e))
14992 (if (member tg current)
14993 (setq current (delete tg current))
14994 (loop for g in groups do
14995 (if (member tg g)
14996 (mapc (lambda (x)
14997 (setq current (delete x current)))
14998 g)))
14999 (push tg current))
15000 (if exit-after-next (setq exit-after-next 'now))))
15002 ;; Create a sorted list
15003 (setq current
15004 (sort current
15005 (lambda (a b)
15006 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15007 (if (eq exit-after-next 'now) (throw 'exit t))
15008 (goto-char (point-min))
15009 (beginning-of-line 2)
15010 (delete-region (point) (point-at-eol))
15011 (org-fast-tag-insert "Current" current c-face)
15012 (org-set-current-tags-overlay current ov-prefix)
15013 (while (re-search-forward
15014 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
15015 (setq tg (match-string 1))
15016 (add-text-properties
15017 (match-beginning 1) (match-end 1)
15018 (list 'face
15019 (cond
15020 ((member tg current) c-face)
15021 ((member tg inherited) i-face)
15022 (t (get-text-property (match-beginning 1) 'face))))))
15023 (goto-char (point-min)))))
15024 (org-detach-overlay org-tags-overlay)
15025 (if rtn
15026 (mapconcat 'identity current ":")
15027 nil))))
15029 (defun org-get-tags-string ()
15030 "Get the TAGS string in the current headline."
15031 (unless (org-at-heading-p t)
15032 (user-error "Not on a heading"))
15033 (save-excursion
15034 (beginning-of-line 1)
15035 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
15036 (org-match-string-no-properties 1)
15037 "")))
15039 (defun org-get-tags ()
15040 "Get the list of tags specified in the current headline."
15041 (org-split-string (org-get-tags-string) ":"))
15043 (defun org-get-buffer-tags ()
15044 "Get a table of all tags used in the buffer, for completion."
15045 (let (tags)
15046 (save-excursion
15047 (goto-char (point-min))
15048 (while (re-search-forward
15049 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
15050 (when (equal (char-after (point-at-bol 0)) ?*)
15051 (mapc (lambda (x) (add-to-list 'tags x))
15052 (org-split-string (org-match-string-no-properties 1) ":")))))
15053 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
15054 (mapcar 'list tags)))
15056 ;;;; The mapping API
15058 (defun org-map-entries (func &optional match scope &rest skip)
15059 "Call FUNC at each headline selected by MATCH in SCOPE.
15061 FUNC is a function or a lisp form. The function will be called without
15062 arguments, with the cursor positioned at the beginning of the headline.
15063 The return values of all calls to the function will be collected and
15064 returned as a list.
15066 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15067 does not need to preserve point. After evaluation, the cursor will be
15068 moved to the end of the line (presumably of the headline of the
15069 processed entry) and search continues from there. Under some
15070 circumstances, this may not produce the wanted results. For example,
15071 if you have removed (e.g. archived) the current (sub)tree it could
15072 mean that the next entry will be skipped entirely. In such cases, you
15073 can specify the position from where search should continue by making
15074 FUNC set the variable `org-map-continue-from' to the desired buffer
15075 position.
15077 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15078 Only headlines that are matched by this query will be considered during
15079 the iteration. When MATCH is nil or t, all headlines will be
15080 visited by the iteration.
15082 SCOPE determines the scope of this command. It can be any of:
15084 nil The current buffer, respecting the restriction if any
15085 tree The subtree started with the entry at point
15086 region The entries within the active region, if any
15087 region-start-level
15088 The entries within the active region, but only those at
15089 the same level than the first one.
15090 file The current buffer, without restriction
15091 file-with-archives
15092 The current buffer, and any archives associated with it
15093 agenda All agenda files
15094 agenda-with-archives
15095 All agenda files with any archive files associated with them
15096 \(file1 file2 ...)
15097 If this is a list, all files in the list will be scanned
15099 The remaining args are treated as settings for the skipping facilities of
15100 the scanner. The following items can be given here:
15102 archive skip trees with the archive tag
15103 comment skip trees with the COMMENT keyword
15104 function or Emacs Lisp form:
15105 will be used as value for `org-agenda-skip-function', so
15106 whenever the function returns a position, FUNC will not be
15107 called for that entry and search will continue from the
15108 position returned
15110 If your function needs to retrieve the tags including inherited tags
15111 at the *current* entry, you can use the value of the variable
15112 `org-scanner-tags' which will be much faster than getting the value
15113 with `org-get-tags-at'. If your function gets properties with
15114 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15115 to t around the call to `org-entry-properties' to get the same speedup.
15116 Note that if your function moves around to retrieve tags and properties at
15117 a *different* entry, you cannot use these techniques."
15118 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15119 (not (org-region-active-p)))
15120 (let* ((org-agenda-archives-mode nil) ; just to make sure
15121 (org-agenda-skip-archived-trees (memq 'archive skip))
15122 (org-agenda-skip-comment-trees (memq 'comment skip))
15123 (org-agenda-skip-function
15124 (car (org-delete-all '(comment archive) skip)))
15125 (org-tags-match-list-sublevels t)
15126 (start-level (eq scope 'region-start-level))
15127 matcher file res
15128 org-todo-keywords-for-agenda
15129 org-done-keywords-for-agenda
15130 org-todo-keyword-alist-for-agenda
15131 org-tag-alist-for-agenda
15132 todo-only)
15134 (cond
15135 ((eq match t) (setq matcher t))
15136 ((eq match nil) (setq matcher t))
15137 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15139 (save-excursion
15140 (save-restriction
15141 (cond ((eq scope 'tree)
15142 (org-back-to-heading t)
15143 (org-narrow-to-subtree)
15144 (setq scope nil))
15145 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15146 (org-region-active-p))
15147 ;; If needed, set start-level to a string like "2"
15148 (when start-level
15149 (save-excursion
15150 (goto-char (region-beginning))
15151 (unless (org-at-heading-p) (outline-next-heading))
15152 (setq start-level (org-current-level))))
15153 (narrow-to-region (region-beginning)
15154 (save-excursion
15155 (goto-char (region-end))
15156 (unless (and (bolp) (org-at-heading-p))
15157 (outline-next-heading))
15158 (point)))
15159 (setq scope nil)))
15161 (if (not scope)
15162 (progn
15163 (org-agenda-prepare-buffers
15164 (list (buffer-file-name (current-buffer))))
15165 (setq res (org-scan-tags func matcher todo-only start-level)))
15166 ;; Get the right scope
15167 (cond
15168 ((and scope (listp scope) (symbolp (car scope)))
15169 (setq scope (eval scope)))
15170 ((eq scope 'agenda)
15171 (setq scope (org-agenda-files t)))
15172 ((eq scope 'agenda-with-archives)
15173 (setq scope (org-agenda-files t))
15174 (setq scope (org-add-archive-files scope)))
15175 ((eq scope 'file)
15176 (setq scope (list (buffer-file-name))))
15177 ((eq scope 'file-with-archives)
15178 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15179 (org-agenda-prepare-buffers scope)
15180 (while (setq file (pop scope))
15181 (with-current-buffer (org-find-base-buffer-visiting file)
15182 (save-excursion
15183 (save-restriction
15184 (widen)
15185 (goto-char (point-min))
15186 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
15187 res)))
15189 ;;;; Properties
15191 ;;; Setting and retrieving properties
15193 (defconst org-special-properties
15194 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
15195 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
15196 "The special properties valid in Org-mode.
15198 These are properties that are not defined in the property drawer,
15199 but in some other way.")
15201 (defconst org-default-properties
15202 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15203 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15204 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15205 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15206 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
15207 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15208 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15209 "Some properties that are used by Org-mode for various purposes.
15210 Being in this list makes sure that they are offered for completion.")
15212 (defun org-property-action ()
15213 "Do an action on properties."
15214 (interactive)
15215 (let (c)
15216 (org-at-property-p)
15217 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15218 (setq c (read-char-exclusive))
15219 (cond
15220 ((equal c ?s)
15221 (call-interactively 'org-set-property))
15222 ((equal c ?d)
15223 (call-interactively 'org-delete-property))
15224 ((equal c ?D)
15225 (call-interactively 'org-delete-property-globally))
15226 ((equal c ?c)
15227 (call-interactively 'org-compute-property-at-point))
15228 (t (user-error "No such property action %c" c)))))
15230 (defun org-inc-effort ()
15231 "Increment the value of the effort property in the current entry."
15232 (interactive)
15233 (org-set-effort nil t))
15235 (defvar org-clock-effort) ;; Defined in org-clock.el
15236 (defvar org-clock-current-task) ;; Defined in org-clock.el
15237 (defun org-set-effort (&optional value increment)
15238 "Set the effort property of the current entry.
15239 With numerical prefix arg, use the nth allowed value, 0 stands for the
15240 10th allowed value.
15242 When INCREMENT is non-nil, set the property to the next allowed value."
15243 (interactive "P")
15244 (if (equal value 0) (setq value 10))
15245 (let* ((completion-ignore-case t)
15246 (prop org-effort-property)
15247 (cur (org-entry-get nil prop))
15248 (allowed (org-property-get-allowed-values nil prop 'table))
15249 (existing (mapcar 'list (org-property-values prop)))
15250 (heading (nth 4 (org-heading-components)))
15252 (val (cond
15253 ((stringp value) value)
15254 ((and allowed (integerp value))
15255 (or (car (nth (1- value) allowed))
15256 (car (org-last allowed))))
15257 ((and allowed increment)
15258 (or (caadr (member (list cur) allowed))
15259 (user-error "Allowed effort values are not set")))
15260 (allowed
15261 (message "Select 1-9,0, [RET%s]: %s"
15262 (if cur (concat "=" cur) "")
15263 (mapconcat 'car allowed " "))
15264 (setq rpl (read-char-exclusive))
15265 (if (equal rpl ?\r)
15267 (setq rpl (- rpl ?0))
15268 (if (equal rpl 0) (setq rpl 10))
15269 (if (and (> rpl 0) (<= rpl (length allowed)))
15270 (car (nth (1- rpl) allowed))
15271 (org-completing-read "Effort: " allowed nil))))
15273 (let (org-completion-use-ido org-completion-use-iswitchb)
15274 (org-completing-read
15275 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15276 (concat "[" cur "]") "")
15277 ": ")
15278 existing nil nil "" nil cur))))))
15279 (unless (equal (org-entry-get nil prop) val)
15280 (org-entry-put nil prop val))
15281 (save-excursion
15282 (org-back-to-heading t)
15283 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
15284 (when (string= heading org-clock-current-task)
15285 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
15286 (org-clock-update-mode-line))
15287 (message "%s is now %s" prop val)))
15289 (defun org-at-property-p ()
15290 "Is cursor inside a property drawer?"
15291 (save-excursion
15292 (when (equal 'node-property (car (org-element-at-point)))
15293 (beginning-of-line 1)
15294 (looking-at org-property-re))))
15296 (defun org-get-property-block (&optional beg end force)
15297 "Return the (beg . end) range of the body of the property drawer.
15298 BEG and END are the beginning and end of the current subtree, or of
15299 the part before the first headline. If they are not given, they will
15300 be found. If the drawer does not exist and FORCE is non-nil, create
15301 the drawer."
15302 (catch 'exit
15303 (save-excursion
15304 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15305 (progn (org-back-to-heading t) (point))))
15306 (end (or end (and (not (outline-next-heading)) (point-max))
15307 (point))))
15308 (goto-char beg)
15309 (if (re-search-forward org-property-start-re end t)
15310 (setq beg (1+ (match-end 0)))
15311 (if force
15312 (save-excursion
15313 (org-insert-property-drawer)
15314 (setq end (progn (outline-next-heading) (point))))
15315 (throw 'exit nil))
15316 (goto-char beg)
15317 (if (re-search-forward org-property-start-re end t)
15318 (setq beg (1+ (match-end 0)))))
15319 (if (re-search-forward org-property-end-re end t)
15320 (setq end (match-beginning 0))
15321 (or force (throw 'exit nil))
15322 (goto-char beg)
15323 (setq end beg)
15324 (org-indent-line)
15325 (insert ":END:\n"))
15326 (cons beg end)))))
15328 (defun org-entry-properties (&optional pom which specific)
15329 "Get all properties of the entry at point-or-marker POM.
15330 This includes the TODO keyword, the tags, time strings for deadline,
15331 scheduled, and clocking, and any additional properties defined in the
15332 entry. The return value is an alist, keys may occur multiple times
15333 if the property key was used several times.
15334 POM may also be nil, in which case the current entry is used.
15335 If WHICH is nil or `all', get all properties. If WHICH is
15336 `special' or `standard', only get that subclass. If WHICH
15337 is a string only get exactly this property. SPECIFIC can be a string, the
15338 specific property we are interested in. Specifying it can speed
15339 things up because then unnecessary parsing is avoided."
15340 (setq which (or which 'all))
15341 (org-with-wide-buffer
15342 (org-with-point-at pom
15343 (let ((clockstr (substring org-clock-string 0 -1))
15344 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15345 (case-fold-search nil)
15346 beg end range props sum-props key key1 value string clocksum clocksumt)
15347 (when (and (derived-mode-p 'org-mode)
15348 (ignore-errors (org-back-to-heading t)))
15349 (setq beg (point))
15350 (setq sum-props (get-text-property (point) 'org-summaries))
15351 (setq clocksum (get-text-property (point) :org-clock-minutes)
15352 clocksumt (get-text-property (point) :org-clock-minutes-today))
15353 (outline-next-heading)
15354 (setq end (point))
15355 (when (memq which '(all special))
15356 ;; Get the special properties, like TODO and tags
15357 (goto-char beg)
15358 (when (and (or (not specific) (string= specific "TODO"))
15359 (looking-at org-todo-line-regexp) (match-end 2))
15360 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15361 (when (and (or (not specific) (string= specific "PRIORITY"))
15362 (looking-at org-priority-regexp))
15363 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15364 (when (or (not specific) (string= specific "FILE"))
15365 (push (cons "FILE" buffer-file-name) props))
15366 (when (and (or (not specific) (string= specific "TAGS"))
15367 (setq value (org-get-tags-string))
15368 (string-match "\\S-" value))
15369 (push (cons "TAGS" value) props))
15370 (when (and (or (not specific) (string= specific "ALLTAGS"))
15371 (setq value (org-get-tags-at)))
15372 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15373 ":"))
15374 props))
15375 (when (or (not specific) (string= specific "BLOCKED"))
15376 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15377 (when (or (not specific)
15378 (member specific
15379 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15380 "TIMESTAMP" "TIMESTAMP_IA")))
15381 (catch 'match
15382 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15383 (setq key (if (match-end 1)
15384 (substring (org-match-string-no-properties 1)
15385 0 -1))
15386 string (if (equal key clockstr)
15387 (org-trim
15388 (buffer-substring-no-properties
15389 (match-beginning 3) (goto-char
15390 (point-at-eol))))
15391 (substring (org-match-string-no-properties 3)
15392 1 -1)))
15393 ;; Get the correct property name from the key. This is
15394 ;; necessary if the user has configured time keywords.
15395 (setq key1 (concat key ":"))
15396 (cond
15397 ((not key)
15398 (setq key
15399 (if (= (char-after (match-beginning 3)) ?\[)
15400 "TIMESTAMP_IA" "TIMESTAMP")))
15401 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15402 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15403 ((equal key1 org-closed-string) (setq key "CLOSED"))
15404 ((equal key1 org-clock-string) (setq key "CLOCK")))
15405 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15406 (progn
15407 (push (cons key string) props)
15408 ;; no need to search further if match is found
15409 (throw 'match t))
15410 (when (or (equal key "CLOCK") (not (assoc key props)))
15411 (push (cons key string) props)))))))
15413 (when (memq which '(all standard))
15414 ;; Get the standard properties, like :PROP: ...
15415 (setq range (org-get-property-block beg end))
15416 (when range
15417 (goto-char (car range))
15418 (while (re-search-forward org-property-re
15419 (cdr range) t)
15420 (setq key (org-match-string-no-properties 2)
15421 value (org-trim (or (org-match-string-no-properties 3) "")))
15422 (unless (member key excluded)
15423 (push (cons key (or value "")) props)))))
15424 (if clocksum
15425 (push (cons "CLOCKSUM"
15426 (org-columns-number-to-string (/ (float clocksum) 60.)
15427 'add_times))
15428 props))
15429 (if clocksumt
15430 (push (cons "CLOCKSUM_T"
15431 (org-columns-number-to-string (/ (float clocksumt) 60.)
15432 'add_times))
15433 props))
15434 (unless (assoc "CATEGORY" props)
15435 (push (cons "CATEGORY" (org-get-category)) props))
15436 (append sum-props (nreverse props)))))))
15438 (defun org-entry-get (pom property &optional inherit literal-nil)
15439 "Get value of PROPERTY for entry or content at point-or-marker POM.
15440 If INHERIT is non-nil and the entry does not have the property,
15441 then also check higher levels of the hierarchy.
15442 If INHERIT is the symbol `selective', use inheritance only if the setting
15443 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15444 If the property is present but empty, the return value is the empty string.
15445 If the property is not present at all, nil is returned.
15447 Return the value as a string.
15449 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15450 do not interpret it as the list atom nil. This is used for inheritance
15451 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15452 (org-with-point-at pom
15453 (if (and inherit (if (eq inherit 'selective)
15454 (org-property-inherit-p property)
15456 (org-entry-get-with-inheritance property literal-nil)
15457 (if (member property org-special-properties)
15458 ;; We need a special property. Use `org-entry-properties'
15459 ;; to retrieve it, but specify the wanted property
15460 (cdr (assoc property (org-entry-properties nil 'special property)))
15461 (org-with-wide-buffer
15462 (let ((range (org-get-property-block)))
15463 (when (and range (not (eq (car range) (cdr range)))
15464 (save-excursion
15465 (goto-char (car range))
15466 (re-search-forward
15467 (concat (org-re-property property) "\\|"
15468 (org-re-property (concat property "+")))
15469 (cdr range) t)))
15470 (let* ((props
15471 (list (or (assoc property org-file-properties)
15472 (assoc property org-global-properties)
15473 (assoc property org-global-properties-fixed))))
15474 (ap (lambda (key)
15475 (when (re-search-forward
15476 (org-re-property key) (cdr range) t)
15477 (setq props
15478 (org-update-property-plist
15480 (if (match-end 3)
15481 (org-match-string-no-properties 3) "")
15482 props)))))
15483 val)
15484 (goto-char (car range))
15485 (funcall ap property)
15486 (goto-char (car range))
15487 (while (funcall ap (concat property "+")))
15488 (setq val (cdr (assoc property props)))
15489 (when val (if literal-nil val (org-not-nil val)))))))))))
15491 (defun org-property-or-variable-value (var &optional inherit)
15492 "Check if there is a property fixing the value of VAR.
15493 If yes, return this value. If not, return the current value of the variable."
15494 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15495 (if (and prop (stringp prop) (string-match "\\S-" prop))
15496 (read prop)
15497 (symbol-value var))))
15499 (defun org-entry-delete (pom property)
15500 "Delete the property PROPERTY from entry at point-or-marker POM."
15501 (unless (member property org-special-properties)
15502 (org-with-point-at pom
15503 (let ((range (org-get-property-block)))
15504 (if (and range
15505 (goto-char (car range))
15506 (re-search-forward
15507 (org-re-property property)
15508 (cdr range) t))
15509 (progn
15510 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15511 (org-remove-empty-drawer-at (car range))
15513 nil)))))
15515 ;; Multi-values properties are properties that contain multiple values
15516 ;; These values are assumed to be single words, separated by whitespace.
15517 (defun org-entry-add-to-multivalued-property (pom property value)
15518 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15519 (let* ((old (org-entry-get pom property))
15520 (values (and old (org-split-string old "[ \t]"))))
15521 (setq value (org-entry-protect-space value))
15522 (unless (member value values)
15523 (setq values (append values (list value)))
15524 (org-entry-put pom property
15525 (mapconcat 'identity values " ")))))
15527 (defun org-entry-remove-from-multivalued-property (pom property value)
15528 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15529 (let* ((old (org-entry-get pom property))
15530 (values (and old (org-split-string old "[ \t]"))))
15531 (setq value (org-entry-protect-space value))
15532 (when (member value values)
15533 (setq values (delete value values))
15534 (org-entry-put pom property
15535 (mapconcat 'identity values " ")))))
15537 (defun org-entry-member-in-multivalued-property (pom property value)
15538 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15539 (let* ((old (org-entry-get pom property))
15540 (values (and old (org-split-string old "[ \t]"))))
15541 (setq value (org-entry-protect-space value))
15542 (member value values)))
15544 (defun org-entry-get-multivalued-property (pom property)
15545 "Return a list of values in a multivalued property."
15546 (let* ((value (org-entry-get pom property))
15547 (values (and value (org-split-string value "[ \t]"))))
15548 (mapcar 'org-entry-restore-space values)))
15550 (defun org-entry-put-multivalued-property (pom property &rest values)
15551 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15552 VALUES should be a list of strings. Spaces will be protected."
15553 (org-entry-put pom property
15554 (mapconcat 'org-entry-protect-space values " "))
15555 (let* ((value (org-entry-get pom property))
15556 (values (and value (org-split-string value "[ \t]"))))
15557 (mapcar 'org-entry-restore-space values)))
15559 (defun org-entry-protect-space (s)
15560 "Protect spaces and newline in string S."
15561 (while (string-match " " s)
15562 (setq s (replace-match "%20" t t s)))
15563 (while (string-match "\n" s)
15564 (setq s (replace-match "%0A" t t s)))
15567 (defun org-entry-restore-space (s)
15568 "Restore spaces and newline in string S."
15569 (while (string-match "%20" s)
15570 (setq s (replace-match " " t t s)))
15571 (while (string-match "%0A" s)
15572 (setq s (replace-match "\n" t t s)))
15575 (defvar org-entry-property-inherited-from (make-marker)
15576 "Marker pointing to the entry from where a property was inherited.
15577 Each call to `org-entry-get-with-inheritance' will set this marker to the
15578 location of the entry where the inheritance search matched. If there was
15579 no match, the marker will point nowhere.
15580 Note that also `org-entry-get' calls this function, if the INHERIT flag
15581 is set.")
15583 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15584 "Get PROPERTY of entry or content at point, search higher levels if needed.
15585 The search will stop at the first ancestor which has the property defined.
15586 If the value found is \"nil\", return nil to show that the property
15587 should be considered as undefined (this is the meaning of nil here).
15588 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15589 (move-marker org-entry-property-inherited-from nil)
15590 (let (tmp)
15591 (save-excursion
15592 (save-restriction
15593 (widen)
15594 (catch 'ex
15595 (while t
15596 (when (setq tmp (org-entry-get nil property nil literal-nil))
15597 (or (ignore-errors (org-back-to-heading t))
15598 (goto-char (point-min)))
15599 (move-marker org-entry-property-inherited-from (point))
15600 (throw 'ex tmp))
15601 (or (ignore-errors (org-up-heading-safe))
15602 (throw 'ex nil))))))
15603 (setq tmp (or tmp
15604 (cdr (assoc property org-file-properties))
15605 (cdr (assoc property org-global-properties))
15606 (cdr (assoc property org-global-properties-fixed))))
15607 (if literal-nil tmp (org-not-nil tmp))))
15609 (defvar org-property-changed-functions nil
15610 "Hook called when the value of a property has changed.
15611 Each hook function should accept two arguments, the name of the property
15612 and the new value.")
15614 (defun org-entry-put (pom property value)
15615 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15616 If the value is `nil', it is converted to the empty string.
15617 If it is not a string, an error is raised."
15618 (cond ((null value) (setq value ""))
15619 ((not (stringp value))
15620 (error "Properties values should be strings.")))
15621 (org-with-point-at pom
15622 (org-back-to-heading t)
15623 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15624 range)
15625 (cond
15626 ((equal property "TODO")
15627 (when (and (string-match "\\S-" value)
15628 (not (member value org-todo-keywords-1)))
15629 (user-error "\"%s\" is not a valid TODO state" value))
15630 (if (or (not value)
15631 (not (string-match "\\S-" value)))
15632 (setq value 'none))
15633 (org-todo value)
15634 (org-set-tags nil 'align))
15635 ((equal property "PRIORITY")
15636 (org-priority (if (and value (string-match "\\S-" value))
15637 (string-to-char value) ?\ ))
15638 (org-set-tags nil 'align))
15639 ((equal property "CLOCKSUM")
15640 (if (not (re-search-forward
15641 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15642 (error "Cannot find a clock log")
15643 (goto-char (- (match-end 1) 2))
15644 (cond
15645 ((eq value 'earlier) (org-timestamp-down))
15646 ((eq value 'later) (org-timestamp-up)))
15647 (org-clock-sum-current-item)))
15648 ((equal property "SCHEDULED")
15649 (if (re-search-forward org-scheduled-time-regexp end t)
15650 (cond
15651 ((eq value 'earlier) (org-timestamp-change -1 'day))
15652 ((eq value 'later) (org-timestamp-change 1 'day))
15653 (t (call-interactively 'org-schedule)))
15654 (call-interactively 'org-schedule)))
15655 ((equal property "DEADLINE")
15656 (if (re-search-forward org-deadline-time-regexp end t)
15657 (cond
15658 ((eq value 'earlier) (org-timestamp-change -1 'day))
15659 ((eq value 'later) (org-timestamp-change 1 'day))
15660 (t (call-interactively 'org-deadline)))
15661 (call-interactively 'org-deadline)))
15662 ((member property org-special-properties)
15663 (error "The %s property can not yet be set with `org-entry-put'"
15664 property))
15665 (t ; a non-special property
15666 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15667 (setq range (org-get-property-block beg end 'force))
15668 (goto-char (car range))
15669 (if (re-search-forward
15670 (org-re-property property) (cdr range) t)
15671 (progn
15672 (delete-region (match-beginning 0) (match-end 0))
15673 (goto-char (match-beginning 0)))
15674 (goto-char (cdr range))
15675 (insert "\n")
15676 (backward-char 1)
15677 (org-indent-line))
15678 (insert ":" property ":")
15679 (and value (insert " " value))
15680 (org-indent-line)))))
15681 (run-hook-with-args 'org-property-changed-functions property value)))
15683 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15684 "Get all property keys in the current buffer.
15685 With INCLUDE-SPECIALS, also list the special properties that reflect things
15686 like tags and TODO state.
15687 With INCLUDE-DEFAULTS, also include properties that has special meaning
15688 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15689 and others.
15690 With INCLUDE-COLUMNS, also include property names given in COLUMN
15691 formats in the current buffer."
15692 (let (rtn range cfmt s p)
15693 (save-excursion
15694 (save-restriction
15695 (widen)
15696 (goto-char (point-min))
15697 (while (re-search-forward org-property-start-re nil t)
15698 (setq range (org-get-property-block))
15699 (goto-char (car range))
15700 (while (re-search-forward org-property-re
15701 (cdr range) t)
15702 (add-to-list 'rtn (org-match-string-no-properties 2)))
15703 (outline-next-heading))))
15705 (when include-specials
15706 (setq rtn (append org-special-properties rtn)))
15708 (when include-defaults
15709 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15710 (add-to-list 'rtn org-effort-property))
15712 (when include-columns
15713 (save-excursion
15714 (save-restriction
15715 (widen)
15716 (goto-char (point-min))
15717 (while (re-search-forward
15718 "^[ \t]*\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15719 nil t)
15720 (setq cfmt (match-string 2) s 0)
15721 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15722 cfmt s)
15723 (setq s (match-end 0)
15724 p (match-string 1 cfmt))
15725 (unless (or (equal p "ITEM")
15726 (member p org-special-properties))
15727 (add-to-list 'rtn (match-string 1 cfmt))))))))
15729 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15731 (defun org-property-values (key)
15732 "Return a list of all values of property KEY in the current buffer."
15733 (save-excursion
15734 (save-restriction
15735 (widen)
15736 (goto-char (point-min))
15737 (let ((re (org-re-property key))
15738 values)
15739 (while (re-search-forward re nil t)
15740 (add-to-list 'values (org-trim (match-string 3))))
15741 (delete "" values)))))
15743 (defun org-insert-property-drawer ()
15744 "Insert a property drawer into the current entry."
15745 (org-back-to-heading t)
15746 (looking-at org-outline-regexp)
15747 (let ((indent (if org-adapt-indentation
15748 (- (match-end 0) (match-beginning 0))
15750 (beg (point))
15751 (re (concat "^[ \t]*" org-keyword-time-regexp))
15752 end hiddenp)
15753 (outline-next-heading)
15754 (setq end (point))
15755 (goto-char beg)
15756 (while (re-search-forward re end t))
15757 (setq hiddenp (outline-invisible-p))
15758 (end-of-line 1)
15759 (and (equal (char-after) ?\n) (forward-char 1))
15760 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15761 (if (member (match-string 1) '("CLOCK:" ":END:"))
15762 ;; just skip this line
15763 (beginning-of-line 2)
15764 ;; Drawer start, find the end
15765 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15766 (beginning-of-line 1)))
15767 (org-skip-over-state-notes)
15768 (skip-chars-backward " \t\n\r")
15769 (if (and (eq (char-before) ?*) (not (eq (char-after) ?\n)))
15770 (forward-char 1))
15771 (goto-char (point-at-eol))
15772 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15773 (beginning-of-line 0)
15774 (org-indent-to-column indent)
15775 (beginning-of-line 2)
15776 (org-indent-to-column indent)
15777 (beginning-of-line 0)
15778 (if hiddenp
15779 (save-excursion
15780 (org-back-to-heading t)
15781 (hide-entry))
15782 (org-flag-drawer t))))
15784 (defun org-insert-drawer (&optional arg drawer)
15785 "Insert a drawer at point.
15787 Optional argument DRAWER, when non-nil, is a string representing
15788 drawer's name. Otherwise, the user is prompted for a name.
15790 If a region is active, insert the drawer around that region
15791 instead.
15793 Point is left between drawer's boundaries."
15794 (interactive "P")
15795 (let* ((drawer (if arg "PROPERTIES"
15796 (or drawer (read-from-minibuffer "Drawer: ")))))
15797 (cond
15798 ;; With C-u, fall back on `org-insert-property-drawer'
15799 (arg (org-insert-property-drawer))
15801 ((not (org-string-match-p org-drawer-regexp (format ":%s:" drawer)))
15802 (user-error "Invalid drawer name"))
15803 ;; With an active region, insert a drawer at point.
15804 ((not (org-region-active-p))
15805 (progn
15806 (unless (bolp) (insert "\n"))
15807 (insert (format ":%s:\n\n:END:\n" drawer))
15808 (forward-line -2)))
15809 ;; Otherwise, insert the drawer at point
15811 (let ((rbeg (region-beginning))
15812 (rend (copy-marker (region-end))))
15813 (unwind-protect
15814 (progn
15815 (goto-char rbeg)
15816 (beginning-of-line)
15817 (when (save-excursion
15818 (re-search-forward org-outline-regexp-bol rend t))
15819 (user-error "Drawers cannot contain headlines"))
15820 ;; Position point at the beginning of the first
15821 ;; non-blank line in region. Insert drawer's opening
15822 ;; there, then indent it.
15823 (org-skip-whitespace)
15824 (beginning-of-line)
15825 (insert ":" drawer ":\n")
15826 (forward-line -1)
15827 (indent-for-tab-command)
15828 ;; Move point to the beginning of the first blank line
15829 ;; after the last non-blank line in region. Insert
15830 ;; drawer's closing, then indent it.
15831 (goto-char rend)
15832 (skip-chars-backward " \r\t\n")
15833 (insert "\n:END:")
15834 (deactivate-mark t)
15835 (indent-for-tab-command)
15836 (unless (eolp) (insert "\n")))
15837 ;; Clear marker, whatever the outcome of insertion is.
15838 (set-marker rend nil)))))))
15840 (defvar org-property-set-functions-alist nil
15841 "Property set function alist.
15842 Each entry should have the following format:
15844 (PROPERTY . READ-FUNCTION)
15846 The read function will be called with the same argument as
15847 `org-completing-read'.")
15849 (defun org-set-property-function (property)
15850 "Get the function that should be used to set PROPERTY.
15851 This is computed according to `org-property-set-functions-alist'."
15852 (or (cdr (assoc property org-property-set-functions-alist))
15853 'org-completing-read))
15855 (defun org-read-property-value (property)
15856 "Read PROPERTY value from user."
15857 (let* ((completion-ignore-case t)
15858 (allowed (org-property-get-allowed-values nil property 'table))
15859 (cur (org-entry-get nil property))
15860 (prompt (concat property " value"
15861 (if (and cur (string-match "\\S-" cur))
15862 (concat " [" cur "]") "") ": "))
15863 (set-function (org-set-property-function property))
15864 (val (if allowed
15865 (funcall set-function prompt allowed nil
15866 (not (get-text-property 0 'org-unrestricted
15867 (caar allowed))))
15868 (let (org-completion-use-ido org-completion-use-iswitchb)
15869 (funcall set-function prompt
15870 (mapcar 'list (org-property-values property))
15871 nil nil "" nil cur)))))
15872 (if (equal val "")
15874 val)))
15876 (defvar org-last-set-property nil)
15877 (defvar org-last-set-property-value nil)
15878 (defun org-read-property-name ()
15879 "Read a property name."
15880 (let* ((completion-ignore-case t)
15881 (keys (org-buffer-property-keys nil t t))
15882 (default-prop (or (save-excursion
15883 (save-match-data
15884 (beginning-of-line)
15885 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15886 (null (string= (match-string 1) "END"))
15887 (match-string 1))))
15888 org-last-set-property))
15889 (property (org-icompleting-read
15890 (concat "Property"
15891 (if default-prop (concat " [" default-prop "]") "")
15892 ": ")
15893 (mapcar 'list keys)
15894 nil nil nil nil
15895 default-prop)))
15896 (if (member property keys)
15897 property
15898 (or (cdr (assoc (downcase property)
15899 (mapcar (lambda (x) (cons (downcase x) x))
15900 keys)))
15901 property))))
15903 (defun org-set-property-and-value (use-last)
15904 "Allow to set [PROPERTY]: [value] direction from prompt.
15905 When use-default, don't even ask, just use the last
15906 \"[PROPERTY]: [value]\" string from the history."
15907 (interactive "P")
15908 (let* ((completion-ignore-case t)
15909 (pv (or (and use-last org-last-set-property-value)
15910 (org-completing-read
15911 "Enter a \"[Property]: [value]\" pair: "
15912 nil nil nil nil nil
15913 org-last-set-property-value)))
15914 prop val)
15915 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15916 (setq prop (match-string 1 pv)
15917 val (match-string 2 pv))
15918 (org-set-property prop val))))
15920 (defun org-set-property (property value)
15921 "In the current entry, set PROPERTY to VALUE.
15922 When called interactively, this will prompt for a property name, offering
15923 completion on existing and default properties. And then it will prompt
15924 for a value, offering completion either on allowed values (via an inherited
15925 xxx_ALL property) or on existing values in other instances of this property
15926 in the current file."
15927 (interactive (list nil nil))
15928 (let* ((property (or property (org-read-property-name)))
15929 (value (or value (org-read-property-value property)))
15930 (fn (cdr (assoc property org-properties-postprocess-alist))))
15931 (setq org-last-set-property property)
15932 (setq org-last-set-property-value (concat property ": " value))
15933 ;; Possibly postprocess the inserted value:
15934 (when fn (setq value (funcall fn value)))
15935 (unless (equal (org-entry-get nil property) value)
15936 (org-entry-put nil property value))))
15938 (defun org-delete-property (property)
15939 "In the current entry, delete PROPERTY."
15940 (interactive
15941 (let* ((completion-ignore-case t)
15942 (cat (org-entry-get (point) "CATEGORY"))
15943 (props0 (org-entry-properties nil 'standard))
15944 (props (if cat props0
15945 (delete `("CATEGORY" . ,(org-get-category)) props0)))
15946 (prop (if (< 1 (length props))
15947 (org-icompleting-read "Property: " props nil t)
15948 (caar props))))
15949 (list prop)))
15950 (if (org-entry-delete nil property)
15951 (message "Property %s deleted" property)))
15953 (defun org-delete-property-globally (property)
15954 "Remove PROPERTY globally, from all entries."
15955 (interactive
15956 (let* ((completion-ignore-case t)
15957 (prop (org-icompleting-read
15958 "Globally remove property: "
15959 (mapcar 'list (org-buffer-property-keys)))))
15960 (list prop)))
15961 (save-excursion
15962 (save-restriction
15963 (widen)
15964 (goto-char (point-min))
15965 (let ((cnt 0))
15966 (while (re-search-forward
15967 (org-re-property property)
15968 nil t)
15969 (setq cnt (1+ cnt))
15970 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15971 (message "Property \"%s\" removed from %d entries" property cnt)))))
15973 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15975 (defun org-compute-property-at-point ()
15976 "Compute the property at point.
15977 This looks for an enclosing column format, extracts the operator and
15978 then applies it to the property in the column format's scope."
15979 (interactive)
15980 (unless (org-at-property-p)
15981 (user-error "Not at a property"))
15982 (let ((prop (org-match-string-no-properties 2)))
15983 (org-columns-get-format-and-top-level)
15984 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15985 (user-error "No operator defined for property %s" prop))
15986 (org-columns-compute prop)))
15988 (defvar org-property-allowed-value-functions nil
15989 "Hook for functions supplying allowed values for a specific property.
15990 The functions must take a single argument, the name of the property, and
15991 return a flat list of allowed values. If \":ETC\" is one of
15992 the values, this means that these values are intended as defaults for
15993 completion, but that other values should be allowed too.
15994 The functions must return nil if they are not responsible for this
15995 property.")
15997 (defun org-property-get-allowed-values (pom property &optional table)
15998 "Get allowed values for the property PROPERTY.
15999 When TABLE is non-nil, return an alist that can directly be used for
16000 completion."
16001 (let (vals)
16002 (cond
16003 ((equal property "TODO")
16004 (setq vals (org-with-point-at pom
16005 (append org-todo-keywords-1 '("")))))
16006 ((equal property "PRIORITY")
16007 (let ((n org-lowest-priority))
16008 (while (>= n org-highest-priority)
16009 (push (char-to-string n) vals)
16010 (setq n (1- n)))))
16011 ((member property org-special-properties))
16012 ((setq vals (run-hook-with-args-until-success
16013 'org-property-allowed-value-functions property)))
16015 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16016 (when (and vals (string-match "\\S-" vals))
16017 (setq vals (car (read-from-string (concat "(" vals ")"))))
16018 (setq vals (mapcar (lambda (x)
16019 (cond ((stringp x) x)
16020 ((numberp x) (number-to-string x))
16021 ((symbolp x) (symbol-name x))
16022 (t "???")))
16023 vals)))))
16024 (when (member ":ETC" vals)
16025 (setq vals (remove ":ETC" vals))
16026 (org-add-props (car vals) '(org-unrestricted t)))
16027 (if table (mapcar 'list vals) vals)))
16029 (defun org-property-previous-allowed-value (&optional previous)
16030 "Switch to the next allowed value for this property."
16031 (interactive)
16032 (org-property-next-allowed-value t))
16034 (defun org-property-next-allowed-value (&optional previous)
16035 "Switch to the next allowed value for this property."
16036 (interactive)
16037 (unless (org-at-property-p)
16038 (user-error "Not at a property"))
16039 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16040 (key (match-string 2))
16041 (value (match-string 3))
16042 (allowed (or (org-property-get-allowed-values (point) key)
16043 (and (member value '("[ ]" "[-]" "[X]"))
16044 '("[ ]" "[X]"))))
16045 (heading (save-match-data (nth 4 (org-heading-components))))
16046 nval)
16047 (unless allowed
16048 (user-error "Allowed values for this property have not been defined"))
16049 (if previous (setq allowed (reverse allowed)))
16050 (if (member value allowed)
16051 (setq nval (car (cdr (member value allowed)))))
16052 (setq nval (or nval (car allowed)))
16053 (if (equal nval value)
16054 (user-error "Only one allowed value for this property"))
16055 (org-at-property-p)
16056 (replace-match (concat " :" key ": " nval) t t)
16057 (org-indent-line)
16058 (beginning-of-line 1)
16059 (skip-chars-forward " \t")
16060 (when (equal prop org-effort-property)
16061 (save-excursion
16062 (org-back-to-heading t)
16063 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
16064 (when (string= org-clock-current-task heading)
16065 (setq org-clock-effort nval)
16066 (org-clock-update-mode-line)))
16067 (run-hook-with-args 'org-property-changed-functions key nval)))
16069 (defun org-find-olp (path &optional this-buffer)
16070 "Return a marker pointing to the entry at outline path OLP.
16071 If anything goes wrong, throw an error.
16072 You can wrap this call to catch the error like this:
16074 (condition-case msg
16075 (org-mobile-locate-entry (match-string 4))
16076 (error (nth 1 msg)))
16078 The return value will then be either a string with the error message,
16079 or a marker if everything is OK.
16081 If THIS-BUFFER is set, the outline path does not contain a file,
16082 only headings."
16083 (let* ((file (if this-buffer buffer-file-name (pop path)))
16084 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16085 (level 1)
16086 (lmin 1)
16087 (lmax 1)
16088 limit re end found pos heading cnt flevel)
16089 (unless buffer (error "File not found :%s" file))
16090 (with-current-buffer buffer
16091 (save-excursion
16092 (save-restriction
16093 (widen)
16094 (setq limit (point-max))
16095 (goto-char (point-min))
16096 (while (setq heading (pop path))
16097 (setq re (format org-complex-heading-regexp-format
16098 (regexp-quote heading)))
16099 (setq cnt 0 pos (point))
16100 (while (re-search-forward re end t)
16101 (setq level (- (match-end 1) (match-beginning 1)))
16102 (if (and (>= level lmin) (<= level lmax))
16103 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16104 (when (= cnt 0) (error "Heading not found on level %d: %s"
16105 lmax heading))
16106 (when (> cnt 1) (error "Heading not unique on level %d: %s"
16107 lmax heading))
16108 (goto-char found)
16109 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16110 (setq end (save-excursion (org-end-of-subtree t t))))
16111 (when (org-at-heading-p)
16112 (point-marker)))))))
16114 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16115 "Find node HEADING in BUFFER.
16116 Return a marker to the heading if it was found, or nil if not.
16117 If POS-ONLY is set, return just the position instead of a marker.
16119 The heading text must match exact, but it may have a TODO keyword,
16120 a priority cookie and tags in the standard locations."
16121 (with-current-buffer (or buffer (current-buffer))
16122 (save-excursion
16123 (save-restriction
16124 (widen)
16125 (goto-char (point-min))
16126 (let (case-fold-search)
16127 (if (re-search-forward
16128 (format org-complex-heading-regexp-format
16129 (regexp-quote heading)) nil t)
16130 (if pos-only
16131 (match-beginning 0)
16132 (move-marker (make-marker) (match-beginning 0)))))))))
16134 (defun org-find-exact-heading-in-directory (heading &optional dir)
16135 "Find Org node headline HEADING in all .org files in directory DIR.
16136 When the target headline is found, return a marker to this location."
16137 (let ((files (directory-files (or dir default-directory)
16138 nil "\\`[^.#].*\\.org\\'"))
16139 file visiting m buffer)
16140 (catch 'found
16141 (while (setq file (pop files))
16142 (message "trying %s" file)
16143 (setq visiting (org-find-base-buffer-visiting file))
16144 (setq buffer (or visiting (find-file-noselect file)))
16145 (setq m (org-find-exact-headline-in-buffer
16146 heading buffer))
16147 (when (and (not m) (not visiting)) (kill-buffer buffer))
16148 (and m (throw 'found m))))))
16150 (defun org-find-entry-with-id (ident)
16151 "Locate the entry that contains the ID property with exact value IDENT.
16152 IDENT can be a string, a symbol or a number, this function will search for
16153 the string representation of it.
16154 Return the position where this entry starts, or nil if there is no such entry."
16155 (interactive "sID: ")
16156 (let ((id (cond
16157 ((stringp ident) ident)
16158 ((symbol-name ident) (symbol-name ident))
16159 ((numberp ident) (number-to-string ident))
16160 (t (error "IDENT %s must be a string, symbol or number" ident))))
16161 (case-fold-search nil))
16162 (save-excursion
16163 (save-restriction
16164 (widen)
16165 (goto-char (point-min))
16166 (when (re-search-forward
16167 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16168 nil t)
16169 (org-back-to-heading t)
16170 (point))))))
16172 ;;;; Timestamps
16174 (defvar org-last-changed-timestamp nil)
16175 (defvar org-last-inserted-timestamp nil
16176 "The last time stamp inserted with `org-insert-time-stamp'.")
16177 (defvar org-ts-what) ; dynamically scoped parameter
16179 (defun org-time-stamp (arg &optional inactive)
16180 "Prompt for a date/time and insert a time stamp.
16181 If the user specifies a time like HH:MM or if this command is
16182 called with at least one prefix argument, the time stamp contains
16183 the date and the time. Otherwise, only the date is be included.
16185 All parts of a date not specified by the user is filled in from
16186 the current date/time. So if you just press return without
16187 typing anything, the time stamp will represent the current
16188 date/time.
16190 If there is already a timestamp at the cursor, it will be
16191 modified.
16193 With two universal prefix arguments, insert an active timestamp
16194 with the current time without prompting the user.
16196 When called from lisp, the timestamp is inactive if INACTIVE is
16197 non-nil."
16198 (interactive "P")
16199 (let* ((ts nil)
16200 (default-time
16201 ;; Default time is either today, or, when entering a range,
16202 ;; the range start.
16203 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16204 (save-excursion
16205 (re-search-backward
16206 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16207 (- (point) 20) t)))
16208 (apply 'encode-time (org-parse-time-string (match-string 1)))
16209 (current-time)))
16210 (default-input (and ts (org-get-compact-tod ts)))
16211 (repeater (save-excursion
16212 (save-match-data
16213 (beginning-of-line)
16214 (when (re-search-forward
16215 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16216 (save-excursion (progn (end-of-line) (point))) t)
16217 (match-string 0)))))
16218 org-time-was-given org-end-time-was-given time)
16219 (cond
16220 ((and (org-at-timestamp-p t)
16221 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16222 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16223 (insert "--")
16224 (setq time (let ((this-command this-command))
16225 (org-read-date arg 'totime nil nil
16226 default-time default-input inactive)))
16227 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16228 ((org-at-timestamp-p t)
16229 (setq time (let ((this-command this-command))
16230 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16231 (when (org-at-timestamp-p t) ; just to get the match data
16232 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16233 (replace-match "")
16234 (setq org-last-changed-timestamp
16235 (org-insert-time-stamp
16236 time (or org-time-was-given arg)
16237 inactive nil nil (list org-end-time-was-given)))
16238 (when repeater (goto-char (1- (point))) (insert " " repeater)
16239 (setq org-last-changed-timestamp
16240 (concat (substring org-last-inserted-timestamp 0 -1)
16241 " " repeater ">"))))
16242 (message "Timestamp updated"))
16243 ((equal arg '(16))
16244 (org-insert-time-stamp (current-time) t inactive))
16246 (setq time (let ((this-command this-command))
16247 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16248 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16249 nil nil (list org-end-time-was-given))))))
16251 ;; FIXME: can we use this for something else, like computing time differences?
16252 (defun org-get-compact-tod (s)
16253 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16254 (let* ((t1 (match-string 1 s))
16255 (h1 (string-to-number (match-string 2 s)))
16256 (m1 (string-to-number (match-string 3 s)))
16257 (t2 (and (match-end 4) (match-string 5 s)))
16258 (h2 (and t2 (string-to-number (match-string 6 s))))
16259 (m2 (and t2 (string-to-number (match-string 7 s))))
16260 dh dm)
16261 (if (not t2)
16263 (setq dh (- h2 h1) dm (- m2 m1))
16264 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16265 (concat t1 "+" (number-to-string dh)
16266 (and (/= 0 dm) (format ":%02d" dm)))))))
16268 (defun org-time-stamp-inactive (&optional arg)
16269 "Insert an inactive time stamp.
16270 An inactive time stamp is enclosed in square brackets instead of angle
16271 brackets. It is inactive in the sense that it does not trigger agenda entries,
16272 does not link to the calendar and cannot be changed with the S-cursor keys.
16273 So these are more for recording a certain time/date."
16274 (interactive "P")
16275 (org-time-stamp arg 'inactive))
16277 (defvar org-date-ovl (make-overlay 1 1))
16278 (overlay-put org-date-ovl 'face 'org-date-selected)
16279 (org-detach-overlay org-date-ovl)
16281 (defvar org-ans1) ; dynamically scoped parameter
16282 (defvar org-ans2) ; dynamically scoped parameter
16284 (defvar org-plain-time-of-day-regexp) ; defined below
16286 (defvar org-overriding-default-time nil) ; dynamically scoped
16287 (defvar org-read-date-overlay nil)
16288 (defvar org-dcst nil) ; dynamically scoped
16289 (defvar org-read-date-history nil)
16290 (defvar org-read-date-final-answer nil)
16291 (defvar org-read-date-analyze-futurep nil)
16292 (defvar org-read-date-analyze-forced-year nil)
16293 (defvar org-read-date-inactive)
16295 (defvar org-read-date-minibuffer-local-map
16296 (let* ((org-replace-disputed-keys nil)
16297 (map (make-sparse-keymap)))
16298 (set-keymap-parent map minibuffer-local-map)
16299 (org-defkey map (kbd ".")
16300 (lambda () (interactive)
16301 ;; Are we at the beginning of the prompt?
16302 (if (looking-back "^[^:]+: ")
16303 (org-eval-in-calendar '(calendar-goto-today))
16304 (insert "."))))
16305 (org-defkey map (kbd "C-.")
16306 (lambda () (interactive)
16307 (org-eval-in-calendar '(calendar-goto-today))))
16308 (org-defkey map [(meta shift left)]
16309 (lambda () (interactive)
16310 (org-eval-in-calendar '(calendar-backward-month 1))))
16311 (org-defkey map [(meta shift right)]
16312 (lambda () (interactive)
16313 (org-eval-in-calendar '(calendar-forward-month 1))))
16314 (org-defkey map [(meta shift up)]
16315 (lambda () (interactive)
16316 (org-eval-in-calendar '(calendar-backward-year 1))))
16317 (org-defkey map [(meta shift down)]
16318 (lambda () (interactive)
16319 (org-eval-in-calendar '(calendar-forward-year 1))))
16320 (org-defkey map [?\e (shift left)]
16321 (lambda () (interactive)
16322 (org-eval-in-calendar '(calendar-backward-month 1))))
16323 (org-defkey map [?\e (shift right)]
16324 (lambda () (interactive)
16325 (org-eval-in-calendar '(calendar-forward-month 1))))
16326 (org-defkey map [?\e (shift up)]
16327 (lambda () (interactive)
16328 (org-eval-in-calendar '(calendar-backward-year 1))))
16329 (org-defkey map [?\e (shift down)]
16330 (lambda () (interactive)
16331 (org-eval-in-calendar '(calendar-forward-year 1))))
16332 (org-defkey map [(shift up)]
16333 (lambda () (interactive)
16334 (org-eval-in-calendar '(calendar-backward-week 1))))
16335 (org-defkey map [(shift down)]
16336 (lambda () (interactive)
16337 (org-eval-in-calendar '(calendar-forward-week 1))))
16338 (org-defkey map [(shift left)]
16339 (lambda () (interactive)
16340 (org-eval-in-calendar '(calendar-backward-day 1))))
16341 (org-defkey map [(shift right)]
16342 (lambda () (interactive)
16343 (org-eval-in-calendar '(calendar-forward-day 1))))
16344 (org-defkey map "!"
16345 (lambda () (interactive)
16346 (org-eval-in-calendar '(diary-view-entries))
16347 (message "")))
16348 (org-defkey map ">"
16349 (lambda () (interactive)
16350 (org-eval-in-calendar '(scroll-calendar-left 1))))
16351 (org-defkey map "<"
16352 (lambda () (interactive)
16353 (org-eval-in-calendar '(scroll-calendar-right 1))))
16354 (org-defkey map "\C-v"
16355 (lambda () (interactive)
16356 (org-eval-in-calendar
16357 '(calendar-scroll-left-three-months 1))))
16358 (org-defkey map "\M-v"
16359 (lambda () (interactive)
16360 (org-eval-in-calendar
16361 '(calendar-scroll-right-three-months 1))))
16362 map)
16363 "Keymap for minibuffer commands when using `org-read-date'.")
16365 (defvar org-def)
16366 (defvar org-defdecode)
16367 (defvar org-with-time)
16369 (defun org-read-date (&optional org-with-time to-time from-string prompt
16370 default-time default-input inactive)
16371 "Read a date, possibly a time, and make things smooth for the user.
16372 The prompt will suggest to enter an ISO date, but you can also enter anything
16373 which will at least partially be understood by `parse-time-string'.
16374 Unrecognized parts of the date will default to the current day, month, year,
16375 hour and minute. If this command is called to replace a timestamp at point,
16376 or to enter the second timestamp of a range, the default time is taken
16377 from the existing stamp. Furthermore, the command prefers the future,
16378 so if you are giving a date where the year is not given, and the day-month
16379 combination is already past in the current year, it will assume you
16380 mean next year. For details, see the manual. A few examples:
16382 3-2-5 --> 2003-02-05
16383 feb 15 --> currentyear-02-15
16384 2/15 --> currentyear-02-15
16385 sep 12 9 --> 2009-09-12
16386 12:45 --> today 12:45
16387 22 sept 0:34 --> currentyear-09-22 0:34
16388 12 --> currentyear-currentmonth-12
16389 Fri --> nearest Friday after today
16390 -Tue --> last Tuesday
16391 etc.
16393 Furthermore you can specify a relative date by giving, as the *first* thing
16394 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16395 change in days weeks, months, years.
16396 With a single plus or minus, the date is relative to today. With a double
16397 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16398 +4d --> four days from today
16399 +4 --> same as above
16400 +2w --> two weeks from today
16401 ++5 --> five days from default date
16403 The function understands only English month and weekday abbreviations.
16405 While prompting, a calendar is popped up - you can also select the
16406 date with the mouse (button 1). The calendar shows a period of three
16407 months. To scroll it to other months, use the keys `>' and `<'.
16408 If you don't like the calendar, turn it off with
16409 \(setq org-read-date-popup-calendar nil)
16411 With optional argument TO-TIME, the date will immediately be converted
16412 to an internal time.
16413 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16414 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16415 still enter a time, and this function will inform the calling routine
16416 about this change. The calling routine may then choose to change the
16417 format used to insert the time stamp into the buffer to include the time.
16418 With optional argument FROM-STRING, read from this string instead from
16419 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16420 the time/date that is used for everything that is not specified by the
16421 user."
16422 (require 'parse-time)
16423 (let* ((org-time-stamp-rounding-minutes
16424 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16425 (org-dcst org-display-custom-times)
16426 (ct (org-current-time))
16427 (org-def (or org-overriding-default-time default-time ct))
16428 (org-defdecode (decode-time org-def))
16429 (dummy (progn
16430 (when (< (nth 2 org-defdecode) org-extend-today-until)
16431 (setcar (nthcdr 2 org-defdecode) -1)
16432 (setcar (nthcdr 1 org-defdecode) 59)
16433 (setq org-def (apply 'encode-time org-defdecode)
16434 org-defdecode (decode-time org-def)))))
16435 (mouse-autoselect-window nil) ; Don't let the mouse jump
16436 (calendar-frame-setup nil)
16437 (calendar-setup nil)
16438 (calendar-move-hook nil)
16439 (calendar-view-diary-initially-flag nil)
16440 (calendar-view-holidays-initially-flag nil)
16441 (timestr (format-time-string
16442 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16443 (prompt (concat (if prompt (concat prompt " ") "")
16444 (format "Date+time [%s]: " timestr)))
16445 ans (org-ans0 "") org-ans1 org-ans2 final)
16447 (cond
16448 (from-string (setq ans from-string))
16449 (org-read-date-popup-calendar
16450 (save-excursion
16451 (save-window-excursion
16452 (calendar)
16453 (org-eval-in-calendar '(setq cursor-type nil) t)
16454 (unwind-protect
16455 (progn
16456 (calendar-forward-day (- (time-to-days org-def)
16457 (calendar-absolute-from-gregorian
16458 (calendar-current-date))))
16459 (org-eval-in-calendar nil t)
16460 (let* ((old-map (current-local-map))
16461 (map (copy-keymap calendar-mode-map))
16462 (minibuffer-local-map
16463 (copy-keymap org-read-date-minibuffer-local-map)))
16464 (org-defkey map (kbd "RET") 'org-calendar-select)
16465 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16466 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16467 (unwind-protect
16468 (progn
16469 (use-local-map map)
16470 (setq org-read-date-inactive inactive)
16471 (add-hook 'post-command-hook 'org-read-date-display)
16472 (setq org-ans0 (read-string prompt default-input
16473 'org-read-date-history nil))
16474 ;; org-ans0: from prompt
16475 ;; org-ans1: from mouse click
16476 ;; org-ans2: from calendar motion
16477 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16478 (remove-hook 'post-command-hook 'org-read-date-display)
16479 (use-local-map old-map)
16480 (when org-read-date-overlay
16481 (delete-overlay org-read-date-overlay)
16482 (setq org-read-date-overlay nil)))))
16483 (bury-buffer "*Calendar*")))))
16485 (t ; Naked prompt only
16486 (unwind-protect
16487 (setq ans (read-string prompt default-input
16488 'org-read-date-history timestr))
16489 (when org-read-date-overlay
16490 (delete-overlay org-read-date-overlay)
16491 (setq org-read-date-overlay nil)))))
16493 (setq final (org-read-date-analyze ans org-def org-defdecode))
16495 (when org-read-date-analyze-forced-year
16496 (message "Year was forced into %s"
16497 (if org-read-date-force-compatible-dates
16498 "compatible range (1970-2037)"
16499 "range representable on this machine"))
16500 (ding))
16502 ;; One round trip to get rid of 34th of August and stuff like that....
16503 (setq final (decode-time (apply 'encode-time final)))
16505 (setq org-read-date-final-answer ans)
16507 (if to-time
16508 (apply 'encode-time final)
16509 (if (and (boundp 'org-time-was-given) org-time-was-given)
16510 (format "%04d-%02d-%02d %02d:%02d"
16511 (nth 5 final) (nth 4 final) (nth 3 final)
16512 (nth 2 final) (nth 1 final))
16513 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16515 (defun org-read-date-display ()
16516 "Display the current date prompt interpretation in the minibuffer."
16517 (when org-read-date-display-live
16518 (when org-read-date-overlay
16519 (delete-overlay org-read-date-overlay))
16520 (when (minibufferp (current-buffer))
16521 (save-excursion
16522 (end-of-line 1)
16523 (while (not (equal (buffer-substring
16524 (max (point-min) (- (point) 4)) (point))
16525 " "))
16526 (insert " ")))
16527 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16528 " " (or org-ans1 org-ans2)))
16529 (org-end-time-was-given nil)
16530 (f (org-read-date-analyze ans org-def org-defdecode))
16531 (fmts (if org-dcst
16532 org-time-stamp-custom-formats
16533 org-time-stamp-formats))
16534 (fmt (if (or org-with-time
16535 (and (boundp 'org-time-was-given) org-time-was-given))
16536 (cdr fmts)
16537 (car fmts)))
16538 (txt (format-time-string fmt (apply 'encode-time f)))
16539 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16540 (txt (concat "=> " txt)))
16541 (when (and org-end-time-was-given
16542 (string-match org-plain-time-of-day-regexp txt))
16543 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16544 org-end-time-was-given
16545 (substring txt (match-end 0)))))
16546 (when org-read-date-analyze-futurep
16547 (setq txt (concat txt " (=>F)")))
16548 (setq org-read-date-overlay
16549 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16550 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16552 (defun org-read-date-analyze (ans org-def org-defdecode)
16553 "Analyze the combined answer of the date prompt."
16554 ;; FIXME: cleanup and comment
16555 (let ((nowdecode (decode-time (current-time)))
16556 delta deltan deltaw deltadef year month day
16557 hour minute second wday pm h2 m2 tl wday1
16558 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16559 (setq org-read-date-analyze-futurep nil
16560 org-read-date-analyze-forced-year nil)
16561 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16562 (setq ans "+0"))
16564 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16565 (setq ans (replace-match "" t t ans)
16566 deltan (car delta)
16567 deltaw (nth 1 delta)
16568 deltadef (nth 2 delta)))
16570 ;; Check if there is an iso week date in there. If yes, store the
16571 ;; info and postpone interpreting it until the rest of the parsing
16572 ;; is done.
16573 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16574 (setq iso-year (if (match-end 1)
16575 (org-small-year-to-year
16576 (string-to-number (match-string 1 ans))))
16577 iso-weekday (if (match-end 3)
16578 (string-to-number (match-string 3 ans)))
16579 iso-week (string-to-number (match-string 2 ans)))
16580 (setq ans (replace-match "" t t ans)))
16582 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16583 (when (string-match
16584 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16585 (setq year (if (match-end 2)
16586 (string-to-number (match-string 2 ans))
16587 (progn (setq kill-year t)
16588 (string-to-number (format-time-string "%Y"))))
16589 month (string-to-number (match-string 3 ans))
16590 day (string-to-number (match-string 4 ans)))
16591 (if (< year 100) (setq year (+ 2000 year)))
16592 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16593 t nil ans)))
16595 ;; Help matching dotted european dates
16596 (when (string-match
16597 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16598 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16599 (setq kill-year t)
16600 (string-to-number (format-time-string "%Y")))
16601 day (string-to-number (match-string 1 ans))
16602 month (string-to-number (match-string 2 ans))
16603 ans (replace-match (format "%04d-%02d-%02d" year month day)
16604 t nil ans)))
16606 ;; Help matching american dates, like 5/30 or 5/30/7
16607 (when (string-match
16608 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16609 (setq year (if (match-end 4)
16610 (string-to-number (match-string 4 ans))
16611 (progn (setq kill-year t)
16612 (string-to-number (format-time-string "%Y"))))
16613 month (string-to-number (match-string 1 ans))
16614 day (string-to-number (match-string 2 ans)))
16615 (if (< year 100) (setq year (+ 2000 year)))
16616 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16617 t nil ans)))
16618 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16619 ;; If there is a time with am/pm, and *no* time without it, we convert
16620 ;; so that matching will be successful.
16621 (loop for i from 1 to 2 do ; twice, for end time as well
16622 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16623 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16624 (setq hour (string-to-number (match-string 1 ans))
16625 minute (if (match-end 3)
16626 (string-to-number (match-string 3 ans))
16628 pm (equal ?p
16629 (string-to-char (downcase (match-string 4 ans)))))
16630 (if (and (= hour 12) (not pm))
16631 (setq hour 0)
16632 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16633 (setq ans (replace-match (format "%02d:%02d" hour minute)
16634 t t ans))))
16636 ;; Check if a time range is given as a duration
16637 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16638 (setq hour (string-to-number (match-string 1 ans))
16639 h2 (+ hour (string-to-number (match-string 3 ans)))
16640 minute (string-to-number (match-string 2 ans))
16641 m2 (+ minute (if (match-end 5) (string-to-number
16642 (match-string 5 ans))0)))
16643 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16644 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16645 t t ans)))
16647 ;; Check if there is a time range
16648 (when (boundp 'org-end-time-was-given)
16649 (setq org-time-was-given nil)
16650 (when (and (string-match org-plain-time-of-day-regexp ans)
16651 (match-end 8))
16652 (setq org-end-time-was-given (match-string 8 ans))
16653 (setq ans (concat (substring ans 0 (match-beginning 7))
16654 (substring ans (match-end 7))))))
16656 (setq tl (parse-time-string ans)
16657 day (or (nth 3 tl) (nth 3 org-defdecode))
16658 month (or (nth 4 tl)
16659 (if (and org-read-date-prefer-future
16660 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16661 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16662 (nth 4 org-defdecode)))
16663 year (or (and (not kill-year) (nth 5 tl))
16664 (if (and org-read-date-prefer-future
16665 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16666 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16667 (nth 5 org-defdecode)))
16668 hour (or (nth 2 tl) (nth 2 org-defdecode))
16669 minute (or (nth 1 tl) (nth 1 org-defdecode))
16670 second (or (nth 0 tl) 0)
16671 wday (nth 6 tl))
16673 (when (and (eq org-read-date-prefer-future 'time)
16674 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16675 (equal day (nth 3 nowdecode))
16676 (equal month (nth 4 nowdecode))
16677 (equal year (nth 5 nowdecode))
16678 (nth 2 tl)
16679 (or (< (nth 2 tl) (nth 2 nowdecode))
16680 (and (= (nth 2 tl) (nth 2 nowdecode))
16681 (nth 1 tl)
16682 (< (nth 1 tl) (nth 1 nowdecode)))))
16683 (setq day (1+ day)
16684 futurep t))
16686 ;; Special date definitions below
16687 (cond
16688 (iso-week
16689 ;; There was an iso week
16690 (require 'cal-iso)
16691 (setq futurep nil)
16692 (setq year (or iso-year year)
16693 day (or iso-weekday wday 1)
16694 wday nil ; to make sure that the trigger below does not match
16695 iso-date (calendar-gregorian-from-absolute
16696 (calendar-absolute-from-iso
16697 (list iso-week day year))))
16698 ; FIXME: Should we also push ISO weeks into the future?
16699 ; (when (and org-read-date-prefer-future
16700 ; (not iso-year)
16701 ; (< (calendar-absolute-from-gregorian iso-date)
16702 ; (time-to-days (current-time))))
16703 ; (setq year (1+ year)
16704 ; iso-date (calendar-gregorian-from-absolute
16705 ; (calendar-absolute-from-iso
16706 ; (list iso-week day year)))))
16707 (setq month (car iso-date)
16708 year (nth 2 iso-date)
16709 day (nth 1 iso-date)))
16710 (deltan
16711 (setq futurep nil)
16712 (unless deltadef
16713 (let ((now (decode-time (current-time))))
16714 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16715 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16716 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16717 ((equal deltaw "m") (setq month (+ month deltan)))
16718 ((equal deltaw "y") (setq year (+ year deltan)))))
16719 ((and wday (not (nth 3 tl)))
16720 ;; Weekday was given, but no day, so pick that day in the week
16721 ;; on or after the derived date.
16722 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16723 (unless (equal wday wday1)
16724 (setq day (+ day (% (- wday wday1 -7) 7))))))
16725 (if (and (boundp 'org-time-was-given)
16726 (nth 2 tl))
16727 (setq org-time-was-given t))
16728 (if (< year 100) (setq year (+ 2000 year)))
16729 ;; Check of the date is representable
16730 (if org-read-date-force-compatible-dates
16731 (progn
16732 (if (< year 1970)
16733 (setq year 1970 org-read-date-analyze-forced-year t))
16734 (if (> year 2037)
16735 (setq year 2037 org-read-date-analyze-forced-year t)))
16736 (condition-case nil
16737 (ignore (encode-time second minute hour day month year))
16738 (error
16739 (setq year (nth 5 org-defdecode))
16740 (setq org-read-date-analyze-forced-year t))))
16741 (setq org-read-date-analyze-futurep futurep)
16742 (list second minute hour day month year)))
16744 (defvar parse-time-weekdays)
16745 (defun org-read-date-get-relative (s today default)
16746 "Check string S for special relative date string.
16747 TODAY and DEFAULT are internal times, for today and for a default.
16748 Return shift list (N what def-flag)
16749 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16750 N is the number of WHATs to shift.
16751 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16752 the DEFAULT date rather than TODAY."
16753 (require 'parse-time)
16754 (when (and
16755 (string-match
16756 (concat
16757 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16758 "\\([0-9]+\\)?"
16759 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16760 "\\([ \t]\\|$\\)") s)
16761 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16762 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16763 (string-to-char (substring (match-string 1 s) -1))
16764 ?+))
16765 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16766 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16767 (what (if (match-end 3) (match-string 3 s) "d"))
16768 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16769 (date (if rel default today))
16770 (wday (nth 6 (decode-time date)))
16771 delta)
16772 (if wday1
16773 (progn
16774 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16775 (if (= delta 0) (setq delta 7))
16776 (if (= dir ?-)
16777 (progn
16778 (setq delta (- delta 7))
16779 (if (= delta 0) (setq delta -7))))
16780 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16781 (list delta "d" rel))
16782 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16784 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16785 "Turn a user-specified date into the internal representation.
16786 The internal representation needed by the calendar is (month day year).
16787 This is a wrapper to handle the brain-dead convention in calendar that
16788 user function argument order change dependent on argument order."
16789 (if (boundp 'calendar-date-style)
16790 (cond
16791 ((eq calendar-date-style 'american)
16792 (list arg1 arg2 arg3))
16793 ((eq calendar-date-style 'european)
16794 (list arg2 arg1 arg3))
16795 ((eq calendar-date-style 'iso)
16796 (list arg2 arg3 arg1)))
16797 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16798 (if (org-bound-and-true-p european-calendar-style)
16799 (list arg2 arg1 arg3)
16800 (list arg1 arg2 arg3)))))
16802 (defun org-eval-in-calendar (form &optional keepdate)
16803 "Eval FORM in the calendar window and return to current window.
16804 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16805 otherwise stick to the current value of `org-ans2'."
16806 (let ((sf (selected-frame))
16807 (sw (selected-window)))
16808 (select-window (get-buffer-window "*Calendar*" t))
16809 (eval form)
16810 (when (and (not keepdate) (calendar-cursor-to-date))
16811 (let* ((date (calendar-cursor-to-date))
16812 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16813 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16814 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16815 (select-window sw)
16816 (org-select-frame-set-input-focus sf)))
16818 (defun org-calendar-select ()
16819 "Return to `org-read-date' with the date currently selected.
16820 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16821 (interactive)
16822 (when (calendar-cursor-to-date)
16823 (let* ((date (calendar-cursor-to-date))
16824 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16825 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16826 (if (active-minibuffer-window) (exit-minibuffer))))
16828 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16829 "Insert a date stamp for the date given by the internal TIME.
16830 WITH-HM means use the stamp format that includes the time of the day.
16831 INACTIVE means use square brackets instead of angular ones, so that the
16832 stamp will not contribute to the agenda.
16833 PRE and POST are optional strings to be inserted before and after the
16834 stamp.
16835 The command returns the inserted time stamp."
16836 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16837 stamp)
16838 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16839 (insert-before-markers (or pre ""))
16840 (when (listp extra)
16841 (setq extra (car extra))
16842 (if (and (stringp extra)
16843 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16844 (setq extra (format "-%02d:%02d"
16845 (string-to-number (match-string 1 extra))
16846 (string-to-number (match-string 2 extra))))
16847 (setq extra nil)))
16848 (when extra
16849 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16850 (insert-before-markers (setq stamp (format-time-string fmt time)))
16851 (insert-before-markers (or post ""))
16852 (setq org-last-inserted-timestamp stamp)))
16854 (defun org-toggle-time-stamp-overlays ()
16855 "Toggle the use of custom time stamp formats."
16856 (interactive)
16857 (setq org-display-custom-times (not org-display-custom-times))
16858 (unless org-display-custom-times
16859 (let ((p (point-min)) (bmp (buffer-modified-p)))
16860 (while (setq p (next-single-property-change p 'display))
16861 (if (and (get-text-property p 'display)
16862 (eq (get-text-property p 'face) 'org-date))
16863 (remove-text-properties
16864 p (setq p (next-single-property-change p 'display))
16865 '(display t))))
16866 (set-buffer-modified-p bmp)))
16867 (if (featurep 'xemacs)
16868 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16869 (org-restart-font-lock)
16870 (setq org-table-may-need-update t)
16871 (if org-display-custom-times
16872 (message "Time stamps are overlaid with custom format")
16873 (message "Time stamp overlays removed")))
16875 (defun org-display-custom-time (beg end)
16876 "Overlay modified time stamp format over timestamp between BEG and END."
16877 (let* ((ts (buffer-substring beg end))
16878 t1 w1 with-hm tf time str w2 (off 0))
16879 (save-match-data
16880 (setq t1 (org-parse-time-string ts t))
16881 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16882 (setq off (- (match-end 0) (match-beginning 0)))))
16883 (setq end (- end off))
16884 (setq w1 (- end beg)
16885 with-hm (and (nth 1 t1) (nth 2 t1))
16886 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16887 time (org-fix-decoded-time t1)
16888 str (org-add-props
16889 (format-time-string
16890 (substring tf 1 -1) (apply 'encode-time time))
16891 nil 'mouse-face 'highlight)
16892 w2 (length str))
16893 (if (not (= w2 w1))
16894 (add-text-properties (1+ beg) (+ 2 beg)
16895 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16896 (if (featurep 'xemacs)
16897 (progn
16898 (put-text-property beg end 'invisible t)
16899 (put-text-property beg end 'end-glyph (make-glyph str)))
16900 (put-text-property beg end 'display str))))
16902 (defun org-translate-time (string)
16903 "Translate all timestamps in STRING to custom format.
16904 But do this only if the variable `org-display-custom-times' is set."
16905 (when org-display-custom-times
16906 (save-match-data
16907 (let* ((start 0)
16908 (re org-ts-regexp-both)
16909 t1 with-hm inactive tf time str beg end)
16910 (while (setq start (string-match re string start))
16911 (setq beg (match-beginning 0)
16912 end (match-end 0)
16913 t1 (save-match-data
16914 (org-parse-time-string (substring string beg end) t))
16915 with-hm (and (nth 1 t1) (nth 2 t1))
16916 inactive (equal (substring string beg (1+ beg)) "[")
16917 tf (funcall (if with-hm 'cdr 'car)
16918 org-time-stamp-custom-formats)
16919 time (org-fix-decoded-time t1)
16920 str (format-time-string
16921 (concat
16922 (if inactive "[" "<") (substring tf 1 -1)
16923 (if inactive "]" ">"))
16924 (apply 'encode-time time))
16925 string (replace-match str t t string)
16926 start (+ start (length str)))))))
16927 string)
16929 (defun org-fix-decoded-time (time)
16930 "Set 0 instead of nil for the first 6 elements of time.
16931 Don't touch the rest."
16932 (let ((n 0))
16933 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16935 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16937 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16938 "Difference between TIMESTAMP-STRING and now in days.
16939 If SECONDS is non-nil, return the difference in seconds."
16940 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16941 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16942 (funcall fdiff (current-time)))))
16944 (defun org-deadline-close (timestamp-string &optional ndays)
16945 "Is the time in TIMESTAMP-STRING close to the current date?"
16946 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16947 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16948 (not (org-entry-is-done-p))))
16950 (defun org-get-wdays (ts &optional delay zero-delay)
16951 "Get the deadline lead time appropriate for timestring TS.
16952 When DELAY is non-nil, get the delay time for scheduled items
16953 instead of the deadline lead time. When ZERO-DELAY is non-nil
16954 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16955 don't try to find the delay cookie in the scheduled timestamp."
16956 (let ((tv (if delay org-scheduled-delay-days
16957 org-deadline-warning-days)))
16958 (cond
16959 ((or (and delay (< tv 0))
16960 (and delay zero-delay (<= tv 0))
16961 (and (not delay) (<= tv 0)))
16962 ;; Enforce this value no matter what
16963 (- tv))
16964 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16965 ;; lead time is specified.
16966 (floor (* (string-to-number (match-string 1 ts))
16967 (cdr (assoc (match-string 2 ts)
16968 '(("d" . 1) ("w" . 7)
16969 ("m" . 30.4) ("y" . 365.25)
16970 ("h" . 0.041667)))))))
16971 ;; go for the default.
16972 (t tv))))
16974 (defun org-calendar-select-mouse (ev)
16975 "Return to `org-read-date' with the date currently selected.
16976 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16977 (interactive "e")
16978 (mouse-set-point ev)
16979 (when (calendar-cursor-to-date)
16980 (let* ((date (calendar-cursor-to-date))
16981 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16982 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16983 (if (active-minibuffer-window) (exit-minibuffer))))
16985 (defun org-check-deadlines (ndays)
16986 "Check if there are any deadlines due or past due.
16987 A deadline is considered due if it happens within `org-deadline-warning-days'
16988 days from today's date. If the deadline appears in an entry marked DONE,
16989 it is not shown. The prefix arg NDAYS can be used to test that many
16990 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16991 (interactive "P")
16992 (let* ((org-warn-days
16993 (cond
16994 ((equal ndays '(4)) 100000)
16995 (ndays (prefix-numeric-value ndays))
16996 (t (abs org-deadline-warning-days))))
16997 (case-fold-search nil)
16998 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16999 (callback
17000 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
17002 (message "%d deadlines past-due or due within %d days"
17003 (org-occur regexp nil callback)
17004 org-warn-days)))
17006 (defsubst org-re-timestamp (type)
17007 "Return a regexp for timestamp TYPE.
17008 Allowed values for TYPE are:
17010 all: all timestamps
17011 active: only active timestamps (<...>)
17012 inactive: only inactive timestamps ([...])
17013 scheduled: only scheduled timestamps
17014 deadline: only deadline timestamps
17015 closed: only closed time-stamps
17017 When TYPE is nil, fall back on returning a regexp that matches
17018 both scheduled and deadline timestamps."
17019 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
17020 ((eq type 'active) org-ts-regexp)
17021 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
17022 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
17023 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17024 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
17025 ((eq type 'scheduled-or-deadline)
17026 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
17028 (defun org-check-before-date (date)
17029 "Check if there are deadlines or scheduled entries before DATE."
17030 (interactive (list (org-read-date)))
17031 (let ((case-fold-search nil)
17032 (regexp (org-re-timestamp org-ts-type))
17033 (callback
17034 (lambda () (time-less-p
17035 (org-time-string-to-time (match-string 1))
17036 (org-time-string-to-time date)))))
17037 (message "%d entries before %s"
17038 (org-occur regexp nil callback) date)))
17040 (defun org-check-after-date (date)
17041 "Check if there are deadlines or scheduled entries after DATE."
17042 (interactive (list (org-read-date)))
17043 (let ((case-fold-search nil)
17044 (regexp (org-re-timestamp org-ts-type))
17045 (callback
17046 (lambda () (not
17047 (time-less-p
17048 (org-time-string-to-time (match-string 1))
17049 (org-time-string-to-time date))))))
17050 (message "%d entries after %s"
17051 (org-occur regexp nil callback) date)))
17053 (defun org-check-dates-range (start-date end-date)
17054 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17055 (interactive (list (org-read-date nil nil nil "Range starts")
17056 (org-read-date nil nil nil "Range end")))
17057 (let ((case-fold-search nil)
17058 (regexp (org-re-timestamp org-ts-type))
17059 (callback
17060 (lambda ()
17061 (let ((match (match-string 1)))
17062 (and
17063 (not (time-less-p
17064 (org-time-string-to-time match)
17065 (org-time-string-to-time start-date)))
17066 (time-less-p
17067 (org-time-string-to-time match)
17068 (org-time-string-to-time end-date)))))))
17069 (message "%d entries between %s and %s"
17070 (org-occur regexp nil callback) start-date end-date)))
17072 (defun org-evaluate-time-range (&optional to-buffer)
17073 "Evaluate a time range by computing the difference between start and end.
17074 Normally the result is just printed in the echo area, but with prefix arg
17075 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17076 If the time range is actually in a table, the result is inserted into the
17077 next column.
17078 For time difference computation, a year is assumed to be exactly 365
17079 days in order to avoid rounding problems."
17080 (interactive "P")
17082 (org-clock-update-time-maybe)
17083 (save-excursion
17084 (unless (org-at-date-range-p t)
17085 (goto-char (point-at-bol))
17086 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17087 (if (not (org-at-date-range-p t))
17088 (user-error "Not at a time-stamp range, and none found in current line")))
17089 (let* ((ts1 (match-string 1))
17090 (ts2 (match-string 2))
17091 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17092 (match-end (match-end 0))
17093 (time1 (org-time-string-to-time ts1))
17094 (time2 (org-time-string-to-time ts2))
17095 (t1 (org-float-time time1))
17096 (t2 (org-float-time time2))
17097 (diff (abs (- t2 t1)))
17098 (negative (< (- t2 t1) 0))
17099 ;; (ys (floor (* 365 24 60 60)))
17100 (ds (* 24 60 60))
17101 (hs (* 60 60))
17102 (fy "%dy %dd %02d:%02d")
17103 (fy1 "%dy %dd")
17104 (fd "%dd %02d:%02d")
17105 (fd1 "%dd")
17106 (fh "%02d:%02d")
17107 y d h m align)
17108 (if havetime
17109 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17111 d (floor (/ diff ds)) diff (mod diff ds)
17112 h (floor (/ diff hs)) diff (mod diff hs)
17113 m (floor (/ diff 60)))
17114 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17116 d (floor (+ (/ diff ds) 0.5))
17117 h 0 m 0))
17118 (if (not to-buffer)
17119 (message "%s" (org-make-tdiff-string y d h m))
17120 (if (org-at-table-p)
17121 (progn
17122 (goto-char match-end)
17123 (setq align t)
17124 (and (looking-at " *|") (goto-char (match-end 0))))
17125 (goto-char match-end))
17126 (if (looking-at
17127 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17128 (replace-match ""))
17129 (if negative (insert " -"))
17130 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17131 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17132 (insert " " (format fh h m))))
17133 (if align (org-table-align))
17134 (message "Time difference inserted")))))
17136 (defun org-make-tdiff-string (y d h m)
17137 (let ((fmt "")
17138 (l nil))
17139 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
17140 l (push y l)))
17141 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
17142 l (push d l)))
17143 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
17144 l (push h l)))
17145 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
17146 l (push m l)))
17147 (apply 'format fmt (nreverse l))))
17149 (defun org-time-string-to-time (s &optional buffer pos)
17150 "Convert a timestamp string into internal time."
17151 (condition-case errdata
17152 (apply 'encode-time (org-parse-time-string s))
17153 (error (error "Bad timestamp `%s'%s\nError was: %s"
17154 s (if (not (and buffer pos))
17156 (format " at %d in buffer `%s'" pos buffer))
17157 (cdr errdata)))))
17159 (defun org-time-string-to-seconds (s)
17160 "Convert a timestamp string to a number of seconds."
17161 (org-float-time (org-time-string-to-time s)))
17163 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17164 "Convert a time stamp to an absolute day number.
17165 If there is a specifier for a cyclic time stamp, get the closest
17166 date to DAYNR.
17167 PREFER and SHOW-ALL are passed through to `org-closest-date'.
17168 The variable `date' is bound by the calendar when this is called."
17169 (cond
17170 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17171 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17172 daynr
17173 (+ daynr 1000)))
17174 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
17175 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17176 (time-to-days (current-time))) (match-string 0 s)
17177 prefer show-all))
17178 (t (time-to-days
17179 (condition-case errdata
17180 (apply 'encode-time (org-parse-time-string s))
17181 (error (error "Bad timestamp `%s'%s\nError was: %s"
17182 s (if (not (and buffer pos))
17184 (format " at %d in buffer `%s'" pos buffer))
17185 (cdr errdata))))))))
17187 (defun org-days-to-iso-week (days)
17188 "Return the iso week number."
17189 (require 'cal-iso)
17190 (car (calendar-iso-from-absolute days)))
17192 (defun org-small-year-to-year (year)
17193 "Convert 2-digit years into 4-digit years.
17194 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
17195 The year 2000 cannot be abbreviated. Any year larger than 99
17196 is returned unchanged."
17197 (if (< year 38)
17198 (setq year (+ 2000 year))
17199 (if (< year 100)
17200 (setq year (+ 1900 year))))
17201 year)
17203 (defun org-time-from-absolute (d)
17204 "Return the time corresponding to date D.
17205 D may be an absolute day number, or a calendar-type list (month day year)."
17206 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17207 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17209 (defun org-calendar-holiday ()
17210 "List of holidays, for Diary display in Org-mode."
17211 (require 'holidays)
17212 (let ((hl (funcall
17213 (if (fboundp 'calendar-check-holidays)
17214 'calendar-check-holidays 'check-calendar-holidays) date)))
17215 (if hl (mapconcat 'identity hl "; "))))
17217 (defun org-diary-sexp-entry (sexp entry date)
17218 "Process a SEXP diary ENTRY for DATE."
17219 (require 'diary-lib)
17220 (let ((result (if calendar-debug-sexp
17221 (let ((stack-trace-on-error t))
17222 (eval (car (read-from-string sexp))))
17223 (condition-case nil
17224 (eval (car (read-from-string sexp)))
17225 (error
17226 (beep)
17227 (message "Bad sexp at line %d in %s: %s"
17228 (org-current-line)
17229 (buffer-file-name) sexp)
17230 (sleep-for 2))))))
17231 (cond ((stringp result) (split-string result "; "))
17232 ((and (consp result)
17233 (not (consp (cdr result)))
17234 (stringp (cdr result))) (cdr result))
17235 ((and (consp result)
17236 (stringp (car result))) result)
17237 (result entry))))
17239 (defun org-diary-to-ical-string (frombuf)
17240 "Get iCalendar entries from diary entries in buffer FROMBUF.
17241 This uses the icalendar.el library."
17242 (let* ((tmpdir (if (featurep 'xemacs)
17243 (temp-directory)
17244 temporary-file-directory))
17245 (tmpfile (make-temp-name
17246 (expand-file-name "orgics" tmpdir)))
17247 buf rtn b e)
17248 (with-current-buffer frombuf
17249 (icalendar-export-region (point-min) (point-max) tmpfile)
17250 (setq buf (find-buffer-visiting tmpfile))
17251 (set-buffer buf)
17252 (goto-char (point-min))
17253 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17254 (setq b (match-beginning 0)))
17255 (goto-char (point-max))
17256 (if (re-search-backward "^END:VEVENT" nil t)
17257 (setq e (match-end 0)))
17258 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17259 (kill-buffer buf)
17260 (delete-file tmpfile)
17261 rtn))
17263 (defun org-closest-date (start current change prefer show-all)
17264 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17265 When PREFER is `past', return a date that is either CURRENT or past.
17266 When PREFER is `future', return a date that is either CURRENT or future.
17267 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17268 ;; Make the proper lists from the dates
17269 (catch 'exit
17270 (let ((a1 '(("h" . hour)
17271 ("d" . day)
17272 ("w" . week)
17273 ("m" . month)
17274 ("y" . year)))
17275 (shour (nth 2 (org-parse-time-string start)))
17276 dn dw sday cday n1 n2 n0
17277 d m y y1 y2 date1 date2 nmonths nm ny m2)
17279 (setq start (org-date-to-gregorian start)
17280 current (org-date-to-gregorian
17281 (if show-all
17282 current
17283 (time-to-days (current-time))))
17284 sday (calendar-absolute-from-gregorian start)
17285 cday (calendar-absolute-from-gregorian current))
17287 (if (<= cday sday) (throw 'exit sday))
17289 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17290 (setq dn (string-to-number (match-string 1 change))
17291 dw (cdr (assoc (match-string 2 change) a1)))
17292 (user-error "Invalid change specifier: %s" change))
17293 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17294 (cond
17295 ((eq dw 'hour)
17296 (let ((missing-hours
17297 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17298 dn)))
17299 (setq n1 (if (zerop missing-hours) cday
17300 (- cday (1+ (floor (/ missing-hours 24)))))
17301 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17302 ((eq dw 'day)
17303 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17304 n2 (+ n1 dn)))
17305 ((eq dw 'year)
17306 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17307 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17308 (setq date1 (list m d y1)
17309 n1 (calendar-absolute-from-gregorian date1)
17310 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17311 n2 (calendar-absolute-from-gregorian date2)))
17312 ((eq dw 'month)
17313 ;; approx number of month between the two dates
17314 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17315 ;; How often does dn fit in there?
17316 (setq d (nth 1 start) m (car start) y (nth 2 start)
17317 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17318 m (+ m nm)
17319 ny (floor (/ m 12))
17320 y (+ y ny)
17321 m (- m (* ny 12)))
17322 (while (> m 12) (setq m (- m 12) y (1+ y)))
17323 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17324 (setq m2 (+ m dn) y2 y)
17325 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17326 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17327 (while (<= n2 cday)
17328 (setq n1 n2 m m2 y y2)
17329 (setq m2 (+ m dn) y2 y)
17330 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17331 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17332 ;; Make sure n1 is the earlier date
17333 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17334 (if show-all
17335 (cond
17336 ((eq prefer 'past) (if (= cday n2) n2 n1))
17337 ((eq prefer 'future) (if (= cday n1) n1 n2))
17338 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17339 (cond
17340 ((eq prefer 'past) (if (= cday n2) n2 n1))
17341 ((eq prefer 'future) (if (= cday n1) n1 n2))
17342 (t (if (= cday n1) n1 n2)))))))
17344 (defun org-date-to-gregorian (date)
17345 "Turn any specification of DATE into a Gregorian date for the calendar."
17346 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17347 ((and (listp date) (= (length date) 3)) date)
17348 ((stringp date)
17349 (setq date (org-parse-time-string date))
17350 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17351 ((listp date)
17352 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17354 (defun org-parse-time-string (s &optional nodefault)
17355 "Parse the standard Org-mode time string.
17356 This should be a lot faster than the normal `parse-time-string'.
17357 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17358 hour and minute fields will be nil if not given."
17359 (cond ((string-match org-ts-regexp0 s)
17360 (list 0
17361 (if (or (match-beginning 8) (not nodefault))
17362 (string-to-number (or (match-string 8 s) "0")))
17363 (if (or (match-beginning 7) (not nodefault))
17364 (string-to-number (or (match-string 7 s) "0")))
17365 (string-to-number (match-string 4 s))
17366 (string-to-number (match-string 3 s))
17367 (string-to-number (match-string 2 s))
17368 nil nil nil))
17369 ((string-match "^<[^>]+>$" s)
17370 (decode-time (seconds-to-time (org-matcher-time s))))
17371 (t (error "Not a standard Org-mode time string: %s" s))))
17373 (defun org-timestamp-up (&optional arg)
17374 "Increase the date item at the cursor by one.
17375 If the cursor is on the year, change the year. If it is on the month,
17376 the day or the time, change that.
17377 With prefix ARG, change by that many units."
17378 (interactive "p")
17379 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17381 (defun org-timestamp-down (&optional arg)
17382 "Decrease the date item at the cursor by one.
17383 If the cursor is on the year, change the year. If it is on the month,
17384 the day or the time, change that.
17385 With prefix ARG, change by that many units."
17386 (interactive "p")
17387 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17389 (defun org-timestamp-up-day (&optional arg)
17390 "Increase the date in the time stamp by one day.
17391 With prefix ARG, change that many days."
17392 (interactive "p")
17393 (if (and (not (org-at-timestamp-p t))
17394 (org-at-heading-p))
17395 (org-todo 'up)
17396 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17398 (defun org-timestamp-down-day (&optional arg)
17399 "Decrease the date in the time stamp by one day.
17400 With prefix ARG, change that many days."
17401 (interactive "p")
17402 (if (and (not (org-at-timestamp-p t))
17403 (org-at-heading-p))
17404 (org-todo 'down)
17405 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17407 (defun org-at-timestamp-p (&optional inactive-ok)
17408 "Determine if the cursor is in or at a timestamp."
17409 (interactive)
17410 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17411 (pos (point))
17412 (ans (or (looking-at tsr)
17413 (save-excursion
17414 (skip-chars-backward "^[<\n\r\t")
17415 (if (> (point) (point-min)) (backward-char 1))
17416 (and (looking-at tsr)
17417 (> (- (match-end 0) pos) -1))))))
17418 (and ans
17419 (boundp 'org-ts-what)
17420 (setq org-ts-what
17421 (cond
17422 ((= pos (match-beginning 0)) 'bracket)
17423 ;; Point is considered to be "on the bracket" whether
17424 ;; it's really on it or right after it.
17425 ((= pos (1- (match-end 0))) 'bracket)
17426 ((= pos (match-end 0)) 'after)
17427 ((org-pos-in-match-range pos 2) 'year)
17428 ((org-pos-in-match-range pos 3) 'month)
17429 ((org-pos-in-match-range pos 7) 'hour)
17430 ((org-pos-in-match-range pos 8) 'minute)
17431 ((or (org-pos-in-match-range pos 4)
17432 (org-pos-in-match-range pos 5)) 'day)
17433 ((and (> pos (or (match-end 8) (match-end 5)))
17434 (< pos (match-end 0)))
17435 (- pos (or (match-end 8) (match-end 5))))
17436 (t 'day))))
17437 ans))
17439 (defun org-toggle-timestamp-type ()
17440 "Toggle the type (<active> or [inactive]) of a time stamp."
17441 (interactive)
17442 (when (org-at-timestamp-p t)
17443 (let ((beg (match-beginning 0)) (end (match-end 0))
17444 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17445 (save-excursion
17446 (goto-char beg)
17447 (while (re-search-forward "[][<>]" end t)
17448 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17449 t t)))
17450 (message "Timestamp is now %sactive"
17451 (if (equal (char-after beg) ?<) "" "in")))))
17453 (defun org-at-clock-log-p nil
17454 "Is the cursor on the clock log line?"
17455 (save-excursion
17456 (move-beginning-of-line 1)
17457 (looking-at "^[ \t]*CLOCK:")))
17459 (defvar org-clock-history) ; defined in org-clock.el
17460 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17461 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17462 "Change the date in the time stamp at point.
17463 The date will be changed by N times WHAT. WHAT can be `day', `month',
17464 `year', `minute', `second'. If WHAT is not given, the cursor position
17465 in the timestamp determines what will be changed.
17466 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17467 (let ((origin (point)) origin-cat
17468 with-hm inactive
17469 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17470 org-ts-what
17471 extra rem
17472 ts time time0 fixnext clrgx)
17473 (if (not (org-at-timestamp-p t))
17474 (user-error "Not at a timestamp"))
17475 (if (and (not what) (eq org-ts-what 'bracket))
17476 (org-toggle-timestamp-type)
17477 ;; Point isn't on brackets. Remember the part of the time-stamp
17478 ;; the point was in. Indeed, size of time-stamps may change,
17479 ;; but point must be kept in the same category nonetheless.
17480 (setq origin-cat org-ts-what)
17481 (if (and (not what) (not (eq org-ts-what 'day))
17482 org-display-custom-times
17483 (get-text-property (point) 'display)
17484 (not (get-text-property (1- (point)) 'display)))
17485 (setq org-ts-what 'day))
17486 (setq org-ts-what (or what org-ts-what)
17487 inactive (= (char-after (match-beginning 0)) ?\[)
17488 ts (match-string 0))
17489 (replace-match "")
17490 (when (string-match
17491 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17493 (setq extra (match-string 1 ts))
17494 (if suppress-tmp-delay
17495 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17496 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17497 (setq with-hm t))
17498 (setq time0 (org-parse-time-string ts))
17499 (when (and updown
17500 (eq org-ts-what 'minute)
17501 (not current-prefix-arg))
17502 ;; This looks like s-up and s-down. Change by one rounding step.
17503 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17504 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17505 (setcar (cdr time0) (+ (nth 1 time0)
17506 (if (> n 0) (- rem) (- dm rem))))))
17507 (setq time
17508 (encode-time (or (car time0) 0)
17509 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17510 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17511 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17512 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17513 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17514 (nthcdr 6 time0)))
17515 (when (and (member org-ts-what '(hour minute))
17516 extra
17517 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17518 (setq extra (org-modify-ts-extra
17519 extra
17520 (if (eq org-ts-what 'hour) 2 5)
17521 n dm)))
17522 (when (integerp org-ts-what)
17523 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17524 (if (eq what 'calendar)
17525 (let ((cal-date (org-get-date-from-calendar)))
17526 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17527 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17528 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17529 (setcar time0 (or (car time0) 0))
17530 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17531 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17532 (setq time (apply 'encode-time time0))))
17533 ;; Insert the new time-stamp, and ensure point stays in the same
17534 ;; category as before (i.e. not after the last position in that
17535 ;; category).
17536 (let ((pos (point)))
17537 ;; Stay before inserted string. `save-excursion' is of no use.
17538 (setq org-last-changed-timestamp
17539 (org-insert-time-stamp time with-hm inactive nil nil extra))
17540 (goto-char pos))
17541 (save-match-data
17542 (looking-at org-ts-regexp3)
17543 (goto-char (cond
17544 ;; `day' category ends before `hour' if any, or at
17545 ;; the end of the day name.
17546 ((eq origin-cat 'day)
17547 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17548 ((eq origin-cat 'hour) (min (match-end 7) origin))
17549 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17550 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17551 ;; `year' and `month' have both fixed size: point
17552 ;; couldn't have moved into another part.
17553 (t origin))))
17554 ;; Update clock if on a CLOCK line.
17555 (org-clock-update-time-maybe)
17556 ;; Maybe adjust the closest clock in `org-clock-history'
17557 (when org-clock-adjust-closest
17558 (if (not (and (org-at-clock-log-p)
17559 (< 1 (length (delq nil (mapcar 'marker-position
17560 org-clock-history))))))
17561 (message "No clock to adjust")
17562 (cond ((save-excursion ; fix previous clock?
17563 (re-search-backward org-ts-regexp0 nil t)
17564 (org-looking-back (concat org-clock-string " \\[")))
17565 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17566 ((save-excursion ; fix next clock?
17567 (re-search-backward org-ts-regexp0 nil t)
17568 (looking-at (concat org-ts-regexp0 "\\] =>")))
17569 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17570 (save-window-excursion
17571 ;; Find closest clock to point, adjust the previous/next one in history
17572 (let* ((p (save-excursion (org-back-to-heading t)))
17573 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17574 (clfixnth
17575 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17576 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17577 (if (not clfixpos)
17578 (message "No clock to adjust")
17579 (save-excursion
17580 (org-goto-marker-or-bmk clfixpos)
17581 (org-show-subtree)
17582 (when (re-search-forward clrgx nil t)
17583 (goto-char (match-beginning 1))
17584 (let (org-clock-adjust-closest)
17585 (org-timestamp-change n org-ts-what updown))
17586 (message "Clock adjusted in %s for heading: %s"
17587 (file-name-nondirectory (buffer-file-name))
17588 (org-get-heading t t)))))))))
17589 ;; Try to recenter the calendar window, if any.
17590 (if (and org-calendar-follow-timestamp-change
17591 (get-buffer-window "*Calendar*" t)
17592 (memq org-ts-what '(day month year)))
17593 (org-recenter-calendar (time-to-days time))))))
17595 (defun org-modify-ts-extra (s pos n dm)
17596 "Change the different parts of the lead-time and repeat fields in timestamp."
17597 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17598 ng h m new rem)
17599 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17600 (cond
17601 ((or (org-pos-in-match-range pos 2)
17602 (org-pos-in-match-range pos 3))
17603 (setq m (string-to-number (match-string 3 s))
17604 h (string-to-number (match-string 2 s)))
17605 (if (org-pos-in-match-range pos 2)
17606 (setq h (+ h n))
17607 (setq n (* dm (org-no-warnings (signum n))))
17608 (when (not (= 0 (setq rem (% m dm))))
17609 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17610 (setq m (+ m n)))
17611 (if (< m 0) (setq m (+ m 60) h (1- h)))
17612 (if (> m 59) (setq m (- m 60) h (1+ h)))
17613 (setq h (min 24 (max 0 h)))
17614 (setq ng 1 new (format "-%02d:%02d" h m)))
17615 ((org-pos-in-match-range pos 6)
17616 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17617 ((org-pos-in-match-range pos 5)
17618 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17620 ((org-pos-in-match-range pos 9)
17621 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17622 ((org-pos-in-match-range pos 8)
17623 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17625 (when ng
17626 (setq s (concat
17627 (substring s 0 (match-beginning ng))
17629 (substring s (match-end ng))))))
17632 (defun org-recenter-calendar (date)
17633 "If the calendar is visible, recenter it to DATE."
17634 (let ((cwin (get-buffer-window "*Calendar*" t)))
17635 (when cwin
17636 (let ((calendar-move-hook nil))
17637 (with-selected-window cwin
17638 (calendar-goto-date (if (listp date) date
17639 (calendar-gregorian-from-absolute date))))))))
17641 (defun org-goto-calendar (&optional arg)
17642 "Go to the Emacs calendar at the current date.
17643 If there is a time stamp in the current line, go to that date.
17644 A prefix ARG can be used to force the current date."
17645 (interactive "P")
17646 (let ((tsr org-ts-regexp) diff
17647 (calendar-move-hook nil)
17648 (calendar-view-holidays-initially-flag nil)
17649 (calendar-view-diary-initially-flag nil))
17650 (if (or (org-at-timestamp-p)
17651 (save-excursion
17652 (beginning-of-line 1)
17653 (looking-at (concat ".*" tsr))))
17654 (let ((d1 (time-to-days (current-time)))
17655 (d2 (time-to-days
17656 (org-time-string-to-time (match-string 1)))))
17657 (setq diff (- d2 d1))))
17658 (calendar)
17659 (calendar-goto-today)
17660 (if (and diff (not arg)) (calendar-forward-day diff))))
17662 (defun org-get-date-from-calendar ()
17663 "Return a list (month day year) of date at point in calendar."
17664 (with-current-buffer "*Calendar*"
17665 (save-match-data
17666 (calendar-cursor-to-date))))
17668 (defun org-date-from-calendar ()
17669 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17670 If there is already a time stamp at the cursor position, update it."
17671 (interactive)
17672 (if (org-at-timestamp-p t)
17673 (org-timestamp-change 0 'calendar)
17674 (let ((cal-date (org-get-date-from-calendar)))
17675 (org-insert-time-stamp
17676 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17678 (defcustom org-effort-durations
17679 `(("h" . 60)
17680 ("d" . ,(* 60 8))
17681 ("w" . ,(* 60 8 5))
17682 ("m" . ,(* 60 8 5 4))
17683 ("y" . ,(* 60 8 5 40)))
17684 "Conversion factor to minutes for an effort modifier.
17686 Each entry has the form (MODIFIER . MINUTES).
17688 In an effort string, a number followed by MODIFIER is multiplied
17689 by the specified number of MINUTES to obtain an effort in
17690 minutes.
17692 For example, if the value of this variable is ((\"hours\" . 60)), then an
17693 effort string \"2hours\" is equivalent to 120 minutes."
17694 :group 'org-agenda
17695 :version "24.1"
17696 :type '(alist :key-type (string :tag "Modifier")
17697 :value-type (number :tag "Minutes")))
17699 (defun org-minutes-to-clocksum-string (m)
17700 "Format number of minutes as a clocksum string.
17701 The format is determined by `org-time-clocksum-format',
17702 `org-time-clocksum-use-fractional' and
17703 `org-time-clocksum-fractional-format' and
17704 `org-time-clocksum-use-effort-durations'."
17705 (let ((clocksum "")
17706 (m (round m)) ; Don't allow fractions of minutes
17707 h d w mo y fmt n)
17708 (setq h (if org-time-clocksum-use-effort-durations
17709 (cdr (assoc "h" org-effort-durations)) 60)
17710 d (if org-time-clocksum-use-effort-durations
17711 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17712 w (if org-time-clocksum-use-effort-durations
17713 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17714 mo (if org-time-clocksum-use-effort-durations
17715 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17716 y (if org-time-clocksum-use-effort-durations
17717 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17718 ;; fractional format
17719 (if org-time-clocksum-use-fractional
17720 (cond
17721 ;; single format string
17722 ((stringp org-time-clocksum-fractional-format)
17723 (format org-time-clocksum-fractional-format (/ m (float h))))
17724 ;; choice of fractional formats for different time units
17725 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17726 (> (/ (truncate m) (* y d h)) 0))
17727 (format fmt (/ m (* y d (float h)))))
17728 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17729 (> (/ (truncate m) (* mo d h)) 0))
17730 (format fmt (/ m (* mo d (float h)))))
17731 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17732 (> (/ (truncate m) (* w d h)) 0))
17733 (format fmt (/ m (* w d (float h)))))
17734 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17735 (> (/ (truncate m) (* d h)) 0))
17736 (format fmt (/ m (* d (float h)))))
17737 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17738 (> (/ (truncate m) h) 0))
17739 (format fmt (/ m (float h))))
17740 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17741 (format fmt m))
17742 ;; fall back to smallest time unit with a format
17743 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17744 (format fmt (/ m (float h))))
17745 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17746 (format fmt (/ m (* d (float h)))))
17747 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17748 (format fmt (/ m (* w d (float h)))))
17749 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17750 (format fmt (/ m (* mo d (float h)))))
17751 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17752 (format fmt (/ m (* y d (float h))))))
17753 ;; standard (non-fractional) format, with single format string
17754 (if (stringp org-time-clocksum-format)
17755 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17756 ;; separate formats components
17757 (and (setq fmt (plist-get org-time-clocksum-format :years))
17758 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17759 (plist-get org-time-clocksum-format :require-years))
17760 (setq clocksum (concat clocksum (format fmt n))
17761 m (- m (* n y d h))))
17762 (and (setq fmt (plist-get org-time-clocksum-format :months))
17763 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17764 (plist-get org-time-clocksum-format :require-months))
17765 (setq clocksum (concat clocksum (format fmt n))
17766 m (- m (* n mo d h))))
17767 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17768 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17769 (plist-get org-time-clocksum-format :require-weeks))
17770 (setq clocksum (concat clocksum (format fmt n))
17771 m (- m (* n w d h))))
17772 (and (setq fmt (plist-get org-time-clocksum-format :days))
17773 (or (> (setq n (/ (truncate m) (* d h))) 0)
17774 (plist-get org-time-clocksum-format :require-days))
17775 (setq clocksum (concat clocksum (format fmt n))
17776 m (- m (* n d h))))
17777 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17778 (or (> (setq n (/ (truncate m) h)) 0)
17779 (plist-get org-time-clocksum-format :require-hours))
17780 (setq clocksum (concat clocksum (format fmt n))
17781 m (- m (* n h))))
17782 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17783 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17784 (setq clocksum (concat clocksum (format fmt m))))
17785 ;; return formatted time duration
17786 clocksum))))
17788 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17789 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17790 "Org mode version 8.0")
17792 (defun org-hours-to-clocksum-string (n)
17793 (org-minutes-to-clocksum-string (* n 60)))
17795 (defun org-hh:mm-string-to-minutes (s)
17796 "Convert a string H:MM to a number of minutes.
17797 If the string is just a number, interpret it as minutes.
17798 In fact, the first hh:mm or number in the string will be taken,
17799 there can be extra stuff in the string.
17800 If no number is found, the return value is 0."
17801 (cond
17802 ((integerp s) s)
17803 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17804 (+ (* (string-to-number (match-string 1 s)) 60)
17805 (string-to-number (match-string 2 s))))
17806 ((string-match "\\([0-9]+\\)" s)
17807 (string-to-number (match-string 1 s)))
17808 (t 0)))
17810 (defcustom org-image-actual-width t
17811 "Should we use the actual width of images when inlining them?
17813 When set to `t', always use the image width.
17815 When set to a number, use imagemagick (when available) to set
17816 the image's width to this value.
17818 When set to a number in a list, try to get the width from any
17819 #+ATTR.* keyword if it matches a width specification like
17821 #+ATTR_HTML: :width 300px
17823 and fall back on that number if none is found.
17825 When set to nil, try to get the width from an #+ATTR.* keyword
17826 and fall back on the original width if none is found.
17828 This requires Emacs >= 24.1, build with imagemagick support."
17829 :group 'org-appearance
17830 :version "24.4"
17831 :package-version '(Org . "8.0")
17832 :type '(choice
17833 (const :tag "Use the image width" t)
17834 (integer :tag "Use a number of pixels")
17835 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17836 (const :tag "Use #+ATTR* or don't resize" nil)))
17838 (defcustom org-agenda-inhibit-startup nil
17839 "Inhibit startup when preparing agenda buffers.
17840 When this variable is `t' (the default), the initialization of
17841 the Org agenda buffers is inhibited: e.g. the visibility state
17842 is not set, the tables are not re-aligned, etc."
17843 :type 'boolean
17844 :version "24.3"
17845 :group 'org-agenda)
17847 (defcustom org-agenda-ignore-drawer-properties nil
17848 "Avoid updating text properties when building the agenda.
17849 Properties are used to prepare buffers for effort estimates, appointments,
17850 and subtree-local categories.
17851 If you don't use these in the agenda, you can add them to this list and
17852 agenda building will be a bit faster.
17853 The value is a list, with zero or more of the symbols `effort', `appt',
17854 or `category'."
17855 :type '(set :greedy t
17856 (const effort)
17857 (const appt)
17858 (const category))
17859 :version "24.3"
17860 :group 'org-agenda)
17862 (defun org-duration-string-to-minutes (s &optional output-to-string)
17863 "Convert a duration string S to minutes.
17865 A bare number is interpreted as minutes, modifiers can be set by
17866 customizing `org-effort-durations' (which see).
17868 Entries containing a colon are interpreted as H:MM by
17869 `org-hh:mm-string-to-minutes'."
17870 (let ((result 0)
17871 (re (concat "\\([0-9.]+\\) *\\("
17872 (regexp-opt (mapcar 'car org-effort-durations))
17873 "\\)")))
17874 (while (string-match re s)
17875 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17876 (string-to-number (match-string 1 s))))
17877 (setq s (replace-match "" nil t s)))
17878 (setq result (floor result))
17879 (incf result (org-hh:mm-string-to-minutes s))
17880 (if output-to-string (number-to-string result) result)))
17882 ;;;; Files
17884 (defun org-save-all-org-buffers ()
17885 "Save all Org-mode buffers without user confirmation."
17886 (interactive)
17887 (message "Saving all Org-mode buffers...")
17888 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17889 (when (featurep 'org-id) (org-id-locations-save))
17890 (message "Saving all Org-mode buffers... done"))
17892 (defun org-revert-all-org-buffers ()
17893 "Revert all Org-mode buffers.
17894 Prompt for confirmation when there are unsaved changes.
17895 Be sure you know what you are doing before letting this function
17896 overwrite your changes.
17898 This function is useful in a setup where one tracks org files
17899 with a version control system, to revert on one machine after pulling
17900 changes from another. I believe the procedure must be like this:
17902 1. M-x org-save-all-org-buffers
17903 2. Pull changes from the other machine, resolve conflicts
17904 3. M-x org-revert-all-org-buffers"
17905 (interactive)
17906 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17907 (user-error "Abort"))
17908 (save-excursion
17909 (save-window-excursion
17910 (mapc
17911 (lambda (b)
17912 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17913 (with-current-buffer b buffer-file-name))
17914 (org-pop-to-buffer-same-window b)
17915 (revert-buffer t 'no-confirm)))
17916 (buffer-list))
17917 (when (and (featurep 'org-id) org-id-track-globally)
17918 (org-id-locations-load)))))
17920 ;;;; Agenda files
17922 ;;;###autoload
17923 (defun org-switchb (&optional arg)
17924 "Switch between Org buffers.
17925 With one prefix argument, restrict available buffers to files.
17926 With two prefix arguments, restrict available buffers to agenda files.
17928 Defaults to `iswitchb' for buffer name completion.
17929 Set `org-completion-use-ido' to make it use ido instead."
17930 (interactive "P")
17931 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17932 ((equal arg '(16)) (org-buffer-list 'agenda))
17933 (t (org-buffer-list))))
17934 (org-completion-use-iswitchb org-completion-use-iswitchb)
17935 (org-completion-use-ido org-completion-use-ido))
17936 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17937 (setq org-completion-use-iswitchb t))
17938 (org-pop-to-buffer-same-window
17939 (org-icompleting-read "Org buffer: "
17940 (mapcar 'list (mapcar 'buffer-name blist))
17941 nil t))))
17943 ;;; Define some older names previously used for this functionality
17944 ;;;###autoload
17945 (defalias 'org-ido-switchb 'org-switchb)
17946 ;;;###autoload
17947 (defalias 'org-iswitchb 'org-switchb)
17949 (defun org-buffer-list (&optional predicate exclude-tmp)
17950 "Return a list of Org buffers.
17951 PREDICATE can be `export', `files' or `agenda'.
17953 export restrict the list to Export buffers.
17954 files restrict the list to buffers visiting Org files.
17955 agenda restrict the list to buffers visiting agenda files.
17957 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17958 (let* ((bfn nil)
17959 (agenda-files (and (eq predicate 'agenda)
17960 (mapcar 'file-truename (org-agenda-files t))))
17961 (filter
17962 (cond
17963 ((eq predicate 'files)
17964 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17965 ((eq predicate 'export)
17966 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17967 ((eq predicate 'agenda)
17968 (lambda (b)
17969 (with-current-buffer b
17970 (and (derived-mode-p 'org-mode)
17971 (setq bfn (buffer-file-name b))
17972 (member (file-truename bfn) agenda-files)))))
17973 (t (lambda (b) (with-current-buffer b
17974 (or (derived-mode-p 'org-mode)
17975 (string-match "\*Org .*Export"
17976 (buffer-name b)))))))))
17977 (delq nil
17978 (mapcar
17979 (lambda(b)
17980 (if (and (funcall filter b)
17981 (or (not exclude-tmp)
17982 (not (string-match "tmp" (buffer-name b)))))
17984 nil))
17985 (buffer-list)))))
17987 (defun org-agenda-files (&optional unrestricted archives)
17988 "Get the list of agenda files.
17989 Optional UNRESTRICTED means return the full list even if a restriction
17990 is currently in place.
17991 When ARCHIVES is t, include all archive files that are really being
17992 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17993 `org-agenda-archives-mode' is t."
17994 (let ((files
17995 (cond
17996 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17997 ((stringp org-agenda-files) (org-read-agenda-file-list))
17998 ((listp org-agenda-files) org-agenda-files)
17999 (t (error "Invalid value of `org-agenda-files'")))))
18000 (setq files (apply 'append
18001 (mapcar (lambda (f)
18002 (if (file-directory-p f)
18003 (directory-files
18004 f t org-agenda-file-regexp)
18005 (list f)))
18006 files)))
18007 (when org-agenda-skip-unavailable-files
18008 (setq files (delq nil
18009 (mapcar (function
18010 (lambda (file)
18011 (and (file-readable-p file) file)))
18012 files))))
18013 (when (or (eq archives t)
18014 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18015 (setq files (org-add-archive-files files)))
18016 files))
18018 (defun org-agenda-file-p (&optional file)
18019 "Return non-nil, if FILE is an agenda file.
18020 If FILE is omitted, use the file associated with the current
18021 buffer."
18022 (member (or file (buffer-file-name))
18023 (org-agenda-files t)))
18025 (defun org-edit-agenda-file-list ()
18026 "Edit the list of agenda files.
18027 Depending on setup, this either uses customize to edit the variable
18028 `org-agenda-files', or it visits the file that is holding the list. In the
18029 latter case, the buffer is set up in a way that saving it automatically kills
18030 the buffer and restores the previous window configuration."
18031 (interactive)
18032 (if (stringp org-agenda-files)
18033 (let ((cw (current-window-configuration)))
18034 (find-file org-agenda-files)
18035 (org-set-local 'org-window-configuration cw)
18036 (org-add-hook 'after-save-hook
18037 (lambda ()
18038 (set-window-configuration
18039 (prog1 org-window-configuration
18040 (kill-buffer (current-buffer))))
18041 (org-install-agenda-files-menu)
18042 (message "New agenda file list installed"))
18043 nil 'local)
18044 (message "%s" (substitute-command-keys
18045 "Edit list and finish with \\[save-buffer]")))
18046 (customize-variable 'org-agenda-files)))
18048 (defun org-store-new-agenda-file-list (list)
18049 "Set new value for the agenda file list and save it correctly."
18050 (if (stringp org-agenda-files)
18051 (let ((fe (org-read-agenda-file-list t)) b u)
18052 (while (setq b (find-buffer-visiting org-agenda-files))
18053 (kill-buffer b))
18054 (with-temp-file org-agenda-files
18055 (insert
18056 (mapconcat
18057 (lambda (f) ;; Keep un-expanded entries.
18058 (if (setq u (assoc f fe))
18059 (cdr u)
18061 list "\n")
18062 "\n")))
18063 (let ((org-mode-hook nil) (org-inhibit-startup t)
18064 (org-insert-mode-line-in-empty-file nil))
18065 (setq org-agenda-files list)
18066 (customize-save-variable 'org-agenda-files org-agenda-files))))
18068 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18069 "Read the list of agenda files from a file.
18070 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18071 filenames, used by `org-store-new-agenda-file-list' to write back
18072 un-expanded file names."
18073 (when (file-directory-p org-agenda-files)
18074 (error "`org-agenda-files' cannot be a single directory"))
18075 (when (stringp org-agenda-files)
18076 (with-temp-buffer
18077 (insert-file-contents org-agenda-files)
18078 (mapcar
18079 (lambda (f)
18080 (let ((e (expand-file-name (substitute-in-file-name f)
18081 org-directory)))
18082 (if pair-with-expansion
18083 (cons e f)
18084 e)))
18085 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18087 ;;;###autoload
18088 (defun org-cycle-agenda-files ()
18089 "Cycle through the files in `org-agenda-files'.
18090 If the current buffer visits an agenda file, find the next one in the list.
18091 If the current buffer does not, find the first agenda file."
18092 (interactive)
18093 (let* ((fs (org-agenda-files t))
18094 (files (append fs (list (car fs))))
18095 (tcf (if buffer-file-name (file-truename buffer-file-name)))
18096 file)
18097 (unless files (user-error "No agenda files"))
18098 (catch 'exit
18099 (while (setq file (pop files))
18100 (if (equal (file-truename file) tcf)
18101 (when (car files)
18102 (find-file (car files))
18103 (throw 'exit t))))
18104 (find-file (car fs)))
18105 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
18107 (defun org-agenda-file-to-front (&optional to-end)
18108 "Move/add the current file to the top of the agenda file list.
18109 If the file is not present in the list, it is added to the front. If it is
18110 present, it is moved there. With optional argument TO-END, add/move to the
18111 end of the list."
18112 (interactive "P")
18113 (let ((org-agenda-skip-unavailable-files nil)
18114 (file-alist (mapcar (lambda (x)
18115 (cons (file-truename x) x))
18116 (org-agenda-files t)))
18117 (ctf (file-truename
18118 (or buffer-file-name
18119 (user-error "Please save the current buffer to a file"))))
18120 x had)
18121 (setq x (assoc ctf file-alist) had x)
18123 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18124 (if to-end
18125 (setq file-alist (append (delq x file-alist) (list x)))
18126 (setq file-alist (cons x (delq x file-alist))))
18127 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18128 (org-install-agenda-files-menu)
18129 (message "File %s to %s of agenda file list"
18130 (if had "moved" "added") (if to-end "end" "front"))))
18132 (defun org-remove-file (&optional file)
18133 "Remove current file from the list of files in variable `org-agenda-files'.
18134 These are the files which are being checked for agenda entries.
18135 Optional argument FILE means use this file instead of the current."
18136 (interactive)
18137 (let* ((org-agenda-skip-unavailable-files nil)
18138 (file (or file buffer-file-name
18139 (user-error "Current buffer does not visit a file")))
18140 (true-file (file-truename file))
18141 (afile (abbreviate-file-name file))
18142 (files (delq nil (mapcar
18143 (lambda (x)
18144 (if (equal true-file
18145 (file-truename x))
18146 nil x))
18147 (org-agenda-files t)))))
18148 (if (not (= (length files) (length (org-agenda-files t))))
18149 (progn
18150 (org-store-new-agenda-file-list files)
18151 (org-install-agenda-files-menu)
18152 (message "Removed file: %s" afile))
18153 (message "File was not in list: %s (not removed)" afile))))
18155 (defun org-file-menu-entry (file)
18156 (vector file (list 'find-file file) t))
18158 (defun org-check-agenda-file (file)
18159 "Make sure FILE exists. If not, ask user what to do."
18160 (when (not (file-exists-p file))
18161 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18162 (abbreviate-file-name file))
18163 (let ((r (downcase (read-char-exclusive))))
18164 (cond
18165 ((equal r ?r)
18166 (org-remove-file file)
18167 (throw 'nextfile t))
18168 (t (error "Abort"))))))
18170 (defun org-get-agenda-file-buffer (file)
18171 "Get a buffer visiting FILE. If the buffer needs to be created, add
18172 it to the list of buffers which might be released later."
18173 (let ((buf (org-find-base-buffer-visiting file)))
18174 (if buf
18175 buf ; just return it
18176 ;; Make a new buffer and remember it
18177 (setq buf (find-file-noselect file))
18178 (if buf (push buf org-agenda-new-buffers))
18179 buf)))
18181 (defun org-release-buffers (blist)
18182 "Release all buffers in list, asking the user for confirmation when needed.
18183 When a buffer is unmodified, it is just killed. When modified, it is saved
18184 \(if the user agrees) and then killed."
18185 (let (buf file)
18186 (while (setq buf (pop blist))
18187 (setq file (buffer-file-name buf))
18188 (when (and (buffer-modified-p buf)
18189 file
18190 (y-or-n-p (format "Save file %s? " file)))
18191 (with-current-buffer buf (save-buffer)))
18192 (kill-buffer buf))))
18194 (defun org-agenda-prepare-buffers (files)
18195 "Create buffers for all agenda files, protect archived trees and comments."
18196 (interactive)
18197 (let ((pa '(:org-archived t))
18198 (pc '(:org-comment t))
18199 (pall '(:org-archived t :org-comment t))
18200 (inhibit-read-only t)
18201 (org-inhibit-startup org-agenda-inhibit-startup)
18202 (rea (concat ":" org-archive-tag ":"))
18203 file re pos)
18204 (setq org-tag-alist-for-agenda nil
18205 org-tag-groups-alist-for-agenda nil)
18206 (save-excursion
18207 (save-restriction
18208 (while (setq file (pop files))
18209 (catch 'nextfile
18210 (if (bufferp file)
18211 (set-buffer file)
18212 (org-check-agenda-file file)
18213 (set-buffer (org-get-agenda-file-buffer file)))
18214 (widen)
18215 (org-set-regexps-and-options-for-tags)
18216 (setq pos (point))
18217 (goto-char (point-min))
18218 (let ((case-fold-search t))
18219 (when (search-forward "#+setupfile" nil t)
18220 ;; Don't set all regexps and options systematically as
18221 ;; this is only run for setting agenda tags from setup
18222 ;; file
18223 (org-set-regexps-and-options)))
18224 (or (memq 'category org-agenda-ignore-drawer-properties)
18225 (org-refresh-category-properties))
18226 (or (memq 'effort org-agenda-ignore-drawer-properties)
18227 (org-refresh-properties org-effort-property 'org-effort))
18228 (or (memq 'appt org-agenda-ignore-drawer-properties)
18229 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18230 (setq org-todo-keywords-for-agenda
18231 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18232 (setq org-done-keywords-for-agenda
18233 (append org-done-keywords-for-agenda org-done-keywords))
18234 (setq org-todo-keyword-alist-for-agenda
18235 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18236 (setq org-tag-alist-for-agenda
18237 (org-uniquify
18238 (append org-tag-alist-for-agenda
18239 org-tag-alist
18240 org-tag-persistent-alist)))
18241 (if org-group-tags
18242 (setq org-tag-groups-alist-for-agenda
18243 (org-uniquify-alist
18244 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18245 (org-with-silent-modifications
18246 (save-excursion
18247 (remove-text-properties (point-min) (point-max) pall)
18248 (when org-agenda-skip-archived-trees
18249 (goto-char (point-min))
18250 (while (re-search-forward rea nil t)
18251 (if (org-at-heading-p t)
18252 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18253 (goto-char (point-min))
18254 (setq re (format "^\\* .*\\<%s\\>" org-comment-string))
18255 (while (re-search-forward re nil t)
18256 (when (save-match-data (org-in-commented-heading-p t))
18257 (add-text-properties
18258 (match-beginning 0) (org-end-of-subtree t) pc)))))
18259 (goto-char pos)))))
18260 (setq org-todo-keywords-for-agenda
18261 (org-uniquify org-todo-keywords-for-agenda))
18262 (setq org-todo-keyword-alist-for-agenda
18263 (org-uniquify org-todo-keyword-alist-for-agenda))))
18266 ;;;; CDLaTeX minor mode
18268 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18269 "Keymap for the minor `org-cdlatex-mode'.")
18271 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18272 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18273 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18274 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18275 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
18277 (defvar org-cdlatex-texmathp-advice-is-done nil
18278 "Flag remembering if we have applied the advice to texmathp already.")
18280 (define-minor-mode org-cdlatex-mode
18281 "Toggle the minor `org-cdlatex-mode'.
18282 This mode supports entering LaTeX environment and math in LaTeX fragments
18283 in Org-mode.
18284 \\{org-cdlatex-mode-map}"
18285 nil " OCDL" nil
18286 (when org-cdlatex-mode
18287 (require 'cdlatex)
18288 (run-hooks 'cdlatex-mode-hook)
18289 (cdlatex-compute-tables))
18290 (unless org-cdlatex-texmathp-advice-is-done
18291 (setq org-cdlatex-texmathp-advice-is-done t)
18292 (defadvice texmathp (around org-math-always-on activate)
18293 "Always return t in org-mode buffers.
18294 This is because we want to insert math symbols without dollars even outside
18295 the LaTeX math segments. If Orgmode thinks that point is actually inside
18296 an embedded LaTeX fragment, let texmathp do its job.
18297 \\[org-cdlatex-mode-map]"
18298 (interactive)
18299 (let (p)
18300 (cond
18301 ((not (derived-mode-p 'org-mode)) ad-do-it)
18302 ((eq this-command 'cdlatex-math-symbol)
18303 (setq ad-return-value t
18304 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18306 (let ((p (org-inside-LaTeX-fragment-p)))
18307 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18308 (setq ad-return-value t
18309 texmathp-why '("Org-mode embedded math" . 0))
18310 (if p ad-do-it)))))))))
18312 (defun turn-on-org-cdlatex ()
18313 "Unconditionally turn on `org-cdlatex-mode'."
18314 (org-cdlatex-mode 1))
18316 (defun org-try-cdlatex-tab ()
18317 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18318 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18319 - inside a LaTeX fragment, or
18320 - after the first word in a line, where an abbreviation expansion could
18321 insert a LaTeX environment."
18322 (when org-cdlatex-mode
18323 (cond
18324 ;; Before any word on the line: No expansion possible.
18325 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18326 ;; Just after first word on the line: Expand it. Make sure it
18327 ;; cannot happen on headlines, though.
18328 ((save-excursion
18329 (skip-chars-backward "a-zA-Z0-9*")
18330 (skip-chars-backward " \t")
18331 (and (bolp) (not (org-at-heading-p))))
18332 (cdlatex-tab) t)
18333 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18335 (defun org-cdlatex-underscore-caret (&optional arg)
18336 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18337 Revert to the normal definition outside of these fragments."
18338 (interactive "P")
18339 (if (org-inside-LaTeX-fragment-p)
18340 (call-interactively 'cdlatex-sub-superscript)
18341 (let (org-cdlatex-mode)
18342 (call-interactively (key-binding (vector last-input-event))))))
18344 (defun org-cdlatex-math-modify (&optional arg)
18345 "Execute `cdlatex-math-modify' in LaTeX fragments.
18346 Revert to the normal definition outside of these fragments."
18347 (interactive "P")
18348 (if (org-inside-LaTeX-fragment-p)
18349 (call-interactively 'cdlatex-math-modify)
18350 (let (org-cdlatex-mode)
18351 (call-interactively (key-binding (vector last-input-event))))))
18355 ;;;; LaTeX fragments
18357 (defun org-inside-LaTeX-fragment-p ()
18358 "Test if point is inside a LaTeX fragment.
18359 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18360 sequence appearing also before point.
18361 Even though the matchers for math are configurable, this function assumes
18362 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18363 delimiters are skipped when they have been removed by customization.
18364 The return value is nil, or a cons cell with the delimiter and the
18365 position of this delimiter.
18367 This function does a reasonably good job, but can locally be fooled by
18368 for example currency specifications. For example it will assume being in
18369 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18370 fragments that are properly closed, but during editing, we have to live
18371 with the uncertainty caused by missing closing delimiters. This function
18372 looks only before point, not after."
18373 (catch 'exit
18374 (let ((pos (point))
18375 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18376 (lim (progn
18377 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18378 (point)))
18379 dd-on str (start 0) m re)
18380 (goto-char pos)
18381 (when dodollar
18382 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18383 re (nth 1 (assoc "$" org-latex-regexps)))
18384 (while (string-match re str start)
18385 (cond
18386 ((= (match-end 0) (length str))
18387 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18388 ((= (match-end 0) (- (length str) 5))
18389 (throw 'exit nil))
18390 (t (setq start (match-end 0))))))
18391 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18392 (goto-char pos)
18393 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18394 (and (match-beginning 2) (throw 'exit nil))
18395 ;; count $$
18396 (while (re-search-backward "\\$\\$" lim t)
18397 (setq dd-on (not dd-on)))
18398 (goto-char pos)
18399 (if dd-on (cons "$$" m))))))
18401 (defun org-inside-latex-macro-p ()
18402 "Is point inside a LaTeX macro or its arguments?"
18403 (save-match-data
18404 (org-in-regexp
18405 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18407 (defvar org-latex-fragment-image-overlays nil
18408 "List of overlays carrying the images of latex fragments.")
18409 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18411 (defun org-remove-latex-fragment-image-overlays ()
18412 "Remove all overlays with LaTeX fragment images in current buffer."
18413 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18414 (setq org-latex-fragment-image-overlays nil))
18416 (defun org-preview-latex-fragment (&optional subtree)
18417 "Preview the LaTeX fragment at point, or all locally or globally.
18418 If the cursor is in a LaTeX fragment, create the image and overlay
18419 it over the source code. If there is no fragment at point, display
18420 all fragments in the current text, from one headline to the next. With
18421 prefix SUBTREE, display all fragments in the current subtree. With a
18422 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18423 the cursor is before the first headline,
18424 display all fragments in the buffer.
18425 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18426 (interactive "P")
18427 (unless buffer-file-name
18428 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18429 (when (display-graphic-p)
18430 (org-remove-latex-fragment-image-overlays)
18431 (save-excursion
18432 (save-restriction
18433 (let (beg end at msg)
18434 (cond
18435 ((or (equal subtree '(16))
18436 (not (save-excursion
18437 (re-search-backward org-outline-regexp-bol nil t))))
18438 (setq beg (point-min) end (point-max)
18439 msg "Creating images for buffer...%s"))
18440 ((equal subtree '(4))
18441 (org-back-to-heading)
18442 (setq beg (point) end (org-end-of-subtree t)
18443 msg "Creating images for subtree...%s"))
18445 (if (setq at (org-inside-LaTeX-fragment-p))
18446 (goto-char (max (point-min) (- (cdr at) 2)))
18447 (org-back-to-heading))
18448 (setq beg (point) end (progn (outline-next-heading) (point))
18449 msg (if at "Creating image...%s"
18450 "Creating images for entry...%s"))))
18451 (message msg "")
18452 (narrow-to-region beg end)
18453 (goto-char beg)
18454 (org-format-latex
18455 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18456 (file-name-nondirectory
18457 buffer-file-name)))
18458 default-directory 'overlays msg at 'forbuffer
18459 org-latex-create-formula-image-program)
18460 (message msg "done. Use `C-c C-c' to remove images."))))))
18462 (defun org-format-latex (prefix &optional dir overlays msg at
18463 forbuffer processing-type)
18464 "Replace LaTeX fragments with links to an image, and produce images.
18465 Some of the options can be changed using the variable
18466 `org-format-latex-options'."
18467 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18468 (let* ((prefixnodir (file-name-nondirectory prefix))
18469 (absprefix (expand-file-name prefix dir))
18470 (todir (file-name-directory absprefix))
18471 (opt org-format-latex-options)
18472 (optnew org-format-latex-options)
18473 (matchers (plist-get opt :matchers))
18474 (re-list org-latex-regexps)
18475 (cnt 0) txt hash link beg end re e checkdir
18476 string
18477 m n block-type block linkfile movefile ov)
18478 ;; Check the different regular expressions
18479 (while (setq e (pop re-list))
18480 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18481 block (if block-type "\n\n" ""))
18482 (when (member m matchers)
18483 (goto-char (point-min))
18484 (while (re-search-forward re nil t)
18485 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18486 (or (not overlays)
18487 (not (eq (get-char-property (match-beginning n)
18488 'org-overlay-type)
18489 'org-latex-overlay))))
18490 (cond
18491 ((eq processing-type 'verbatim))
18492 ((eq processing-type 'mathjax)
18493 ;; Prepare for MathJax processing.
18494 (setq string (match-string n))
18495 (when (member m '("$" "$1"))
18496 (save-excursion
18497 (delete-region (match-beginning n) (match-end n))
18498 (goto-char (match-beginning n))
18499 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18500 ((or (eq processing-type 'dvipng)
18501 (eq processing-type 'imagemagick))
18502 ;; Process to an image.
18503 (setq txt (match-string n)
18504 beg (match-beginning n) end (match-end n)
18505 cnt (1+ cnt))
18506 (let ((face (face-at-point))
18507 (fg (plist-get opt :foreground))
18508 (bg (plist-get opt :background))
18509 ;; Ensure full list is printed.
18510 print-length print-level)
18511 (when forbuffer
18512 ;; Get the colors from the face at point.
18513 (goto-char beg)
18514 (when (eq fg 'auto)
18515 (setq fg (face-attribute face :foreground nil 'default)))
18516 (when (eq bg 'auto)
18517 (setq bg (face-attribute face :background nil 'default)))
18518 (setq optnew (copy-sequence opt))
18519 (plist-put optnew :foreground fg)
18520 (plist-put optnew :background bg))
18521 (setq hash (sha1 (prin1-to-string
18522 (list org-format-latex-header
18523 org-latex-default-packages-alist
18524 org-latex-packages-alist
18525 org-format-latex-options
18526 forbuffer txt fg bg)))
18527 linkfile (format "%s_%s.png" prefix hash)
18528 movefile (format "%s_%s.png" absprefix hash)))
18529 (setq link (concat block "[[file:" linkfile "]]" block))
18530 (if msg (message msg cnt))
18531 (goto-char beg)
18532 (unless checkdir ; Ensure the directory exists.
18533 (setq checkdir t)
18534 (or (file-directory-p todir) (make-directory todir t)))
18535 (unless (file-exists-p movefile)
18536 (org-create-formula-image
18537 txt movefile optnew forbuffer processing-type))
18538 (if overlays
18539 (progn
18540 (mapc (lambda (o)
18541 (if (eq (overlay-get o 'org-overlay-type)
18542 'org-latex-overlay)
18543 (delete-overlay o)))
18544 (overlays-in beg end))
18545 (setq ov (make-overlay beg end))
18546 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18547 (if (featurep 'xemacs)
18548 (progn
18549 (overlay-put ov 'invisible t)
18550 (overlay-put
18551 ov 'end-glyph
18552 (make-glyph (vector 'png :file movefile))))
18553 (overlay-put
18554 ov 'display
18555 (list 'image :type 'png :file movefile :ascent 'center)))
18556 (push ov org-latex-fragment-image-overlays)
18557 (goto-char end))
18558 (delete-region beg end)
18559 (insert (org-add-props link
18560 (list 'org-latex-src
18561 (replace-regexp-in-string
18562 "\"" "" txt)
18563 'org-latex-src-embed-type
18564 (if block-type 'paragraph 'character))))))
18565 ((eq processing-type 'mathml)
18566 ;; Process to MathML
18567 (unless (save-match-data (org-format-latex-mathml-available-p))
18568 (user-error "LaTeX to MathML converter not configured"))
18569 (setq txt (match-string n)
18570 beg (match-beginning n) end (match-end n)
18571 cnt (1+ cnt))
18572 (if msg (message msg cnt))
18573 (goto-char beg)
18574 (delete-region beg end)
18575 (insert (org-format-latex-as-mathml
18576 txt block-type prefix dir)))
18578 (error "Unknown conversion type %s for LaTeX fragments"
18579 processing-type)))))))))
18581 (defun org-create-math-formula (latex-frag &optional mathml-file)
18582 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18583 Use `org-latex-to-mathml-convert-command'. If the conversion is
18584 sucessful, return the portion between \"<math...> </math>\"
18585 elements otherwise return nil. When MATHML-FILE is specified,
18586 write the results in to that file. When invoked as an
18587 interactive command, prompt for LATEX-FRAG, with initial value
18588 set to the current active region and echo the results for user
18589 inspection."
18590 (interactive (list (let ((frag (when (org-region-active-p)
18591 (buffer-substring-no-properties
18592 (region-beginning) (region-end)))))
18593 (read-string "LaTeX Fragment: " frag nil frag))))
18594 (unless latex-frag (error "Invalid LaTeX fragment"))
18595 (let* ((tmp-in-file (file-relative-name
18596 (make-temp-name (expand-file-name "ltxmathml-in"))))
18597 (ignore (write-region latex-frag nil tmp-in-file))
18598 (tmp-out-file (file-relative-name
18599 (make-temp-name (expand-file-name "ltxmathml-out"))))
18600 (cmd (format-spec
18601 org-latex-to-mathml-convert-command
18602 `((?j . ,(shell-quote-argument
18603 (expand-file-name org-latex-to-mathml-jar-file)))
18604 (?I . ,(shell-quote-argument tmp-in-file))
18605 (?o . ,(shell-quote-argument tmp-out-file)))))
18606 mathml shell-command-output)
18607 (when (org-called-interactively-p 'any)
18608 (unless (org-format-latex-mathml-available-p)
18609 (user-error "LaTeX to MathML converter not configured")))
18610 (message "Running %s" cmd)
18611 (setq shell-command-output (shell-command-to-string cmd))
18612 (setq mathml
18613 (when (file-readable-p tmp-out-file)
18614 (with-current-buffer (find-file-noselect tmp-out-file t)
18615 (goto-char (point-min))
18616 (when (re-search-forward
18617 (concat
18618 (regexp-quote
18619 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18620 "\\(.\\|\n\\)*"
18621 (regexp-quote "</math>")) nil t)
18622 (prog1 (match-string 0) (kill-buffer))))))
18623 (cond
18624 (mathml
18625 (setq mathml
18626 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18627 (when mathml-file
18628 (write-region mathml nil mathml-file))
18629 (when (org-called-interactively-p 'any)
18630 (message mathml)))
18631 ((message "LaTeX to MathML conversion failed")
18632 (message shell-command-output)))
18633 (delete-file tmp-in-file)
18634 (when (file-exists-p tmp-out-file)
18635 (delete-file tmp-out-file))
18636 mathml))
18638 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18639 prefix &optional dir)
18640 "Use `org-create-math-formula' but check local cache first."
18641 (let* ((absprefix (expand-file-name prefix dir))
18642 (print-length nil) (print-level nil)
18643 (formula-id (concat
18644 "formula-"
18645 (sha1
18646 (prin1-to-string
18647 (list latex-frag
18648 org-latex-to-mathml-convert-command)))))
18649 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18650 (formula-cache-dir (file-name-directory formula-cache)))
18652 (unless (file-directory-p formula-cache-dir)
18653 (make-directory formula-cache-dir t))
18655 (unless (file-exists-p formula-cache)
18656 (org-create-math-formula latex-frag formula-cache))
18658 (if (file-exists-p formula-cache)
18659 ;; Successful conversion. Return the link to MathML file.
18660 (org-add-props
18661 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18662 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18663 'org-latex-src-embed-type (if latex-frag-type
18664 'paragraph 'character)))
18665 ;; Failed conversion. Return the LaTeX fragment verbatim
18666 latex-frag)))
18668 (defun org-create-formula-image (string tofile options buffer &optional type)
18669 "Create an image from LaTeX source using dvipng or convert.
18670 This function calls either `org-create-formula-image-with-dvipng'
18671 or `org-create-formula-image-with-imagemagick' depending on the
18672 value of `org-latex-create-formula-image-program' or on the value
18673 of the optional TYPE variable.
18675 Note: ultimately these two function should be combined as they
18676 share a good deal of logic."
18677 (org-check-external-command
18678 "latex" "needed to convert LaTeX fragments to images")
18679 (funcall
18680 (case (or type org-latex-create-formula-image-program)
18681 ('dvipng
18682 (org-check-external-command
18683 "dvipng" "needed to convert LaTeX fragments to images")
18684 #'org-create-formula-image-with-dvipng)
18685 ('imagemagick
18686 (org-check-external-command
18687 "convert" "you need to install imagemagick")
18688 #'org-create-formula-image-with-imagemagick)
18689 (t (error
18690 "Invalid value of `org-latex-create-formula-image-program'")))
18691 string tofile options buffer))
18693 (declare-function org-export-get-backend "ox" (name))
18694 (declare-function org-export--get-global-options "ox" (&optional backend))
18695 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18696 (declare-function org-latex-guess-inputenc "ox-latex" (header))
18697 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
18698 (defun org-create-formula--latex-header ()
18699 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18700 (let ((info (org-combine-plists (org-export--get-global-options
18701 (org-export-get-backend 'latex))
18702 (org-export--get-inbuffer-options
18703 (org-export-get-backend 'latex)))))
18704 (org-latex-guess-babel-language
18705 (org-latex-guess-inputenc
18706 (org-splice-latex-header
18707 org-format-latex-header
18708 org-latex-default-packages-alist
18709 org-latex-packages-alist t
18710 (plist-get info :latex-header)))
18711 info)))
18713 ;; This function borrows from Ganesh Swami's latex2png.el
18714 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18715 "This calls dvipng."
18716 (require 'ox-latex)
18717 (let* ((tmpdir (if (featurep 'xemacs)
18718 (temp-directory)
18719 temporary-file-directory))
18720 (texfilebase (make-temp-name
18721 (expand-file-name "orgtex" tmpdir)))
18722 (texfile (concat texfilebase ".tex"))
18723 (dvifile (concat texfilebase ".dvi"))
18724 (pngfile (concat texfilebase ".png"))
18725 (fnh (if (featurep 'xemacs)
18726 (font-height (face-font 'default))
18727 (face-attribute 'default :height nil)))
18728 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18729 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18730 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18731 "Black"))
18732 (bg (or (plist-get options (if buffer :background :html-background))
18733 "Transparent")))
18734 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18735 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18736 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18737 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18738 (let ((latex-header (org-create-formula--latex-header)))
18739 (with-temp-file texfile
18740 (insert latex-header)
18741 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18742 (let ((dir default-directory))
18743 (condition-case nil
18744 (progn
18745 (cd tmpdir)
18746 (call-process "latex" nil nil nil texfile))
18747 (error nil))
18748 (cd dir))
18749 (if (not (file-exists-p dvifile))
18750 (progn (message "Failed to create dvi file from %s" texfile) nil)
18751 (condition-case nil
18752 (if (featurep 'xemacs)
18753 (call-process "dvipng" nil nil nil
18754 "-fg" fg "-bg" bg
18755 "-T" "tight"
18756 "-o" pngfile
18757 dvifile)
18758 (call-process "dvipng" nil nil nil
18759 "-fg" fg "-bg" bg
18760 "-D" dpi
18761 ;;"-x" scale "-y" scale
18762 "-T" "tight"
18763 "-o" pngfile
18764 dvifile))
18765 (error nil))
18766 (if (not (file-exists-p pngfile))
18767 (if org-format-latex-signal-error
18768 (error "Failed to create png file from %s" texfile)
18769 (message "Failed to create png file from %s" texfile)
18770 nil)
18771 ;; Use the requested file name and clean up
18772 (copy-file pngfile tofile 'replace)
18773 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18774 (if (file-exists-p (concat texfilebase e))
18775 (delete-file (concat texfilebase e))))
18776 pngfile))))
18778 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18779 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18780 "This calls convert, which is included into imagemagick."
18781 (require 'ox-latex)
18782 (let* ((tmpdir (if (featurep 'xemacs)
18783 (temp-directory)
18784 temporary-file-directory))
18785 (texfilebase (make-temp-name
18786 (expand-file-name "orgtex" tmpdir)))
18787 (texfile (concat texfilebase ".tex"))
18788 (pdffile (concat texfilebase ".pdf"))
18789 (pngfile (concat texfilebase ".png"))
18790 (fnh (if (featurep 'xemacs)
18791 (font-height (face-font 'default))
18792 (face-attribute 'default :height nil)))
18793 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18794 (dpi (number-to-string (* scale (floor (if buffer fnh 120.)))))
18795 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18796 "black"))
18797 (bg (or (plist-get options (if buffer :background :html-background))
18798 "white")))
18799 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18800 (setq fg (org-latex-color-format fg)))
18801 (if (eq bg 'default) (setq bg (org-latex-color :background))
18802 (setq bg (org-latex-color-format
18803 (if (string= bg "Transparent") "white" bg))))
18804 (let ((latex-header (org-create-formula--latex-header)))
18805 (with-temp-file texfile
18806 (insert latex-header)
18807 (insert "\n\\begin{document}\n"
18808 "\\definecolor{fg}{rgb}{" fg "}\n"
18809 "\\definecolor{bg}{rgb}{" bg "}\n"
18810 "\n\\pagecolor{bg}\n"
18811 "\n{\\color{fg}\n"
18812 string
18813 "\n}\n"
18814 "\n\\end{document}\n")))
18815 (org-latex-compile texfile t)
18816 (if (not (file-exists-p pdffile))
18817 (progn (message "Failed to create pdf file from %s" texfile) nil)
18818 (condition-case nil
18819 (if (featurep 'xemacs)
18820 (call-process "convert" nil nil nil
18821 "-density" "96"
18822 "-trim"
18823 "-antialias"
18824 pdffile
18825 "-quality" "100"
18826 ;; "-sharpen" "0x1.0"
18827 pngfile)
18828 (call-process "convert" nil nil nil
18829 "-density" dpi
18830 "-trim"
18831 "-antialias"
18832 pdffile
18833 "-quality" "100"
18834 ;; "-sharpen" "0x1.0"
18835 pngfile))
18836 (error nil))
18837 (if (not (file-exists-p pngfile))
18838 (if org-format-latex-signal-error
18839 (error "Failed to create png file from %s" texfile)
18840 (message "Failed to create png file from %s" texfile)
18841 nil)
18842 ;; Use the requested file name and clean up
18843 (copy-file pngfile tofile 'replace)
18844 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18845 (if (file-exists-p (concat texfilebase e))
18846 (delete-file (concat texfilebase e))))
18847 pngfile))))
18849 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18850 "Fill a LaTeX header template TPL.
18851 In the template, the following place holders will be recognized:
18853 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18854 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18855 [PACKAGES] \\usepackage statements for PKG
18856 [NO-PACKAGES] do not include PKG
18857 [EXTRA] the string EXTRA
18858 [NO-EXTRA] do not include EXTRA
18860 For backward compatibility, if both the positive and the negative place
18861 holder is missing, the positive one (without the \"NO-\") will be
18862 assumed to be present at the end of the template.
18863 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18864 EXTRA is a string.
18865 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18866 (let (rpl (end ""))
18867 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18868 (setq rpl (if (or (match-end 1) (not def-pkg))
18869 "" (org-latex-packages-to-string def-pkg snippets-p t))
18870 tpl (replace-match rpl t t tpl))
18871 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18873 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18874 (setq rpl (if (or (match-end 1) (not pkg))
18875 "" (org-latex-packages-to-string pkg snippets-p t))
18876 tpl (replace-match rpl t t tpl))
18877 (if pkg (setq end
18878 (concat end "\n"
18879 (org-latex-packages-to-string pkg snippets-p)))))
18881 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18882 (setq rpl (if (or (match-end 1) (not extra))
18883 "" (concat extra "\n"))
18884 tpl (replace-match rpl t t tpl))
18885 (if (and extra (string-match "\\S-" extra))
18886 (setq end (concat end "\n" extra))))
18888 (if (string-match "\\S-" end)
18889 (concat tpl "\n" end)
18890 tpl)))
18892 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18893 "Turn an alist of packages into a string with the \\usepackage macros."
18894 (setq pkg (mapconcat (lambda(p)
18895 (cond
18896 ((stringp p) p)
18897 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18898 (format "%% Package %s omitted" (cadr p)))
18899 ((equal "" (car p))
18900 (format "\\usepackage{%s}" (cadr p)))
18902 (format "\\usepackage[%s]{%s}"
18903 (car p) (cadr p)))))
18905 "\n"))
18906 (if newline (concat pkg "\n") pkg))
18908 (defun org-dvipng-color (attr)
18909 "Return a RGB color specification for dvipng."
18910 (apply 'format "rgb %s %s %s"
18911 (mapcar 'org-normalize-color
18912 (if (featurep 'xemacs)
18913 (color-rgb-components
18914 (face-property 'default
18915 (cond ((eq attr :foreground) 'foreground)
18916 ((eq attr :background) 'background))))
18917 (color-values (face-attribute 'default attr nil))))))
18919 (defun org-dvipng-color-format (color-name)
18920 "Convert COLOR-NAME to a RGB color value for dvipng."
18921 (apply 'format "rgb %s %s %s"
18922 (mapcar 'org-normalize-color
18923 (color-values color-name))))
18925 (defun org-latex-color (attr)
18926 "Return a RGB color for the LaTeX color package."
18927 (apply 'format "%s,%s,%s"
18928 (mapcar 'org-normalize-color
18929 (if (featurep 'xemacs)
18930 (color-rgb-components
18931 (face-property 'default
18932 (cond ((eq attr :foreground) 'foreground)
18933 ((eq attr :background) 'background))))
18934 (color-values (face-attribute 'default attr nil))))))
18936 (defun org-latex-color-format (color-name)
18937 "Convert COLOR-NAME to a RGB color value."
18938 (apply 'format "%s,%s,%s"
18939 (mapcar 'org-normalize-color
18940 (color-values color-name))))
18942 (defun org-normalize-color (value)
18943 "Return string to be used as color value for an RGB component."
18944 (format "%g" (/ value 65535.0)))
18948 ;; Image display
18950 (defvar org-inline-image-overlays nil)
18951 (make-variable-buffer-local 'org-inline-image-overlays)
18953 (defun org-toggle-inline-images (&optional include-linked)
18954 "Toggle the display of inline images.
18955 INCLUDE-LINKED is passed to `org-display-inline-images'."
18956 (interactive "P")
18957 (if org-inline-image-overlays
18958 (progn
18959 (org-remove-inline-images)
18960 (message "Inline image display turned off"))
18961 (org-display-inline-images include-linked)
18962 (if (and (org-called-interactively-p)
18963 org-inline-image-overlays)
18964 (message "%d images displayed inline"
18965 (length org-inline-image-overlays))
18966 (message "No images to display inline"))))
18968 (defun org-redisplay-inline-images ()
18969 "Refresh the display of inline images."
18970 (interactive)
18971 (if (not org-inline-image-overlays)
18972 (org-toggle-inline-images)
18973 (org-toggle-inline-images)
18974 (org-toggle-inline-images)))
18976 (defun org-display-inline-images (&optional include-linked refresh beg end)
18977 "Display inline images.
18979 An inline image is a link which follows either of these
18980 conventions:
18982 1. Its path is a file with an extension matching return value
18983 from `image-file-name-regexp' and it has no contents.
18985 2. Its description consists in a single link of the previous
18986 type.
18988 When optional argument INCLUDE-LINKED is non-nil, also links with
18989 a text description part will be inlined. This can be nice for
18990 a quick look at those images, but it does not reflect what
18991 exported files will look like.
18993 When optional argument REFRESH is non-nil, refresh existing
18994 images between BEG and END. This will create new image displays
18995 only if necessary. BEG and END default to the buffer
18996 boundaries."
18997 (interactive "P")
18998 (when (display-graphic-p)
18999 (unless refresh
19000 (org-remove-inline-images)
19001 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19002 (org-with-wide-buffer
19003 (goto-char (or beg (point-min)))
19004 (let ((case-fold-search t)
19005 (file-extension-re (org-image-file-name-regexp)))
19006 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19007 (let ((link (save-match-data (org-element-context))))
19008 ;; Check if we're at an inline image.
19009 (when (and (equal (org-element-property :type link) "file")
19010 (or include-linked
19011 (not (org-element-property :contents-begin link)))
19012 (let ((parent (org-element-property :parent link)))
19013 (or (not (eq (org-element-type parent) 'link))
19014 (not (cdr (org-element-contents parent)))))
19015 (org-string-match-p file-extension-re
19016 (org-element-property :path link)))
19017 (let ((file (expand-file-name (org-element-property :path link))))
19018 (when (file-exists-p file)
19019 (let ((width
19020 ;; Apply `org-image-actual-width' specifications.
19021 (cond
19022 ((not (image-type-available-p 'imagemagick)) nil)
19023 ((eq org-image-actual-width t) nil)
19024 ((listp org-image-actual-width)
19026 ;; First try to find a width among
19027 ;; attributes associated to the paragraph
19028 ;; containing link.
19029 (let ((paragraph
19030 (let ((e link))
19031 (while (and (setq e (org-element-property
19032 :parent e))
19033 (not (eq (org-element-type e)
19034 'paragraph))))
19035 e)))
19036 (when paragraph
19037 (save-excursion
19038 (goto-char (org-element-property :begin paragraph))
19039 (when (save-match-data
19040 (re-search-forward
19041 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19042 (org-element-property
19043 :post-affiliated paragraph)
19045 (string-to-number (match-string 1))))))
19046 ;; Otherwise, fall-back to provided number.
19047 (car org-image-actual-width)))
19048 ((numberp org-image-actual-width)
19049 org-image-actual-width)))
19050 (old (get-char-property-and-overlay
19051 (org-element-property :begin link)
19052 'org-image-overlay)))
19053 (if (and (car-safe old) refresh)
19054 (image-refresh (overlay-get (cdr old) 'display))
19055 (let ((image (save-match-data
19056 (create-image file
19057 (and width 'imagemagick)
19059 :width width))))
19060 (when image
19061 (let* ((link
19062 ;; If inline image is the description
19063 ;; of another link, be sure to
19064 ;; consider the latter as the one to
19065 ;; apply the overlay on.
19066 (let ((parent
19067 (org-element-property :parent link)))
19068 (if (eq (org-element-type parent) 'link)
19069 parent
19070 link)))
19071 (ov (make-overlay
19072 (org-element-property :begin link)
19073 (progn
19074 (goto-char
19075 (org-element-property :end link))
19076 (skip-chars-backward " \t")
19077 (point)))))
19078 (overlay-put ov 'display image)
19079 (overlay-put ov 'face 'default)
19080 (overlay-put ov 'org-image-overlay t)
19081 (overlay-put
19082 ov 'modification-hooks
19083 (list 'org-display-inline-remove-overlay))
19084 (push ov org-inline-image-overlays)))))))))))))))
19086 (define-obsolete-function-alias
19087 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
19089 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
19090 "Remove inline-display overlay if a corresponding region is modified."
19091 (let ((inhibit-modification-hooks t))
19092 (when (and ov after)
19093 (delete ov org-inline-image-overlays)
19094 (delete-overlay ov))))
19096 (defun org-remove-inline-images ()
19097 "Remove inline display of images."
19098 (interactive)
19099 (mapc 'delete-overlay org-inline-image-overlays)
19100 (setq org-inline-image-overlays nil))
19102 ;;;; Key bindings
19104 ;; Outline functions from `outline-mode-prefix-map'
19105 ;; that can be remapped in Org:
19106 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19107 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
19108 (define-key org-mode-map [remap outline-forward-same-level]
19109 'org-forward-heading-same-level)
19110 (define-key org-mode-map [remap outline-backward-same-level]
19111 'org-backward-heading-same-level)
19112 (define-key org-mode-map [remap show-branches]
19113 'org-kill-note-or-show-branches)
19114 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19115 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19116 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19118 ;; Outline functions from `outline-mode-prefix-map' that can not
19119 ;; be remapped in Org:
19121 ;; - the column "key binding" shows whether the Outline function is still
19122 ;; available in Org mode on the same key that it has been bound to in
19123 ;; Outline mode:
19124 ;; - "overridden": key used for a different functionality in Org mode
19125 ;; - else: key still bound to the same Outline function in Org mode
19127 ;; | Outline function | key binding | Org replacement |
19128 ;; |------------------------------------+-------------+-----------------------|
19129 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
19130 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
19131 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19132 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19133 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19134 ;; | `show-entry' | overridden | no replacement |
19135 ;; | `show-children' | `C-c C-i' | visibility cycling |
19136 ;; | `show-branches' | `C-c C-k' | still same function |
19137 ;; | `show-subtree' | overridden | visibility cycling |
19138 ;; | `show-all' | overridden | no replacement |
19139 ;; | `hide-subtree' | overridden | visibility cycling |
19140 ;; | `hide-body' | overridden | no replacement |
19141 ;; | `hide-entry' | overridden | visibility cycling |
19142 ;; | `hide-leaves' | overridden | no replacement |
19143 ;; | `hide-sublevels' | overridden | no replacement |
19144 ;; | `hide-other' | overridden | no replacement |
19146 ;; Make `C-c C-x' a prefix key
19147 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19149 ;; TAB key with modifiers
19150 (org-defkey org-mode-map "\C-i" 'org-cycle)
19151 (org-defkey org-mode-map [(tab)] 'org-cycle)
19152 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19153 (org-defkey org-mode-map "\M-\t" 'pcomplete)
19154 ;; The following line is necessary under Suse GNU/Linux
19155 (unless (featurep 'xemacs)
19156 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
19157 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19158 (define-key org-mode-map [backtab] 'org-shifttab)
19160 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19161 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19162 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19164 ;; Cursor keys with modifiers
19165 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19166 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19167 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19168 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19170 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19171 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19172 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19173 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19175 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19176 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19177 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19178 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19180 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19181 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19182 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19183 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19185 ;; Babel keys
19186 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19187 (mapc (lambda (pair)
19188 (define-key org-babel-map (car pair) (cdr pair)))
19189 org-babel-key-bindings)
19191 ;;; Extra keys for tty access.
19192 ;; We only set them when really needed because otherwise the
19193 ;; menus don't show the simple keys
19195 (when (or org-use-extra-keys
19196 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19197 (not window-system))
19198 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19199 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19200 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19201 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19202 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19203 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19204 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19205 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19206 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19207 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19208 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19209 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19210 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19211 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19212 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19213 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19214 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19215 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19216 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19217 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19218 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19219 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19220 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
19221 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19222 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19223 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19224 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19225 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19227 ;; All the other keys
19229 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
19230 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19231 (if (boundp 'narrow-map)
19232 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19233 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19234 (if (boundp 'narrow-map)
19235 (org-defkey narrow-map "b" 'org-narrow-to-block)
19236 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19237 (if (boundp 'narrow-map)
19238 (org-defkey narrow-map "e" 'org-narrow-to-element)
19239 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19240 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19241 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19242 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19243 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19244 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19245 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19246 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19247 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19248 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19249 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19250 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
19251 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19252 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19253 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19254 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19255 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19256 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19257 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19258 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19259 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19260 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19261 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19262 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19263 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19264 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19265 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19266 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19267 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19268 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19269 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19270 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19271 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19272 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19273 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19274 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19275 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19276 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19277 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19278 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19279 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19280 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19281 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19282 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19283 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19284 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19285 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19286 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19287 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19288 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19289 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19290 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19291 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19292 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19293 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19294 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19295 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19296 (org-defkey org-mode-map "\C-c^" 'org-sort)
19297 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19298 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19299 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19300 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19301 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19302 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19303 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19304 (org-defkey org-mode-map "\C-m" 'org-return)
19305 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19306 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19307 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19308 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19309 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19310 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19311 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19312 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19313 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19314 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19315 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19316 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19317 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19318 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19319 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19320 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19321 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19322 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19323 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19324 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19325 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19326 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19327 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19329 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19330 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19331 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19333 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19334 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19335 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19336 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19337 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19338 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19339 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19340 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19341 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19342 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19343 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
19344 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19345 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19346 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19347 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19348 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19349 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19350 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19351 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19352 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19353 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19354 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19355 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19357 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19358 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19359 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19360 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19361 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19363 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19365 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19367 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19368 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19370 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19373 (when (featurep 'xemacs)
19374 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19377 (defconst org-speed-commands-default
19379 ("Outline Navigation")
19380 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19381 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19382 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19383 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19384 ("F" . org-next-block)
19385 ("B" . org-previous-block)
19386 ("u" . (org-speed-move-safe 'outline-up-heading))
19387 ("j" . org-goto)
19388 ("g" . (org-refile t))
19389 ("Outline Visibility")
19390 ("c" . org-cycle)
19391 ("C" . org-shifttab)
19392 (" " . org-display-outline-path)
19393 ("s" . org-narrow-to-subtree)
19394 ("=" . org-columns)
19395 ("Outline Structure Editing")
19396 ("U" . org-shiftmetaup)
19397 ("D" . org-shiftmetadown)
19398 ("r" . org-metaright)
19399 ("l" . org-metaleft)
19400 ("R" . org-shiftmetaright)
19401 ("L" . org-shiftmetaleft)
19402 ("i" . (progn (forward-char 1) (call-interactively
19403 'org-insert-heading-respect-content)))
19404 ("^" . org-sort)
19405 ("w" . org-refile)
19406 ("a" . org-archive-subtree-default-with-confirmation)
19407 ("@" . org-mark-subtree)
19408 ("#" . org-toggle-comment)
19409 ("Clock Commands")
19410 ("I" . org-clock-in)
19411 ("O" . org-clock-out)
19412 ("Meta Data Editing")
19413 ("t" . org-todo)
19414 ("," . (org-priority))
19415 ("0" . (org-priority ?\ ))
19416 ("1" . (org-priority ?A))
19417 ("2" . (org-priority ?B))
19418 ("3" . (org-priority ?C))
19419 (":" . org-set-tags-command)
19420 ("e" . org-set-effort)
19421 ("E" . org-inc-effort)
19422 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19423 (org-entry-put (point) "APPT_WARNTIME" m)))
19424 ("Agenda Views etc")
19425 ("v" . org-agenda)
19426 ("/" . org-sparse-tree)
19427 ("Misc")
19428 ("o" . org-open-at-point)
19429 ("?" . org-speed-command-help)
19430 ("<" . (org-agenda-set-restriction-lock 'subtree))
19431 (">" . (org-agenda-remove-restriction-lock))
19433 "The default speed commands.")
19435 (defun org-print-speed-command (e)
19436 (if (> (length (car e)) 1)
19437 (progn
19438 (princ "\n")
19439 (princ (car e))
19440 (princ "\n")
19441 (princ (make-string (length (car e)) ?-))
19442 (princ "\n"))
19443 (princ (car e))
19444 (princ " ")
19445 (if (symbolp (cdr e))
19446 (princ (symbol-name (cdr e)))
19447 (prin1 (cdr e)))
19448 (princ "\n")))
19450 (defun org-speed-command-help ()
19451 "Show the available speed commands."
19452 (interactive)
19453 (if (not org-use-speed-commands)
19454 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19455 (with-output-to-temp-buffer "*Help*"
19456 (princ "User-defined Speed commands\n===========================\n")
19457 (mapc 'org-print-speed-command org-speed-commands-user)
19458 (princ "\n")
19459 (princ "Built-in Speed commands\n=======================\n")
19460 (mapc 'org-print-speed-command org-speed-commands-default))
19461 (with-current-buffer "*Help*"
19462 (setq truncate-lines t))))
19464 (defun org-speed-move-safe (cmd)
19465 "Execute CMD, but make sure that the cursor always ends up in a headline.
19466 If not, return to the original position and throw an error."
19467 (interactive)
19468 (let ((pos (point)))
19469 (call-interactively cmd)
19470 (unless (and (bolp) (org-at-heading-p))
19471 (goto-char pos)
19472 (error "Boundary reached while executing %s" cmd))))
19474 (defvar org-self-insert-command-undo-counter 0)
19476 (defvar org-table-auto-blank-field) ; defined in org-table.el
19477 (defvar org-speed-command nil)
19479 (define-obsolete-function-alias
19480 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19482 (defun org-speed-command-activate (keys)
19483 "Hook for activating single-letter speed commands.
19484 `org-speed-commands-default' specifies a minimal command set.
19485 Use `org-speed-commands-user' for further customization."
19486 (when (or (and (bolp) (looking-at org-outline-regexp))
19487 (and (functionp org-use-speed-commands)
19488 (funcall org-use-speed-commands)))
19489 (cdr (assoc keys (append org-speed-commands-user
19490 org-speed-commands-default)))))
19492 (define-obsolete-function-alias
19493 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19495 (defun org-babel-speed-command-activate (keys)
19496 "Hook for activating single-letter code block commands."
19497 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19498 (cdr (assoc keys org-babel-key-bindings))))
19500 (defcustom org-speed-command-hook
19501 '(org-speed-command-default-hook org-babel-speed-command-hook)
19502 "Hook for activating speed commands at strategic locations.
19503 Hook functions are called in sequence until a valid handler is
19504 found.
19506 Each hook takes a single argument, a user-pressed command key
19507 which is also a `self-insert-command' from the global map.
19509 Within the hook, examine the cursor position and the command key
19510 and return nil or a valid handler as appropriate. Handler could
19511 be one of an interactive command, a function, or a form.
19513 Set `org-use-speed-commands' to non-nil value to enable this
19514 hook. The default setting is `org-speed-command-activate'."
19515 :group 'org-structure
19516 :version "24.1"
19517 :type 'hook)
19519 (defun org-self-insert-command (N)
19520 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19521 If the cursor is in a table looking at whitespace, the whitespace is
19522 overwritten, and the table is not marked as requiring realignment."
19523 (interactive "p")
19524 (org-check-before-invisible-edit 'insert)
19525 (cond
19526 ((and org-use-speed-commands
19527 (setq org-speed-command
19528 (run-hook-with-args-until-success
19529 'org-speed-command-hook (this-command-keys))))
19530 (cond
19531 ((commandp org-speed-command)
19532 (setq this-command org-speed-command)
19533 (call-interactively org-speed-command))
19534 ((functionp org-speed-command)
19535 (funcall org-speed-command))
19536 ((and org-speed-command (listp org-speed-command))
19537 (eval org-speed-command))
19538 (t (let (org-use-speed-commands)
19539 (call-interactively 'org-self-insert-command)))))
19540 ((and
19541 (org-table-p)
19542 (progn
19543 ;; check if we blank the field, and if that triggers align
19544 (and (featurep 'org-table) org-table-auto-blank-field
19545 (member last-command
19546 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19547 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19548 ;; got extra space, this field does not determine column width
19549 (let (org-table-may-need-update) (org-table-blank-field))
19550 ;; no extra space, this field may determine column width
19551 (org-table-blank-field)))
19553 (eq N 1)
19554 (looking-at "[^|\n]* |"))
19555 (let (org-table-may-need-update)
19556 (goto-char (1- (match-end 0)))
19557 (backward-delete-char 1)
19558 (goto-char (match-beginning 0))
19559 (self-insert-command N)))
19561 (setq org-table-may-need-update t)
19562 (self-insert-command N)
19563 (org-fix-tags-on-the-fly)
19564 (if org-self-insert-cluster-for-undo
19565 (if (not (eq last-command 'org-self-insert-command))
19566 (setq org-self-insert-command-undo-counter 1)
19567 (if (>= org-self-insert-command-undo-counter 20)
19568 (setq org-self-insert-command-undo-counter 1)
19569 (and (> org-self-insert-command-undo-counter 0)
19570 buffer-undo-list (listp buffer-undo-list)
19571 (not (cadr buffer-undo-list)) ; remove nil entry
19572 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19573 (setq org-self-insert-command-undo-counter
19574 (1+ org-self-insert-command-undo-counter))))))))
19576 (defun org-check-before-invisible-edit (kind)
19577 "Check is editing if kind KIND would be dangerous with invisible text around.
19578 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19579 ;; First, try to get out of here as quickly as possible, to reduce overhead
19580 (if (and org-catch-invisible-edits
19581 (or (not (boundp 'visible-mode)) (not visible-mode))
19582 (or (get-char-property (point) 'invisible)
19583 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19584 ;; OK, we need to take a closer look
19585 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19586 (invisible-before-point (if (bobp) nil (get-char-property
19587 (1- (point)) 'invisible)))
19588 (border-and-ok-direction
19590 ;; Check if we are acting predictably before invisible text
19591 (and invisible-at-point (not invisible-before-point)
19592 (memq kind '(insert delete-backward)))
19593 ;; Check if we are acting predictably after invisible text
19594 ;; This works not well, and I have turned it off. It seems
19595 ;; better to always show and stop after invisible text.
19596 ;; (and (not invisible-at-point) invisible-before-point
19597 ;; (memq kind '(insert delete)))
19599 (when (or (memq invisible-at-point '(outline org-hide-block t))
19600 (memq invisible-before-point '(outline org-hide-block t)))
19601 (if (eq org-catch-invisible-edits 'error)
19602 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19603 (if (and org-custom-properties-overlays
19604 (y-or-n-p "Display invisible properties in this buffer? "))
19605 (org-toggle-custom-properties-visibility)
19606 ;; Make the area visible
19607 (save-excursion
19608 (if invisible-before-point
19609 (goto-char (previous-single-char-property-change
19610 (point) 'invisible)))
19611 (org-cycle))
19612 (cond
19613 ((eq org-catch-invisible-edits 'show)
19614 ;; That's it, we do the edit after showing
19615 (message
19616 "Unfolding invisible region around point before editing")
19617 (sit-for 1))
19618 ((and (eq org-catch-invisible-edits 'smart)
19619 border-and-ok-direction)
19620 (message "Unfolding invisible region around point before editing"))
19622 ;; Don't do the edit, make the user repeat it in full visibility
19623 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19625 (defun org-fix-tags-on-the-fly ()
19626 (when (and (equal (char-after (point-at-bol)) ?*)
19627 (org-at-heading-p))
19628 (org-align-tags-here org-tags-column)))
19630 (defun org-delete-backward-char (N)
19631 "Like `delete-backward-char', insert whitespace at field end in tables.
19632 When deleting backwards, in tables this function will insert whitespace in
19633 front of the next \"|\" separator, to keep the table aligned. The table will
19634 still be marked for re-alignment if the field did fill the entire column,
19635 because, in this case the deletion might narrow the column."
19636 (interactive "p")
19637 (save-match-data
19638 (org-check-before-invisible-edit 'delete-backward)
19639 (if (and (org-table-p)
19640 (eq N 1)
19641 (string-match "|" (buffer-substring (point-at-bol) (point)))
19642 (looking-at ".*?|"))
19643 (let ((pos (point))
19644 (noalign (looking-at "[^|\n\r]* |"))
19645 (c org-table-may-need-update))
19646 (backward-delete-char N)
19647 (if (not overwrite-mode)
19648 (progn
19649 (skip-chars-forward "^|")
19650 (insert " ")
19651 (goto-char (1- pos))))
19652 ;; noalign: if there were two spaces at the end, this field
19653 ;; does not determine the width of the column.
19654 (if noalign (setq org-table-may-need-update c)))
19655 (backward-delete-char N)
19656 (org-fix-tags-on-the-fly))))
19658 (defun org-delete-char (N)
19659 "Like `delete-char', but insert whitespace at field end in tables.
19660 When deleting characters, in tables this function will insert whitespace in
19661 front of the next \"|\" separator, to keep the table aligned. The table will
19662 still be marked for re-alignment if the field did fill the entire column,
19663 because, in this case the deletion might narrow the column."
19664 (interactive "p")
19665 (save-match-data
19666 (org-check-before-invisible-edit 'delete)
19667 (if (and (org-table-p)
19668 (not (bolp))
19669 (not (= (char-after) ?|))
19670 (eq N 1))
19671 (if (looking-at ".*?|")
19672 (let ((pos (point))
19673 (noalign (looking-at "[^|\n\r]* |"))
19674 (c org-table-may-need-update))
19675 (replace-match
19676 (concat (substring (match-string 0) 1 -1) " |") nil t)
19677 (goto-char pos)
19678 ;; noalign: if there were two spaces at the end, this field
19679 ;; does not determine the width of the column.
19680 (if noalign (setq org-table-may-need-update c)))
19681 (delete-char N))
19682 (delete-char N)
19683 (org-fix-tags-on-the-fly))))
19685 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19686 (put 'org-self-insert-command 'delete-selection
19687 (lambda ()
19688 (not (run-hook-with-args-until-success
19689 'self-insert-uses-region-functions))))
19690 (put 'orgtbl-self-insert-command 'delete-selection
19691 (lambda ()
19692 (not (run-hook-with-args-until-success
19693 'self-insert-uses-region-functions))))
19694 (put 'org-delete-char 'delete-selection 'supersede)
19695 (put 'org-delete-backward-char 'delete-selection 'supersede)
19696 (put 'org-yank 'delete-selection 'yank)
19698 ;; Make `flyspell-mode' delay after some commands
19699 (put 'org-self-insert-command 'flyspell-delayed t)
19700 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19701 (put 'org-delete-char 'flyspell-delayed t)
19702 (put 'org-delete-backward-char 'flyspell-delayed t)
19704 ;; Make pabbrev-mode expand after org-mode commands
19705 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19706 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19708 (defun org-remap (map &rest commands)
19709 "In MAP, remap the functions given in COMMANDS.
19710 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19711 (let (new old)
19712 (while commands
19713 (setq old (pop commands) new (pop commands))
19714 (if (fboundp 'command-remapping)
19715 (org-defkey map (vector 'remap old) new)
19716 (substitute-key-definition old new map global-map)))))
19718 (defun org-transpose-words ()
19719 "Transpose words for Org.
19720 This uses the `org-mode-transpose-word-syntax-table' syntax
19721 table, which interprets characters in `org-emphasis-alist' as
19722 word constituents."
19723 (interactive)
19724 (with-syntax-table org-mode-transpose-word-syntax-table
19725 (call-interactively 'transpose-words)))
19726 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19728 (when (eq org-enable-table-editor 'optimized)
19729 ;; If the user wants maximum table support, we need to hijack
19730 ;; some standard editing functions
19731 (org-remap org-mode-map
19732 'self-insert-command 'org-self-insert-command
19733 'delete-char 'org-delete-char
19734 'delete-backward-char 'org-delete-backward-char)
19735 (org-defkey org-mode-map "|" 'org-force-self-insert))
19737 (defvar org-ctrl-c-ctrl-c-hook nil
19738 "Hook for functions attaching themselves to `C-c C-c'.
19740 This can be used to add additional functionality to the C-c C-c
19741 key which executes context-dependent commands. This hook is run
19742 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19743 run after the last test.
19745 Each function will be called with no arguments. The function
19746 must check if the context is appropriate for it to act. If yes,
19747 it should do its thing and then return a non-nil value. If the
19748 context is wrong, just do nothing and return nil.")
19750 (defvar org-ctrl-c-ctrl-c-final-hook nil
19751 "Hook for functions attaching themselves to `C-c C-c'.
19753 This can be used to add additional functionality to the C-c C-c
19754 key which executes context-dependent commands. This hook is run
19755 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19756 before the first test.
19758 Each function will be called with no arguments. The function
19759 must check if the context is appropriate for it to act. If yes,
19760 it should do its thing and then return a non-nil value. If the
19761 context is wrong, just do nothing and return nil.")
19763 (defvar org-tab-first-hook nil
19764 "Hook for functions to attach themselves to TAB.
19765 See `org-ctrl-c-ctrl-c-hook' for more information.
19766 This hook runs as the first action when TAB is pressed, even before
19767 `org-cycle' messes around with the `outline-regexp' to cater for
19768 inline tasks and plain list item folding.
19769 If any function in this hook returns t, any other actions that
19770 would have been caused by TAB (such as table field motion or visibility
19771 cycling) will not occur.")
19773 (defvar org-tab-after-check-for-table-hook nil
19774 "Hook for functions to attach themselves to TAB.
19775 See `org-ctrl-c-ctrl-c-hook' for more information.
19776 This hook runs after it has been established that the cursor is not in a
19777 table, but before checking if the cursor is in a headline or if global cycling
19778 should be done.
19779 If any function in this hook returns t, not other actions like visibility
19780 cycling will be done.")
19782 (defvar org-tab-after-check-for-cycling-hook nil
19783 "Hook for functions to attach themselves to TAB.
19784 See `org-ctrl-c-ctrl-c-hook' for more information.
19785 This hook runs after it has been established that not table field motion and
19786 not visibility should be done because of current context. This is probably
19787 the place where a package like yasnippets can hook in.")
19789 (defvar org-tab-before-tab-emulation-hook nil
19790 "Hook for functions to attach themselves to TAB.
19791 See `org-ctrl-c-ctrl-c-hook' for more information.
19792 This hook runs after every other options for TAB have been exhausted, but
19793 before indentation and \t insertion takes place.")
19795 (defvar org-metaleft-hook nil
19796 "Hook for functions attaching themselves to `M-left'.
19797 See `org-ctrl-c-ctrl-c-hook' for more information.")
19798 (defvar org-metaright-hook nil
19799 "Hook for functions attaching themselves to `M-right'.
19800 See `org-ctrl-c-ctrl-c-hook' for more information.")
19801 (defvar org-metaup-hook nil
19802 "Hook for functions attaching themselves to `M-up'.
19803 See `org-ctrl-c-ctrl-c-hook' for more information.")
19804 (defvar org-metadown-hook nil
19805 "Hook for functions attaching themselves to `M-down'.
19806 See `org-ctrl-c-ctrl-c-hook' for more information.")
19807 (defvar org-shiftmetaleft-hook nil
19808 "Hook for functions attaching themselves to `M-S-left'.
19809 See `org-ctrl-c-ctrl-c-hook' for more information.")
19810 (defvar org-shiftmetaright-hook nil
19811 "Hook for functions attaching themselves to `M-S-right'.
19812 See `org-ctrl-c-ctrl-c-hook' for more information.")
19813 (defvar org-shiftmetaup-hook nil
19814 "Hook for functions attaching themselves to `M-S-up'.
19815 See `org-ctrl-c-ctrl-c-hook' for more information.")
19816 (defvar org-shiftmetadown-hook nil
19817 "Hook for functions attaching themselves to `M-S-down'.
19818 See `org-ctrl-c-ctrl-c-hook' for more information.")
19819 (defvar org-metareturn-hook nil
19820 "Hook for functions attaching themselves to `M-RET'.
19821 See `org-ctrl-c-ctrl-c-hook' for more information.")
19822 (defvar org-shiftup-hook nil
19823 "Hook for functions attaching themselves to `S-up'.
19824 See `org-ctrl-c-ctrl-c-hook' for more information.")
19825 (defvar org-shiftup-final-hook nil
19826 "Hook for functions attaching themselves to `S-up'.
19827 This one runs after all other options except shift-select have been excluded.
19828 See `org-ctrl-c-ctrl-c-hook' for more information.")
19829 (defvar org-shiftdown-hook nil
19830 "Hook for functions attaching themselves to `S-down'.
19831 See `org-ctrl-c-ctrl-c-hook' for more information.")
19832 (defvar org-shiftdown-final-hook nil
19833 "Hook for functions attaching themselves to `S-down'.
19834 This one runs after all other options except shift-select have been excluded.
19835 See `org-ctrl-c-ctrl-c-hook' for more information.")
19836 (defvar org-shiftleft-hook nil
19837 "Hook for functions attaching themselves to `S-left'.
19838 See `org-ctrl-c-ctrl-c-hook' for more information.")
19839 (defvar org-shiftleft-final-hook nil
19840 "Hook for functions attaching themselves to `S-left'.
19841 This one runs after all other options except shift-select have been excluded.
19842 See `org-ctrl-c-ctrl-c-hook' for more information.")
19843 (defvar org-shiftright-hook nil
19844 "Hook for functions attaching themselves to `S-right'.
19845 See `org-ctrl-c-ctrl-c-hook' for more information.")
19846 (defvar org-shiftright-final-hook nil
19847 "Hook for functions attaching themselves to `S-right'.
19848 This one runs after all other options except shift-select have been excluded.
19849 See `org-ctrl-c-ctrl-c-hook' for more information.")
19851 (defun org-modifier-cursor-error ()
19852 "Throw an error, a modified cursor command was applied in wrong context."
19853 (user-error "This command is active in special context like tables, headlines or items"))
19855 (defun org-shiftselect-error ()
19856 "Throw an error because Shift-Cursor command was applied in wrong context."
19857 (if (and (boundp 'shift-select-mode) shift-select-mode)
19858 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19859 (user-error "This command works only in special context like headlines or timestamps")))
19861 (defun org-call-for-shift-select (cmd)
19862 (let ((this-command-keys-shift-translated t))
19863 (call-interactively cmd)))
19865 (defun org-shifttab (&optional arg)
19866 "Global visibility cycling or move to previous table field.
19867 Call `org-table-previous-field' within a table.
19868 When ARG is nil, cycle globally through visibility states.
19869 When ARG is a numeric prefix, show contents of this level."
19870 (interactive "P")
19871 (cond
19872 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19873 ((integerp arg)
19874 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19875 (message "Content view to level: %d" arg)
19876 (org-content (prefix-numeric-value arg2))
19877 (org-cycle-show-empty-lines t)
19878 (setq org-cycle-global-status 'overview)))
19879 (t (call-interactively 'org-global-cycle))))
19881 (defun org-shiftmetaleft ()
19882 "Promote subtree or delete table column.
19883 Calls `org-promote-subtree', `org-outdent-item-tree', or
19884 `org-table-delete-column', depending on context. See the
19885 individual commands for more information."
19886 (interactive)
19887 (cond
19888 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19889 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19890 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19891 ((if (not (org-region-active-p)) (org-at-item-p)
19892 (save-excursion (goto-char (region-beginning))
19893 (org-at-item-p)))
19894 (call-interactively 'org-outdent-item-tree))
19895 (t (org-modifier-cursor-error))))
19897 (defun org-shiftmetaright ()
19898 "Demote subtree or insert table column.
19899 Calls `org-demote-subtree', `org-indent-item-tree', or
19900 `org-table-insert-column', depending on context. See the
19901 individual commands for more information."
19902 (interactive)
19903 (cond
19904 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19905 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19906 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19907 ((if (not (org-region-active-p)) (org-at-item-p)
19908 (save-excursion (goto-char (region-beginning))
19909 (org-at-item-p)))
19910 (call-interactively 'org-indent-item-tree))
19911 (t (org-modifier-cursor-error))))
19913 (defun org-shiftmetaup (&optional arg)
19914 "Move subtree up or kill table row.
19915 Calls `org-move-subtree-up' or `org-table-kill-row' or
19916 `org-move-item-up' or `org-timestamp-up', depending on context.
19917 See the individual commands for more information."
19918 (interactive "P")
19919 (cond
19920 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19921 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19922 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19923 ((org-at-item-p) (call-interactively 'org-move-item-up))
19924 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19925 (call-interactively 'org-timestamp-up)))
19926 (t (call-interactively 'org-drag-line-backward))))
19928 (defun org-shiftmetadown (&optional arg)
19929 "Move subtree down or insert table row.
19930 Calls `org-move-subtree-down' or `org-table-insert-row' or
19931 `org-move-item-down' or `org-timestamp-up', depending on context.
19932 See the individual commands for more information."
19933 (interactive "P")
19934 (cond
19935 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19936 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19937 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19938 ((org-at-item-p) (call-interactively 'org-move-item-down))
19939 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19940 (call-interactively 'org-timestamp-down)))
19941 (t (call-interactively 'org-drag-line-forward))))
19943 (defsubst org-hidden-tree-error ()
19944 (user-error
19945 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19947 (defun org-metaleft (&optional arg)
19948 "Promote heading or move table column to left.
19949 Calls `org-do-promote' or `org-table-move-column', depending on context.
19950 With no specific context, calls the Emacs default `backward-word'.
19951 See the individual commands for more information."
19952 (interactive "P")
19953 (cond
19954 ((run-hook-with-args-until-success 'org-metaleft-hook))
19955 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19956 ((org-with-limited-levels
19957 (or (org-at-heading-p)
19958 (and (org-region-active-p)
19959 (save-excursion
19960 (goto-char (region-beginning))
19961 (org-at-heading-p)))))
19962 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19963 (call-interactively 'org-do-promote))
19964 ;; At an inline task.
19965 ((org-at-heading-p)
19966 (call-interactively 'org-inlinetask-promote))
19967 ((or (org-at-item-p)
19968 (and (org-region-active-p)
19969 (save-excursion
19970 (goto-char (region-beginning))
19971 (org-at-item-p))))
19972 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19973 (call-interactively 'org-outdent-item))
19974 (t (call-interactively 'backward-word))))
19976 (defun org-metaright (&optional arg)
19977 "Demote a subtree, a list item or move table column to right.
19978 In front of a drawer or a block keyword, indent it correctly.
19979 With no specific context, calls the Emacs default `forward-word'.
19980 See the individual commands for more information."
19981 (interactive "P")
19982 (cond
19983 ((run-hook-with-args-until-success 'org-metaright-hook))
19984 ((org-at-table-p) (call-interactively 'org-table-move-column))
19985 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19986 ((org-at-block-p) (call-interactively 'org-indent-block))
19987 ((org-with-limited-levels
19988 (or (org-at-heading-p)
19989 (and (org-region-active-p)
19990 (save-excursion
19991 (goto-char (region-beginning))
19992 (org-at-heading-p)))))
19993 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19994 (call-interactively 'org-do-demote))
19995 ;; At an inline task.
19996 ((org-at-heading-p)
19997 (call-interactively 'org-inlinetask-demote))
19998 ((or (org-at-item-p)
19999 (and (org-region-active-p)
20000 (save-excursion
20001 (goto-char (region-beginning))
20002 (org-at-item-p))))
20003 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20004 (call-interactively 'org-indent-item))
20005 (t (call-interactively 'forward-word))))
20007 (defun org-check-for-hidden (what)
20008 "Check if there are hidden headlines/items in the current visual line.
20009 WHAT can be either `headlines' or `items'. If the current line is
20010 an outline or item heading and it has a folded subtree below it,
20011 this function returns t, nil otherwise."
20012 (let ((re (cond
20013 ((eq what 'headlines) org-outline-regexp-bol)
20014 ((eq what 'items) (org-item-beginning-re))
20015 (t (error "This should not happen"))))
20016 beg end)
20017 (save-excursion
20018 (catch 'exit
20019 (unless (org-region-active-p)
20020 (setq beg (point-at-bol))
20021 (beginning-of-line 2)
20022 (while (and (not (eobp)) ;; this is like `next-line'
20023 (get-char-property (1- (point)) 'invisible))
20024 (beginning-of-line 2))
20025 (setq end (point))
20026 (goto-char beg)
20027 (goto-char (point-at-eol))
20028 (setq end (max end (point)))
20029 (while (re-search-forward re end t)
20030 (if (get-char-property (match-beginning 0) 'invisible)
20031 (throw 'exit t))))
20032 nil))))
20034 (defun org-metaup (&optional arg)
20035 "Move subtree up or move table row up.
20036 Calls `org-move-subtree-up' or `org-table-move-row' or
20037 `org-move-item-up', depending on context. See the individual commands
20038 for more information."
20039 (interactive "P")
20040 (cond
20041 ((run-hook-with-args-until-success 'org-metaup-hook))
20042 ((org-region-active-p)
20043 (let* ((a (min (region-beginning) (region-end)))
20044 (b (1- (max (region-beginning) (region-end))))
20045 (c (save-excursion (goto-char a)
20046 (move-beginning-of-line 0)))
20047 (d (save-excursion (goto-char a)
20048 (move-end-of-line 0) (point))))
20049 (transpose-regions a b c d)
20050 (goto-char c)))
20051 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20052 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20053 ((org-at-item-p) (call-interactively 'org-move-item-up))
20054 (t (org-drag-element-backward))))
20056 (defun org-metadown (&optional arg)
20057 "Move subtree down or move table row down.
20058 Calls `org-move-subtree-down' or `org-table-move-row' or
20059 `org-move-item-down', depending on context. See the individual
20060 commands for more information."
20061 (interactive "P")
20062 (cond
20063 ((run-hook-with-args-until-success 'org-metadown-hook))
20064 ((org-region-active-p)
20065 (let* ((a (min (region-beginning) (region-end)))
20066 (b (max (region-beginning) (region-end)))
20067 (c (save-excursion (goto-char b)
20068 (move-beginning-of-line 1)))
20069 (d (save-excursion (goto-char b)
20070 (move-end-of-line 1) (1+ (point)))))
20071 (transpose-regions a b c d)
20072 (goto-char d)))
20073 ((org-at-table-p) (call-interactively 'org-table-move-row))
20074 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20075 ((org-at-item-p) (call-interactively 'org-move-item-down))
20076 (t (org-drag-element-forward))))
20078 (defun org-shiftup (&optional arg)
20079 "Increase item in timestamp or increase priority of current headline.
20080 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20081 depending on context. See the individual commands for more information."
20082 (interactive "P")
20083 (cond
20084 ((run-hook-with-args-until-success 'org-shiftup-hook))
20085 ((and org-support-shift-select (org-region-active-p))
20086 (org-call-for-shift-select 'previous-line))
20087 ((org-at-timestamp-p t)
20088 (call-interactively (if org-edit-timestamp-down-means-later
20089 'org-timestamp-down 'org-timestamp-up)))
20090 ((and (not (eq org-support-shift-select 'always))
20091 org-enable-priority-commands
20092 (org-at-heading-p))
20093 (call-interactively 'org-priority-up))
20094 ((and (not org-support-shift-select) (org-at-item-p))
20095 (call-interactively 'org-previous-item))
20096 ((org-clocktable-try-shift 'up arg))
20097 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20098 (org-support-shift-select
20099 (org-call-for-shift-select 'previous-line))
20100 (t (org-shiftselect-error))))
20102 (defun org-shiftdown (&optional arg)
20103 "Decrease item in timestamp or decrease priority of current headline.
20104 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20105 depending on context. See the individual commands for more information."
20106 (interactive "P")
20107 (cond
20108 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20109 ((and org-support-shift-select (org-region-active-p))
20110 (org-call-for-shift-select 'next-line))
20111 ((org-at-timestamp-p t)
20112 (call-interactively (if org-edit-timestamp-down-means-later
20113 'org-timestamp-up 'org-timestamp-down)))
20114 ((and (not (eq org-support-shift-select 'always))
20115 org-enable-priority-commands
20116 (org-at-heading-p))
20117 (call-interactively 'org-priority-down))
20118 ((and (not org-support-shift-select) (org-at-item-p))
20119 (call-interactively 'org-next-item))
20120 ((org-clocktable-try-shift 'down arg))
20121 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20122 (org-support-shift-select
20123 (org-call-for-shift-select 'next-line))
20124 (t (org-shiftselect-error))))
20126 (defun org-shiftright (&optional arg)
20127 "Cycle the thing at point or in the current line, depending on context.
20128 Depending on context, this does one of the following:
20130 - switch a timestamp at point one day into the future
20131 - on a headline, switch to the next TODO keyword.
20132 - on an item, switch entire list to the next bullet type
20133 - on a property line, switch to the next allowed value
20134 - on a clocktable definition line, move time block into the future"
20135 (interactive "P")
20136 (cond
20137 ((run-hook-with-args-until-success 'org-shiftright-hook))
20138 ((and org-support-shift-select (org-region-active-p))
20139 (org-call-for-shift-select 'forward-char))
20140 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20141 ((and (not (eq org-support-shift-select 'always))
20142 (org-at-heading-p))
20143 (let ((org-inhibit-logging
20144 (not org-treat-S-cursor-todo-selection-as-state-change))
20145 (org-inhibit-blocking
20146 (not org-treat-S-cursor-todo-selection-as-state-change)))
20147 (org-call-with-arg 'org-todo 'right)))
20148 ((or (and org-support-shift-select
20149 (not (eq org-support-shift-select 'always))
20150 (org-at-item-bullet-p))
20151 (and (not org-support-shift-select) (org-at-item-p)))
20152 (org-call-with-arg 'org-cycle-list-bullet nil))
20153 ((and (not (eq org-support-shift-select 'always))
20154 (org-at-property-p))
20155 (call-interactively 'org-property-next-allowed-value))
20156 ((org-clocktable-try-shift 'right arg))
20157 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20158 (org-support-shift-select
20159 (org-call-for-shift-select 'forward-char))
20160 (t (org-shiftselect-error))))
20162 (defun org-shiftleft (&optional arg)
20163 "Cycle the thing at point or in the current line, depending on context.
20164 Depending on context, this does one of the following:
20166 - switch a timestamp at point one day into the past
20167 - on a headline, switch to the previous TODO keyword.
20168 - on an item, switch entire list to the previous bullet type
20169 - on a property line, switch to the previous allowed value
20170 - on a clocktable definition line, move time block into the past"
20171 (interactive "P")
20172 (cond
20173 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20174 ((and org-support-shift-select (org-region-active-p))
20175 (org-call-for-shift-select 'backward-char))
20176 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20177 ((and (not (eq org-support-shift-select 'always))
20178 (org-at-heading-p))
20179 (let ((org-inhibit-logging
20180 (not org-treat-S-cursor-todo-selection-as-state-change))
20181 (org-inhibit-blocking
20182 (not org-treat-S-cursor-todo-selection-as-state-change)))
20183 (org-call-with-arg 'org-todo 'left)))
20184 ((or (and org-support-shift-select
20185 (not (eq org-support-shift-select 'always))
20186 (org-at-item-bullet-p))
20187 (and (not org-support-shift-select) (org-at-item-p)))
20188 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20189 ((and (not (eq org-support-shift-select 'always))
20190 (org-at-property-p))
20191 (call-interactively 'org-property-previous-allowed-value))
20192 ((org-clocktable-try-shift 'left arg))
20193 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20194 (org-support-shift-select
20195 (org-call-for-shift-select 'backward-char))
20196 (t (org-shiftselect-error))))
20198 (defun org-shiftcontrolright ()
20199 "Switch to next TODO set."
20200 (interactive)
20201 (cond
20202 ((and org-support-shift-select (org-region-active-p))
20203 (org-call-for-shift-select 'forward-word))
20204 ((and (not (eq org-support-shift-select 'always))
20205 (org-at-heading-p))
20206 (org-call-with-arg 'org-todo 'nextset))
20207 (org-support-shift-select
20208 (org-call-for-shift-select 'forward-word))
20209 (t (org-shiftselect-error))))
20211 (defun org-shiftcontrolleft ()
20212 "Switch to previous TODO set."
20213 (interactive)
20214 (cond
20215 ((and org-support-shift-select (org-region-active-p))
20216 (org-call-for-shift-select 'backward-word))
20217 ((and (not (eq org-support-shift-select 'always))
20218 (org-at-heading-p))
20219 (org-call-with-arg 'org-todo 'previousset))
20220 (org-support-shift-select
20221 (org-call-for-shift-select 'backward-word))
20222 (t (org-shiftselect-error))))
20224 (defun org-shiftcontrolup (&optional n)
20225 "Change timestamps synchronously up in CLOCK log lines.
20226 Optional argument N tells to change by that many units."
20227 (interactive "P")
20228 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20229 (let (org-support-shift-select)
20230 (org-clock-timestamps-up n))
20231 (user-error "Not at a clock log")))
20233 (defun org-shiftcontroldown (&optional n)
20234 "Change timestamps synchronously down in CLOCK log lines.
20235 Optional argument N tells to change by that many units."
20236 (interactive "P")
20237 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20238 (let (org-support-shift-select)
20239 (org-clock-timestamps-down n))
20240 (user-error "Not at a clock log")))
20242 (defun org-ctrl-c-ret ()
20243 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20244 (interactive)
20245 (cond
20246 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20247 (t (call-interactively 'org-insert-heading))))
20249 (defun org-find-visible ()
20250 (let ((s (point)))
20251 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20252 (get-char-property s 'invisible)))
20254 (defun org-find-invisible ()
20255 (let ((s (point)))
20256 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20257 (not (get-char-property s 'invisible))))
20260 (defun org-copy-visible (beg end)
20261 "Copy the visible parts of the region."
20262 (interactive "r")
20263 (let (snippets s)
20264 (save-excursion
20265 (save-restriction
20266 (narrow-to-region beg end)
20267 (setq s (goto-char (point-min)))
20268 (while (not (= (point) (point-max)))
20269 (goto-char (org-find-invisible))
20270 (push (buffer-substring s (point)) snippets)
20271 (setq s (goto-char (org-find-visible))))))
20272 (kill-new (apply 'concat (nreverse snippets)))))
20274 (defun org-copy-special ()
20275 "Copy region in table or copy current subtree.
20276 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20277 See the individual commands for more information."
20278 (interactive)
20279 (call-interactively
20280 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20282 (defun org-cut-special ()
20283 "Cut region in table or cut current subtree.
20284 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20285 See the individual commands for more information."
20286 (interactive)
20287 (call-interactively
20288 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20290 (defun org-paste-special (arg)
20291 "Paste rectangular region into table, or past subtree relative to level.
20292 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20293 See the individual commands for more information."
20294 (interactive "P")
20295 (if (org-at-table-p)
20296 (org-table-paste-rectangle)
20297 (org-paste-subtree arg)))
20299 (defsubst org-in-fixed-width-region-p ()
20300 "Is point in a fixed-width region?"
20301 (save-match-data
20302 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20304 (defun org-edit-special (&optional arg)
20305 "Call a special editor for the element at point.
20306 When at a table, call the formula editor with `org-table-edit-formulas'.
20307 When in a source code block, call `org-edit-src-code'.
20308 When in a fixed-width region, call `org-edit-fixed-width-region'.
20309 When at an #+INCLUDE keyword, visit the included file.
20310 On a link, call `ffap' to visit the link at point.
20311 Otherwise, return a user error."
20312 (interactive "P")
20313 (let ((element (org-element-at-point)))
20314 (assert (not buffer-read-only) nil
20315 "Buffer is read-only: %s" (buffer-name))
20316 (case (org-element-type element)
20317 (src-block
20318 (if (not arg) (org-edit-src-code)
20319 (let* ((info (org-babel-get-src-block-info))
20320 (lang (nth 0 info))
20321 (params (nth 2 info))
20322 (session (cdr (assq :session params))))
20323 (if (not session) (org-edit-src-code)
20324 ;; At a src-block with a session and function called with
20325 ;; an ARG: switch to the buffer related to the inferior
20326 ;; process.
20327 (switch-to-buffer
20328 (funcall (intern (concat "org-babel-prep-session:" lang))
20329 session params))))))
20330 (keyword
20331 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20332 (find-file-other-window
20333 (org-remove-double-quotes
20334 (car (org-split-string (org-element-property :value element)))))
20335 (user-error "No special environment to edit here")))
20336 (table
20337 (if (eq (org-element-property :type element) 'table.el)
20338 (org-edit-src-code)
20339 (call-interactively 'org-table-edit-formulas)))
20340 ;; Only Org tables contain `table-row' type elements.
20341 (table-row (call-interactively 'org-table-edit-formulas))
20342 ((example-block export-block) (org-edit-src-code))
20343 (fixed-width (org-edit-fixed-width-region))
20344 (otherwise
20345 ;; No notable element at point. Though, we may be at a link,
20346 ;; which is an object. Thus, scan deeper.
20347 (if (eq (org-element-type (org-element-context element)) 'link)
20348 (call-interactively 'ffap)
20349 (user-error "No special environment to edit here"))))))
20351 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20352 (defun org-ctrl-c-ctrl-c (&optional arg)
20353 "Set tags in headline, or update according to changed information at point.
20355 This command does many different things, depending on context:
20357 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20358 this is what we do.
20360 - If the cursor is on a statistics cookie, update it.
20362 - If the cursor is in a headline, prompt for tags and insert them
20363 into the current line, aligned to `org-tags-column'. When called
20364 with prefix arg, realign all tags in the current buffer.
20366 - If the cursor is in one of the special #+KEYWORD lines, this
20367 triggers scanning the buffer for these lines and updating the
20368 information.
20370 - If the cursor is inside a table, realign the table. This command
20371 works even if the automatic table editor has been turned off.
20373 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20374 the entire table.
20376 - If the cursor is at a footnote reference or definition, jump to
20377 the corresponding definition or references, respectively.
20379 - If the cursor is a the beginning of a dynamic block, update it.
20381 - If the current buffer is a capture buffer, close note and file it.
20383 - If the cursor is on a <<<target>>>, update radio targets and
20384 corresponding links in this buffer.
20386 - If the cursor is on a numbered item in a plain list, renumber the
20387 ordered list.
20389 - If the cursor is on a checkbox, toggle it.
20391 - If the cursor is on a code block, evaluate it. The variable
20392 `org-confirm-babel-evaluate' can be used to control prompting
20393 before code block evaluation, by default every code block
20394 evaluation requires confirmation. Code block evaluation can be
20395 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20396 (interactive "P")
20397 (cond
20398 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20399 org-occur-highlights
20400 org-latex-fragment-image-overlays)
20401 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20402 (org-remove-occur-highlights)
20403 (org-remove-latex-fragment-image-overlays)
20404 (message "Temporary highlights/overlays removed from current buffer"))
20405 ((and (local-variable-p 'org-finish-function (current-buffer))
20406 (fboundp org-finish-function))
20407 (funcall org-finish-function))
20408 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20410 (let* ((context (org-element-context)) (type (org-element-type context)))
20411 ;; Test if point is within a blank line.
20412 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20413 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20414 (user-error "C-c C-c can do nothing useful at this location"))
20415 (case type
20416 ;; When at a link, act according to the parent instead.
20417 (link (setq context (org-element-property :parent context))
20418 (setq type (org-element-type context)))
20419 ;; Unsupported object types: refer to the first supported
20420 ;; element or object containing it.
20421 ((bold code entity export-snippet inline-babel-call inline-src-block
20422 italic latex-fragment line-break macro strike-through subscript
20423 superscript underline verbatim)
20424 (while (and (setq context (org-element-property :parent context))
20425 (not (memq (setq type (org-element-type context))
20426 '(radio-target paragraph verse-block
20427 table-cell)))))))
20428 ;; For convenience: at the first line of a paragraph on the
20429 ;; same line as an item, apply function on that item instead.
20430 (when (eq type 'paragraph)
20431 (let ((parent (org-element-property :parent context)))
20432 (when (and (eq (org-element-type parent) 'item)
20433 (= (point-at-bol) (org-element-property :begin parent)))
20434 (setq context parent type 'item))))
20435 ;; Act according to type of element or object at point.
20436 (case type
20437 (clock (org-clock-update-time-maybe))
20438 (dynamic-block
20439 (save-excursion
20440 (goto-char (org-element-property :post-affiliated context))
20441 (org-update-dblock)))
20442 (footnote-definition
20443 (goto-char (org-element-property :post-affiliated context))
20444 (call-interactively 'org-footnote-action))
20445 (footnote-reference (call-interactively 'org-footnote-action))
20446 ((headline inlinetask)
20447 (save-excursion (goto-char (org-element-property :begin context))
20448 (call-interactively 'org-set-tags)))
20449 (item
20450 ;; At an item: a double C-u set checkbox to "[-]"
20451 ;; unconditionally, whereas a single one will toggle its
20452 ;; presence. Without an universal argument, if the item
20453 ;; has a checkbox, toggle it. Otherwise repair the list.
20454 (let* ((box (org-element-property :checkbox context))
20455 (struct (org-element-property :structure context))
20456 (old-struct (copy-tree struct))
20457 (parents (org-list-parents-alist struct))
20458 (prevs (org-list-prevs-alist struct))
20459 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20460 (org-list-set-checkbox
20461 (org-element-property :begin context) struct
20462 (cond ((equal arg '(16)) "[-]")
20463 ((and (not box) (equal arg '(4))) "[ ]")
20464 ((or (not box) (equal arg '(4))) nil)
20465 ((eq box 'on) "[ ]")
20466 (t "[X]")))
20467 ;; Mimic `org-list-write-struct' but with grabbing
20468 ;; a return value from `org-list-struct-fix-box'.
20469 (org-list-struct-fix-ind struct parents 2)
20470 (org-list-struct-fix-item-end struct)
20471 (org-list-struct-fix-bul struct prevs)
20472 (org-list-struct-fix-ind struct parents)
20473 (let ((block-item
20474 (org-list-struct-fix-box struct parents prevs orderedp)))
20475 (if (and box (equal struct old-struct))
20476 (if (equal arg '(16))
20477 (message "Checkboxes already reset")
20478 (user-error "Cannot toggle this checkbox: %s"
20479 (if (eq box 'on)
20480 "all subitems checked"
20481 "unchecked subitems")))
20482 (org-list-struct-apply-struct struct old-struct)
20483 (org-update-checkbox-count-maybe))
20484 (when block-item
20485 (message "Checkboxes were removed due to empty box at line %d"
20486 (org-current-line block-item))))))
20487 (keyword
20488 (let ((org-inhibit-startup-visibility-stuff t)
20489 (org-startup-align-all-tables nil))
20490 (when (boundp 'org-table-coordinate-overlays)
20491 (mapc 'delete-overlay org-table-coordinate-overlays)
20492 (setq org-table-coordinate-overlays nil))
20493 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20494 (message "Local setup has been refreshed"))
20495 (plain-list
20496 ;; At a plain list, with a double C-u argument, set
20497 ;; checkboxes of each item to "[-]", whereas a single one
20498 ;; will toggle their presence according to the state of the
20499 ;; first item in the list. Without an argument, repair the
20500 ;; list.
20501 (let* ((begin (org-element-property :contents-begin context))
20502 (beginm (move-marker (make-marker) begin))
20503 (struct (org-element-property :structure context))
20504 (old-struct (copy-tree struct))
20505 (first-box (save-excursion
20506 (goto-char begin)
20507 (looking-at org-list-full-item-re)
20508 (match-string-no-properties 3)))
20509 (new-box (cond ((equal arg '(16)) "[-]")
20510 ((equal arg '(4)) (unless first-box "[ ]"))
20511 ((equal first-box "[X]") "[ ]")
20512 (t "[X]"))))
20513 (cond
20514 (arg
20515 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20516 (org-list-get-all-items
20517 begin struct (org-list-prevs-alist struct))))
20518 ((and first-box (eq (point) begin))
20519 ;; For convenience, when point is at bol on the first
20520 ;; item of the list and no argument is provided, simply
20521 ;; toggle checkbox of that item, if any.
20522 (org-list-set-checkbox begin struct new-box)))
20523 (org-list-write-struct
20524 struct (org-list-parents-alist struct) old-struct)
20525 (org-update-checkbox-count-maybe)
20526 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20527 ((property-drawer node-property)
20528 (call-interactively 'org-property-action))
20529 ((radio-target target)
20530 (call-interactively 'org-update-radio-target-regexp))
20531 (statistics-cookie
20532 (call-interactively 'org-update-statistics-cookies))
20533 ((table table-cell table-row)
20534 ;; At a table, recalculate every field and align it. Also
20535 ;; send the table if necessary. If the table has
20536 ;; a `table.el' type, just give up. At a table row or
20537 ;; cell, maybe recalculate line but always align table.
20538 (if (eq (org-element-property :type context) 'table.el)
20539 (message "Use C-c ' to edit table.el tables")
20540 (let ((org-enable-table-editor t))
20541 (if (or (eq type 'table)
20542 ;; Check if point is at a TBLFM line.
20543 (and (eq type 'table-row)
20544 (= (point) (org-element-property :end context))))
20545 (save-excursion
20546 (if (org-at-TBLFM-p)
20547 (progn (require 'org-table)
20548 (org-table-calc-current-TBLFM))
20549 (goto-char (org-element-property :contents-begin context))
20550 (org-call-with-arg 'org-table-recalculate (or arg t))
20551 (orgtbl-send-table 'maybe)))
20552 (org-table-maybe-eval-formula)
20553 (cond (arg (call-interactively 'org-table-recalculate))
20554 ((org-table-maybe-recalculate-line))
20555 (t (org-table-align)))))))
20556 (timestamp (org-timestamp-change 0 'day))
20557 (otherwise
20558 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20559 (user-error
20560 "C-c C-c can do nothing useful at this location")))))))))
20562 (defun org-mode-restart ()
20563 (interactive)
20564 (let ((indent-status (org-bound-and-true-p org-indent-mode)))
20565 (funcall major-mode)
20566 (hack-local-variables)
20567 (when (and indent-status (not (org-bound-and-true-p org-indent-mode)))
20568 (org-indent-mode -1)))
20569 (message "%s restarted" major-mode))
20571 (defun org-kill-note-or-show-branches ()
20572 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20573 (interactive)
20574 (if (not org-finish-function)
20575 (progn
20576 (hide-subtree)
20577 (call-interactively 'show-branches))
20578 (let ((org-note-abort t))
20579 (funcall org-finish-function))))
20581 (defun org-open-line (n)
20582 "Insert a new row in tables, call `open-line' elsewhere.
20583 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
20584 (interactive "*p")
20585 (cond
20586 ((not org-special-ctrl-o)
20587 (open-line n))
20588 ((org-at-table-p)
20589 (org-table-insert-row))
20591 (open-line n))))
20593 (defun org-return (&optional indent)
20594 "Goto next table row or insert a newline.
20595 Calls `org-table-next-row' or `newline', depending on context.
20596 See the individual commands for more information."
20597 (interactive)
20598 (let (org-ts-what)
20599 (cond
20600 ((or (bobp) (org-in-src-block-p))
20601 (if indent (newline-and-indent) (newline)))
20602 ((org-at-table-p)
20603 (org-table-justify-field-maybe)
20604 (call-interactively 'org-table-next-row))
20605 ;; when `newline-and-indent' is called within a list, make sure
20606 ;; text moved stays inside the item.
20607 ((and (org-in-item-p) indent)
20608 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20609 (progn
20610 (save-match-data (newline))
20611 (org-indent-line-to (length (match-string 0))))
20612 (let ((ind (org-get-indentation)))
20613 (newline)
20614 (if (org-looking-back org-list-end-re)
20615 (org-indent-line)
20616 (org-indent-line-to ind)))))
20617 ((and org-return-follows-link
20618 (org-at-timestamp-p t)
20619 (not (eq org-ts-what 'after)))
20620 (org-follow-timestamp-link))
20621 ((and org-return-follows-link
20622 (let ((tprop (get-text-property (point) 'face)))
20623 (or (eq tprop 'org-link)
20624 (and (listp tprop) (memq 'org-link tprop)))))
20625 (call-interactively 'org-open-at-point))
20626 ((and (org-at-heading-p)
20627 (looking-at
20628 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20629 (org-show-entry)
20630 (end-of-line 1)
20631 (newline))
20632 (t (if indent (newline-and-indent) (newline))))))
20634 (defun org-return-indent ()
20635 "Goto next table row or insert a newline and indent.
20636 Calls `org-table-next-row' or `newline-and-indent', depending on
20637 context. See the individual commands for more information."
20638 (interactive)
20639 (org-return t))
20641 (defun org-ctrl-c-star ()
20642 "Compute table, or change heading status of lines.
20643 Calls `org-table-recalculate' or `org-toggle-heading',
20644 depending on context."
20645 (interactive)
20646 (cond
20647 ((org-at-table-p)
20648 (call-interactively 'org-table-recalculate))
20650 ;; Convert all lines in region to list items
20651 (call-interactively 'org-toggle-heading))))
20653 (defun org-ctrl-c-minus ()
20654 "Insert separator line in table or modify bullet status of line.
20655 Also turns a plain line or a region of lines into list items.
20656 Calls `org-table-insert-hline', `org-toggle-item', or
20657 `org-cycle-list-bullet', depending on context."
20658 (interactive)
20659 (cond
20660 ((org-at-table-p)
20661 (call-interactively 'org-table-insert-hline))
20662 ((org-region-active-p)
20663 (call-interactively 'org-toggle-item))
20664 ((org-in-item-p)
20665 (call-interactively 'org-cycle-list-bullet))
20667 (call-interactively 'org-toggle-item))))
20669 (defun org-toggle-item (arg)
20670 "Convert headings or normal lines to items, items to normal lines.
20671 If there is no active region, only the current line is considered.
20673 If the first non blank line in the region is a headline, convert
20674 all headlines to items, shifting text accordingly.
20676 If it is an item, convert all items to normal lines.
20678 If it is normal text, change region into a list of items.
20679 With a prefix argument ARG, change the region in a single item."
20680 (interactive "P")
20681 (let ((shift-text
20682 (function
20683 ;; Shift text in current section to IND, from point to END.
20684 ;; The function leaves point to END line.
20685 (lambda (ind end)
20686 (let ((min-i 1000) (end (copy-marker end)))
20687 ;; First determine the minimum indentation (MIN-I) of
20688 ;; the text.
20689 (save-excursion
20690 (catch 'exit
20691 (while (< (point) end)
20692 (let ((i (org-get-indentation)))
20693 (cond
20694 ;; Skip blank lines and inline tasks.
20695 ((looking-at "^[ \t]*$"))
20696 ((looking-at org-outline-regexp-bol))
20697 ;; We can't find less than 0 indentation.
20698 ((zerop i) (throw 'exit (setq min-i 0)))
20699 ((< i min-i) (setq min-i i))))
20700 (forward-line))))
20701 ;; Then indent each line so that a line indented to
20702 ;; MIN-I becomes indented to IND. Ignore blank lines
20703 ;; and inline tasks in the process.
20704 (let ((delta (- ind min-i)))
20705 (while (< (point) end)
20706 (unless (or (looking-at "^[ \t]*$")
20707 (looking-at org-outline-regexp-bol))
20708 (org-indent-line-to (+ (org-get-indentation) delta)))
20709 (forward-line)))))))
20710 (skip-blanks
20711 (function
20712 ;; Return beginning of first non-blank line, starting from
20713 ;; line at POS.
20714 (lambda (pos)
20715 (save-excursion
20716 (goto-char pos)
20717 (skip-chars-forward " \r\t\n")
20718 (point-at-bol)))))
20719 beg end)
20720 ;; Determine boundaries of changes.
20721 (if (org-region-active-p)
20722 (setq beg (funcall skip-blanks (region-beginning))
20723 end (copy-marker (region-end)))
20724 (setq beg (funcall skip-blanks (point-at-bol))
20725 end (copy-marker (point-at-eol))))
20726 ;; Depending on the starting line, choose an action on the text
20727 ;; between BEG and END.
20728 (org-with-limited-levels
20729 (save-excursion
20730 (goto-char beg)
20731 (cond
20732 ;; Case 1. Start at an item: de-itemize. Note that it only
20733 ;; happens when a region is active: `org-ctrl-c-minus'
20734 ;; would call `org-cycle-list-bullet' otherwise.
20735 ((org-at-item-p)
20736 (while (< (point) end)
20737 (when (org-at-item-p)
20738 (skip-chars-forward " \t")
20739 (delete-region (point) (match-end 0)))
20740 (forward-line)))
20741 ;; Case 2. Start at an heading: convert to items.
20742 ((org-at-heading-p)
20743 (let* ((bul (org-list-bullet-string "-"))
20744 (bul-len (length bul))
20745 (done (org-entry-is-done-p))
20746 (todo (org-entry-is-todo-p))
20747 ;; Indentation of the first heading. It should be
20748 ;; relative to the indentation of its parent, if any.
20749 (start-ind (save-excursion
20750 (cond
20751 ((not org-adapt-indentation) 0)
20752 ((not (outline-previous-heading)) 0)
20753 (t (length (match-string 0))))))
20754 ;; Level of first heading. Further headings will be
20755 ;; compared to it to determine hierarchy in the list.
20756 (ref-level (org-reduced-level (org-outline-level))))
20757 (when (or done todo) (org-todo ""))
20758 (while (< (point) end)
20759 (let* ((level (org-reduced-level (org-outline-level)))
20760 (delta (max 0 (- level ref-level))))
20761 ;; If current headline is less indented than the first
20762 ;; one, set it as reference, in order to preserve
20763 ;; subtrees.
20764 (when (< level ref-level) (setq ref-level level))
20765 (replace-match bul t t)
20766 (org-indent-line-to (+ start-ind (* delta bul-len)))
20767 (when (or done todo)
20768 (let* ((struct (org-list-struct))
20769 (old (copy-tree struct)))
20770 (org-list-set-checkbox (line-beginning-position)
20771 struct
20772 (if done "[X]" "[ ]"))
20773 (org-list-write-struct struct
20774 (org-list-parents-alist struct)
20775 old)))
20776 ;; Ensure all text down to END (or SECTION-END) belongs
20777 ;; to the newly created item.
20778 (let ((section-end (save-excursion
20779 (or (outline-next-heading) (point)))))
20780 (forward-line)
20781 (funcall shift-text
20782 (+ start-ind (* (1+ delta) bul-len))
20783 (min end section-end)))))))
20784 ;; Case 3. Normal line with ARG: make the first line of region
20785 ;; an item, and shift indentation of others lines to
20786 ;; set them as item's body.
20787 (arg (let* ((bul (org-list-bullet-string "-"))
20788 (bul-len (length bul))
20789 (ref-ind (org-get-indentation)))
20790 (skip-chars-forward " \t")
20791 (insert bul)
20792 (forward-line)
20793 (while (< (point) end)
20794 ;; Ensure that lines less indented than first one
20795 ;; still get included in item body.
20796 (funcall shift-text
20797 (+ ref-ind bul-len)
20798 (min end (save-excursion (or (outline-next-heading)
20799 (point)))))
20800 (forward-line))))
20801 ;; Case 4. Normal line without ARG: turn each non-item line
20802 ;; into an item.
20804 (while (< (point) end)
20805 (unless (or (org-at-heading-p) (org-at-item-p))
20806 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20807 (replace-match
20808 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20809 (forward-line))))))))
20811 (defun org-toggle-heading (&optional nstars)
20812 "Convert headings to normal text, or items or text to headings.
20813 If there is no active region, only convert the current line.
20815 With a \\[universal-argument] prefix, convert the whole list at
20816 point into heading.
20818 In a region:
20820 - If the first non blank line is a headline, remove the stars
20821 from all headlines in the region.
20823 - If it is a normal line, turn each and every normal line (i.e.,
20824 not an heading or an item) in the region into headings. If you
20825 want to convert only the first line of this region, use one
20826 universal prefix argument.
20828 - If it is a plain list item, turn all plain list items into headings.
20830 When converting a line into a heading, the number of stars is chosen
20831 such that the lines become children of the current entry. However,
20832 when a numeric prefix argument is given, its value determines the
20833 number of stars to add."
20834 (interactive "P")
20835 (let ((skip-blanks
20836 (function
20837 ;; Return beginning of first non-blank line, starting from
20838 ;; line at POS.
20839 (lambda (pos)
20840 (save-excursion
20841 (goto-char pos)
20842 (while (org-at-comment-p) (forward-line))
20843 (skip-chars-forward " \r\t\n")
20844 (point-at-bol)))))
20845 beg end toggled)
20846 ;; Determine boundaries of changes. If a universal prefix has
20847 ;; been given, put the list in a region. If region ends at a bol,
20848 ;; do not consider the last line to be in the region.
20850 (when (and current-prefix-arg (org-at-item-p))
20851 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20852 (org-mark-element))
20854 (if (org-region-active-p)
20855 (setq beg (funcall skip-blanks (region-beginning))
20856 end (copy-marker (save-excursion
20857 (goto-char (region-end))
20858 (if (bolp) (point) (point-at-eol)))))
20859 (setq beg (funcall skip-blanks (point-at-bol))
20860 end (copy-marker (point-at-eol))))
20861 ;; Ensure inline tasks don't count as headings.
20862 (org-with-limited-levels
20863 (save-excursion
20864 (goto-char beg)
20865 (cond
20866 ;; Case 1. Started at an heading: de-star headings.
20867 ((org-at-heading-p)
20868 (while (< (point) end)
20869 (when (org-at-heading-p t)
20870 (looking-at org-outline-regexp) (replace-match "")
20871 (setq toggled t))
20872 (forward-line)))
20873 ;; Case 2. Started at an item: change items into headlines.
20874 ;; One star will be added by `org-list-to-subtree'.
20875 ((org-at-item-p)
20876 (let* ((stars (make-string
20877 ;; subtract the star that will be added again by
20878 ;; `org-list-to-subtree'
20879 (if (numberp nstars) (1- nstars)
20880 (or (org-current-level) 0))
20881 ?*))
20882 (add-stars
20883 (cond (nstars "") ; stars from prefix only
20884 ((equal stars "") "") ; before first heading
20885 (org-odd-levels-only "*") ; inside heading, odd
20886 (t "")))) ; inside heading, oddeven
20887 (while (< (point) end)
20888 (when (org-at-item-p)
20889 ;; Pay attention to cases when region ends before list.
20890 (let* ((struct (org-list-struct))
20891 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20892 (save-restriction
20893 (narrow-to-region (point) list-end)
20894 (insert
20895 (org-list-to-subtree
20896 (org-list-parse-list t)
20897 '(:istart (concat stars add-stars (funcall get-stars depth))
20898 :icount (concat stars add-stars (funcall get-stars depth)))))))
20899 (setq toggled t))
20900 (forward-line))))
20901 ;; Case 3. Started at normal text: make every line an heading,
20902 ;; skipping headlines and items.
20903 (t (let* ((stars
20904 (make-string
20905 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20906 (add-stars
20907 (cond (nstars "") ; stars from prefix only
20908 ((equal stars "") "*") ; before first heading
20909 (org-odd-levels-only "**") ; inside heading, odd
20910 (t "*"))) ; inside heading, oddeven
20911 (rpl (concat stars add-stars " "))
20912 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20913 (while (< (point) (if (equal nstars '(4)) lend end))
20914 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20915 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20916 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20917 (forward-line)))))))
20918 (unless toggled (message "Cannot toggle heading from here"))))
20920 (defun org-meta-return (&optional arg)
20921 "Insert a new heading or wrap a region in a table.
20922 Calls `org-insert-heading' or `org-table-wrap-region', depending
20923 on context. See the individual commands for more information."
20924 (interactive "P")
20925 (org-check-before-invisible-edit 'insert)
20926 (or (run-hook-with-args-until-success 'org-metareturn-hook)
20927 (let* ((element (org-element-at-point))
20928 (type (org-element-type element)))
20929 (when (eq type 'table-row)
20930 (setq element (org-element-property :parent element))
20931 (setq type 'table))
20932 (if (and (eq type 'table)
20933 (eq (org-element-property :type element) 'org)
20934 (>= (point) (org-element-property :contents-begin element))
20935 (< (point) (org-element-property :contents-end element)))
20936 (call-interactively 'org-table-wrap-region)
20937 (call-interactively 'org-insert-heading)))))
20939 ;;; Menu entries
20941 (defsubst org-in-subtree-not-table-p ()
20942 "Are we in a subtree and not in a table?"
20943 (and (not (org-before-first-heading-p))
20944 (not (org-at-table-p))))
20946 ;; Define the Org-mode menus
20947 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20948 '("Tbl"
20949 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20950 ["Next Field" org-cycle (org-at-table-p)]
20951 ["Previous Field" org-shifttab (org-at-table-p)]
20952 ["Next Row" org-return (org-at-table-p)]
20953 "--"
20954 ["Blank Field" org-table-blank-field (org-at-table-p)]
20955 ["Edit Field" org-table-edit-field (org-at-table-p)]
20956 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20957 "--"
20958 ("Column"
20959 ["Move Column Left" org-metaleft (org-at-table-p)]
20960 ["Move Column Right" org-metaright (org-at-table-p)]
20961 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20962 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20963 ("Row"
20964 ["Move Row Up" org-metaup (org-at-table-p)]
20965 ["Move Row Down" org-metadown (org-at-table-p)]
20966 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20967 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20968 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20969 "--"
20970 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20971 ("Rectangle"
20972 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20973 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20974 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20975 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20976 "--"
20977 ("Calculate"
20978 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20979 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20980 ["Edit Formulas" org-edit-special (org-at-table-p)]
20981 "--"
20982 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20983 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20984 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20985 "--"
20986 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20987 "--"
20988 ["Sum Column/Rectangle" org-table-sum
20989 (or (org-at-table-p) (org-region-active-p))]
20990 ["Which Column?" org-table-current-column (org-at-table-p)])
20991 ["Debug Formulas"
20992 org-table-toggle-formula-debugger
20993 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20994 ["Show Col/Row Numbers"
20995 org-table-toggle-coordinate-overlays
20996 :style toggle
20997 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20998 "--"
20999 ["Create" org-table-create (and (not (org-at-table-p))
21000 org-enable-table-editor)]
21001 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21002 ["Import from File" org-table-import (not (org-at-table-p))]
21003 ["Export to File" org-table-export (org-at-table-p)]
21004 "--"
21005 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
21007 (easy-menu-define org-org-menu org-mode-map "Org menu"
21008 '("Org"
21009 ("Show/Hide"
21010 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21011 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21012 ["Sparse Tree..." org-sparse-tree t]
21013 ["Reveal Context" org-reveal t]
21014 ["Show All" show-all t]
21015 "--"
21016 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21017 "--"
21018 ["New Heading" org-insert-heading t]
21019 ("Navigate Headings"
21020 ["Up" outline-up-heading t]
21021 ["Next" outline-next-visible-heading t]
21022 ["Previous" outline-previous-visible-heading t]
21023 ["Next Same Level" outline-forward-same-level t]
21024 ["Previous Same Level" outline-backward-same-level t]
21025 "--"
21026 ["Jump" org-goto t])
21027 ("Edit Structure"
21028 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21029 "--"
21030 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
21031 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
21032 "--"
21033 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21034 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21035 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21036 "--"
21037 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21038 "--"
21039 ["Copy visible text" org-copy-visible t]
21040 "--"
21041 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21042 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21043 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21044 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21045 "--"
21046 ["Sort Region/Children" org-sort t]
21047 "--"
21048 ["Convert to odd levels" org-convert-to-odd-levels t]
21049 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21050 ("Editing"
21051 ["Emphasis..." org-emphasize t]
21052 ["Edit Source Example" org-edit-special t]
21053 "--"
21054 ["Footnote new/jump" org-footnote-action t]
21055 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21056 ("Archive"
21057 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21058 "--"
21059 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
21060 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21061 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21063 "--"
21064 ("Hyperlinks"
21065 ["Store Link (Global)" org-store-link t]
21066 ["Find existing link to here" org-occur-link-in-agenda-files t]
21067 ["Insert Link" org-insert-link t]
21068 ["Follow Link" org-open-at-point t]
21069 "--"
21070 ["Next link" org-next-link t]
21071 ["Previous link" org-previous-link t]
21072 "--"
21073 ["Descriptive Links"
21074 org-toggle-link-display
21075 :style radio
21076 :selected org-descriptive-links
21078 ["Literal Links"
21079 org-toggle-link-display
21080 :style radio
21081 :selected (not org-descriptive-links)])
21082 "--"
21083 ("TODO Lists"
21084 ["TODO/DONE/-" org-todo t]
21085 ("Select keyword"
21086 ["Next keyword" org-shiftright (org-at-heading-p)]
21087 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21088 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21089 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21090 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21091 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21092 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21093 "--"
21094 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21095 :selected org-enforce-todo-dependencies :style toggle :active t]
21096 "Settings for tree at point"
21097 ["Do Children sequentially" org-toggle-ordered-property :style radio
21098 :selected (org-entry-get nil "ORDERED")
21099 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21100 ["Do Children parallel" org-toggle-ordered-property :style radio
21101 :selected (not (org-entry-get nil "ORDERED"))
21102 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21103 "--"
21104 ["Set Priority" org-priority t]
21105 ["Priority Up" org-shiftup t]
21106 ["Priority Down" org-shiftdown t]
21107 "--"
21108 ["Get news from all feeds" org-feed-update-all t]
21109 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21110 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21111 ("TAGS and Properties"
21112 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21113 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21114 "--"
21115 ["Set property" org-set-property (not (org-before-first-heading-p))]
21116 ["Column view of properties" org-columns t]
21117 ["Insert Column View DBlock" org-insert-columns-dblock t])
21118 ("Dates and Scheduling"
21119 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21120 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21121 ("Change Date"
21122 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21123 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21124 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21125 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21126 ["Compute Time Range" org-evaluate-time-range t]
21127 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21128 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21129 "--"
21130 ["Custom time format" org-toggle-time-stamp-overlays
21131 :style radio :selected org-display-custom-times]
21132 "--"
21133 ["Goto Calendar" org-goto-calendar t]
21134 ["Date from Calendar" org-date-from-calendar t]
21135 "--"
21136 ["Start/Restart Timer" org-timer-start t]
21137 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21138 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21139 ["Insert Timer String" org-timer t]
21140 ["Insert Timer Item" org-timer-item t])
21141 ("Logging work"
21142 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21143 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21144 ["Clock out" org-clock-out t]
21145 ["Clock cancel" org-clock-cancel t]
21146 "--"
21147 ["Mark as default task" org-clock-mark-default-task t]
21148 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21149 ["Goto running clock" org-clock-goto t]
21150 "--"
21151 ["Display times" org-clock-display t]
21152 ["Create clock table" org-clock-report t]
21153 "--"
21154 ["Record DONE time"
21155 (progn (setq org-log-done (not org-log-done))
21156 (message "Switching to %s will %s record a timestamp"
21157 (car org-done-keywords)
21158 (if org-log-done "automatically" "not")))
21159 :style toggle :selected org-log-done])
21160 "--"
21161 ["Agenda Command..." org-agenda t]
21162 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21163 ("File List for Agenda")
21164 ("Special views current file"
21165 ["TODO Tree" org-show-todo-tree t]
21166 ["Check Deadlines" org-check-deadlines t]
21167 ["Timeline" org-timeline t]
21168 ["Tags/Property tree" org-match-sparse-tree t])
21169 "--"
21170 ["Export/Publish..." org-export-dispatch t]
21171 ("LaTeX"
21172 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21173 :selected org-cdlatex-mode]
21174 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21175 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21176 ["Modify math symbol" org-cdlatex-math-modify
21177 (org-inside-LaTeX-fragment-p)]
21178 ["Insert citation" org-reftex-citation t]
21179 "--"
21180 ["Template for BEAMER" (org-beamer-insert-options-template) t])
21181 "--"
21182 ("MobileOrg"
21183 ["Push Files and Views" org-mobile-push t]
21184 ["Get Captured and Flagged" org-mobile-pull t]
21185 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21186 "--"
21187 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21188 "--"
21189 ("Documentation"
21190 ["Show Version" org-version t]
21191 ["Info Documentation" org-info t])
21192 ("Customize"
21193 ["Browse Org Group" org-customize t]
21194 "--"
21195 ["Expand This Menu" org-create-customize-menu
21196 (fboundp 'customize-menu-create)])
21197 ["Send bug report" org-submit-bug-report t]
21198 "--"
21199 ("Refresh/Reload"
21200 ["Refresh setup current buffer" org-mode-restart t]
21201 ["Reload Org (after update)" org-reload t]
21202 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21205 (defun org-info (&optional node)
21206 "Read documentation for Org-mode in the info system.
21207 With optional NODE, go directly to that node."
21208 (interactive)
21209 (info (format "(org)%s" (or node ""))))
21211 ;;;###autoload
21212 (defun org-submit-bug-report ()
21213 "Submit a bug report on Org-mode via mail.
21215 Don't hesitate to report any problems or inaccurate documentation.
21217 If you don't have setup sending mail from (X)Emacs, please copy the
21218 output buffer into your mail program, as it gives us important
21219 information about your Org-mode version and configuration."
21220 (interactive)
21221 (require 'reporter)
21222 (org-load-modules-maybe)
21223 (org-require-autoloaded-modules)
21224 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21225 (reporter-submit-bug-report
21226 "emacs-orgmode@gnu.org"
21227 (org-version nil 'full)
21228 (let (list)
21229 (save-window-excursion
21230 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21231 (delete-other-windows)
21232 (erase-buffer)
21233 (insert "You are about to submit a bug report to the Org-mode mailing list.
21235 We would like to add your full Org-mode and Outline configuration to the
21236 bug report. This greatly simplifies the work of the maintainer and
21237 other experts on the mailing list.
21239 HOWEVER, some variables you have customized may contain private
21240 information. The names of customers, colleagues, or friends, might
21241 appear in the form of file names, tags, todo states, or search strings.
21242 If you answer yes to the prompt, you might want to check and remove
21243 such private information before sending the email.")
21244 (add-text-properties (point-min) (point-max) '(face org-warning))
21245 (when (yes-or-no-p "Include your Org-mode configuration ")
21246 (mapatoms
21247 (lambda (v)
21248 (and (boundp v)
21249 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21250 (or (and (symbol-value v)
21251 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21252 (and
21253 (get v 'custom-type) (get v 'standard-value)
21254 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21255 (push v list)))))
21256 (kill-buffer (get-buffer "*Warn about privacy*"))
21257 list))
21258 nil nil
21259 "Remember to cover the basics, that is, what you expected to happen and
21260 what in fact did happen. You don't know how to make a good report? See
21262 http://orgmode.org/manual/Feedback.html#Feedback
21264 Your bug report will be posted to the Org-mode mailing list.
21265 ------------------------------------------------------------------------")
21266 (save-excursion
21267 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21268 (replace-match "\\1Bug: \\3 [\\2]")))))
21271 (defun org-install-agenda-files-menu ()
21272 (let ((bl (buffer-list)))
21273 (save-excursion
21274 (while bl
21275 (set-buffer (pop bl))
21276 (if (derived-mode-p 'org-mode) (setq bl nil)))
21277 (when (derived-mode-p 'org-mode)
21278 (easy-menu-change
21279 '("Org") "File List for Agenda"
21280 (append
21281 (list
21282 ["Edit File List" (org-edit-agenda-file-list) t]
21283 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21284 ["Remove Current File from List" org-remove-file t]
21285 ["Cycle through agenda files" org-cycle-agenda-files t]
21286 ["Occur in all agenda files" org-occur-in-agenda-files t]
21287 "--")
21288 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21290 ;;;; Documentation
21292 (defun org-require-autoloaded-modules ()
21293 (interactive)
21294 (mapc 'require
21295 '(org-agenda org-archive org-attach org-clock org-colview org-id
21296 org-table org-timer)))
21298 ;;;###autoload
21299 (defun org-reload (&optional uncompiled)
21300 "Reload all org lisp files.
21301 With prefix arg UNCOMPILED, load the uncompiled versions."
21302 (interactive "P")
21303 (require 'loadhist)
21304 (let* ((org-dir (org-find-library-dir "org"))
21305 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21306 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21307 (remove-re (mapconcat 'identity
21308 (mapcar (lambda (f) (concat "^" f "$"))
21309 (list (if (featurep 'xemacs)
21310 "org-colview"
21311 "org-colview-xemacs")
21312 "org" "org-loaddefs" "org-version"))
21313 "\\|"))
21314 (feats (delete-dups
21315 (mapcar 'file-name-sans-extension
21316 (mapcar 'file-name-nondirectory
21317 (delq nil
21318 (mapcar 'feature-file
21319 features))))))
21320 (lfeat (append
21321 (sort
21322 (setq feats
21323 (delq nil (mapcar
21324 (lambda (f)
21325 (if (and (string-match feature-re f)
21326 (not (string-match remove-re f)))
21327 f nil))
21328 feats)))
21329 'string-lessp)
21330 (list "org-version" "org")))
21331 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21332 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21333 load-uncore load-misses)
21334 (setq load-misses
21335 (delq 't
21336 (mapcar (lambda (f)
21337 (or (org-load-noerror-mustsuffix (concat org-dir f))
21338 (and (string= org-dir contrib-dir)
21339 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21340 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21341 (add-to-list 'load-uncore f 'append)
21344 lfeat)))
21345 (if load-uncore
21346 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21347 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21348 (if load-misses
21349 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21350 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21351 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21353 ;;;###autoload
21354 (defun org-customize ()
21355 "Call the customize function with org as argument."
21356 (interactive)
21357 (org-load-modules-maybe)
21358 (org-require-autoloaded-modules)
21359 (customize-browse 'org))
21361 (defun org-create-customize-menu ()
21362 "Create a full customization menu for Org-mode, insert it into the menu."
21363 (interactive)
21364 (org-load-modules-maybe)
21365 (org-require-autoloaded-modules)
21366 (if (fboundp 'customize-menu-create)
21367 (progn
21368 (easy-menu-change
21369 '("Org") "Customize"
21370 `(["Browse Org group" org-customize t]
21371 "--"
21372 ,(customize-menu-create 'org)
21373 ["Set" Custom-set t]
21374 ["Save" Custom-save t]
21375 ["Reset to Current" Custom-reset-current t]
21376 ["Reset to Saved" Custom-reset-saved t]
21377 ["Reset to Standard Settings" Custom-reset-standard t]))
21378 (message "\"Org\"-menu now contains full customization menu"))
21379 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21381 ;;;; Miscellaneous stuff
21383 ;;; Generally useful functions
21385 (defun org-get-at-bol (property)
21386 "Get text property PROPERTY at beginning of line."
21387 (get-text-property (point-at-bol) property))
21389 (defun org-find-text-property-in-string (prop s)
21390 "Return the first non-nil value of property PROP in string S."
21391 (or (get-text-property 0 prop s)
21392 (get-text-property (or (next-single-property-change 0 prop s) 0)
21393 prop s)))
21395 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21396 "Display the given MESSAGE as a warning."
21397 (if (fboundp 'display-warning)
21398 (display-warning 'org message
21399 (if (featurep 'xemacs) 'warning :warning))
21400 (let ((buf (get-buffer-create "*Org warnings*")))
21401 (with-current-buffer buf
21402 (goto-char (point-max))
21403 (insert "Warning (Org): " message)
21404 (unless (bolp)
21405 (newline)))
21406 (display-buffer buf)
21407 (sit-for 0))))
21409 (defun org-eval (form)
21410 "Eval FORM and return result."
21411 (condition-case error
21412 (eval form)
21413 (error (format "%%![Error: %s]" error))))
21415 (defun org-in-clocktable-p ()
21416 "Check if the cursor is in a clocktable."
21417 (let ((pos (point)) start)
21418 (save-excursion
21419 (end-of-line 1)
21420 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21421 (setq start (match-beginning 0))
21422 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21423 (>= (match-end 0) pos)
21424 start))))
21426 (defun org-in-commented-line ()
21427 "Is point in a line starting with `#'?"
21428 (equal (char-after (point-at-bol)) ?#))
21430 (defun org-in-indented-comment-line ()
21431 "Is point in a line starting with `#' after some white space?"
21432 (save-excursion
21433 (save-match-data
21434 (goto-char (point-at-bol))
21435 (looking-at "[ \t]*#"))))
21437 (defun org-in-verbatim-emphasis ()
21438 (save-match-data
21439 (and (org-in-regexp org-emph-re 2)
21440 (>= (point) (match-beginning 3))
21441 (<= (point) (match-end 4))
21442 (member (match-string 3) '("=" "~")))))
21444 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21445 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21446 (if (and marker (marker-buffer marker)
21447 (buffer-live-p (marker-buffer marker)))
21448 (progn
21449 (org-pop-to-buffer-same-window (marker-buffer marker))
21450 (if (or (> marker (point-max)) (< marker (point-min)))
21451 (widen))
21452 (goto-char marker)
21453 (org-show-context 'org-goto))
21454 (if bookmark
21455 (bookmark-jump bookmark)
21456 (error "Cannot find location"))))
21458 (defun org-quote-csv-field (s)
21459 "Quote field for inclusion in CSV material."
21460 (if (string-match "[\",]" s)
21461 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21464 (defun org-force-self-insert (N)
21465 "Needed to enforce self-insert under remapping."
21466 (interactive "p")
21467 (self-insert-command N))
21469 (defun org-string-width (s)
21470 "Compute width of string, ignoring invisible characters.
21471 This ignores character with invisibility property `org-link', and also
21472 characters with property `org-cwidth', because these will become invisible
21473 upon the next fontification round."
21474 (let (b l)
21475 (when (or (eq t buffer-invisibility-spec)
21476 (assq 'org-link buffer-invisibility-spec))
21477 (while (setq b (text-property-any 0 (length s)
21478 'invisible 'org-link s))
21479 (setq s (concat (substring s 0 b)
21480 (substring s (or (next-single-property-change
21481 b 'invisible s) (length s)))))))
21482 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21483 (setq s (concat (substring s 0 b)
21484 (substring s (or (next-single-property-change
21485 b 'org-cwidth s) (length s))))))
21486 (setq l (string-width s) b -1)
21487 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21488 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21491 (defun org-shorten-string (s maxlength)
21492 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21493 If the string is shorter or has length MAXLENGTH, just return the
21494 original string. If it is longer, the functions finds a space in the
21495 string, breaks this string off at that locations and adds three dots
21496 as ellipsis. Including the ellipsis, the string will not be longer
21497 than MAXLENGTH. If finding a good breaking point in the string does
21498 not work, the string is just chopped off in the middle of a word
21499 if necessary."
21500 (if (<= (length s) maxlength)
21502 (let* ((n (max (- maxlength 4) 1))
21503 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21504 (if (string-match re s)
21505 (concat (match-string 1 s) "...")
21506 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21508 (defun org-get-indentation (&optional line)
21509 "Get the indentation of the current line, interpreting tabs.
21510 When LINE is given, assume it represents a line and compute its indentation."
21511 (if line
21512 (if (string-match "^ *" (org-remove-tabs line))
21513 (match-end 0))
21514 (save-excursion
21515 (beginning-of-line 1)
21516 (skip-chars-forward " \t")
21517 (current-column))))
21519 (defun org-get-string-indentation (s)
21520 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21521 (let ((n -1) (i 0) (w tab-width) c)
21522 (catch 'exit
21523 (while (< (setq n (1+ n)) (length s))
21524 (setq c (aref s n))
21525 (cond ((= c ?\ ) (setq i (1+ i)))
21526 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21527 (t (throw 'exit t)))))
21530 (defun org-remove-tabs (s &optional width)
21531 "Replace tabulators in S with spaces.
21532 Assumes that s is a single line, starting in column 0."
21533 (setq width (or width tab-width))
21534 (while (string-match "\t" s)
21535 (setq s (replace-match
21536 (make-string
21537 (- (* width (/ (+ (match-beginning 0) width) width))
21538 (match-beginning 0)) ?\ )
21539 t t s)))
21542 (defun org-fix-indentation (line ind)
21543 "Fix indentation in LINE.
21544 IND is a cons cell with target and minimum indentation.
21545 If the current indentation in LINE is smaller than the minimum,
21546 leave it alone. If it is larger than ind, set it to the target."
21547 (let* ((l (org-remove-tabs line))
21548 (i (org-get-indentation l))
21549 (i1 (car ind)) (i2 (cdr ind)))
21550 (if (>= i i2) (setq l (substring line i2)))
21551 (if (> i1 0)
21552 (concat (make-string i1 ?\ ) l)
21553 l)))
21555 (defun org-remove-indentation (code &optional n)
21556 "Remove the maximum common indentation from the lines in CODE.
21557 N may optionally be the number of spaces to remove."
21558 (with-temp-buffer
21559 (insert code)
21560 (org-do-remove-indentation n)
21561 (buffer-string)))
21563 (defun org-do-remove-indentation (&optional n)
21564 "Remove the maximum common indentation from the buffer."
21565 (untabify (point-min) (point-max))
21566 (let ((min 10000) re)
21567 (if n
21568 (setq min n)
21569 (goto-char (point-min))
21570 (while (re-search-forward "^ *[^ \n]" nil t)
21571 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21572 (unless (or (= min 0) (= min 10000))
21573 (setq re (format "^ \\{%d\\}" min))
21574 (goto-char (point-min))
21575 (while (re-search-forward re nil t)
21576 (replace-match "")
21577 (end-of-line 1))
21578 min)))
21580 (defun org-fill-template (template alist)
21581 "Find each %key of ALIST in TEMPLATE and replace it."
21582 (let ((case-fold-search nil)
21583 entry key value)
21584 (setq alist (sort (copy-sequence alist)
21585 (lambda (a b) (< (length (car a)) (length (car b))))))
21586 (while (setq entry (pop alist))
21587 (setq template
21588 (replace-regexp-in-string
21589 (concat "%" (regexp-quote (car entry)))
21590 (or (cdr entry) "") template t t)))
21591 template))
21593 (defun org-base-buffer (buffer)
21594 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21595 (if (not buffer)
21596 buffer
21597 (or (buffer-base-buffer buffer)
21598 buffer)))
21600 (defun org-trim (s)
21601 "Remove whitespace at beginning and end of string."
21602 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
21603 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
21606 (defun org-wrap (string &optional width lines)
21607 "Wrap string to either a number of lines, or a width in characters.
21608 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21609 that costs. If there is a word longer than WIDTH, the text is actually
21610 wrapped to the length of that word.
21611 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21612 many lines, whatever width that takes.
21613 The return value is a list of lines, without newlines at the end."
21614 (let* ((words (org-split-string string "[ \t\n]+"))
21615 (maxword (apply 'max (mapcar 'org-string-width words)))
21616 w ll)
21617 (cond (width
21618 (org-do-wrap words (max maxword width)))
21619 (lines
21620 (setq w maxword)
21621 (setq ll (org-do-wrap words maxword))
21622 (if (<= (length ll) lines)
21624 (setq ll words)
21625 (while (> (length ll) lines)
21626 (setq w (1+ w))
21627 (setq ll (org-do-wrap words w)))
21628 ll))
21629 (t (error "Cannot wrap this")))))
21631 (defun org-do-wrap (words width)
21632 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21633 (let (lines line)
21634 (while words
21635 (setq line (pop words))
21636 (while (and words (< (+ (length line) (length (car words))) width))
21637 (setq line (concat line " " (pop words))))
21638 (setq lines (push line lines)))
21639 (nreverse lines)))
21641 (defun org-split-string (string &optional separators)
21642 "Splits STRING into substrings at SEPARATORS.
21643 No empty strings are returned if there are matches at the beginning
21644 and end of string."
21645 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21646 (start 0)
21647 notfirst
21648 (list nil))
21649 (while (and (string-match rexp string
21650 (if (and notfirst
21651 (= start (match-beginning 0))
21652 (< start (length string)))
21653 (1+ start) start))
21654 (< (match-beginning 0) (length string)))
21655 (setq notfirst t)
21656 (or (eq (match-beginning 0) 0)
21657 (and (eq (match-beginning 0) (match-end 0))
21658 (eq (match-beginning 0) start))
21659 (setq list
21660 (cons (substring string start (match-beginning 0))
21661 list)))
21662 (setq start (match-end 0)))
21663 (or (eq start (length string))
21664 (setq list
21665 (cons (substring string start)
21666 list)))
21667 (nreverse list)))
21669 (defun org-quote-vert (s)
21670 "Replace \"|\" with \"\\vert\"."
21671 (while (string-match "|" s)
21672 (setq s (replace-match "\\vert" t t s)))
21675 (defun org-uuidgen-p (s)
21676 "Is S an ID created by UUIDGEN?"
21677 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21679 (defun org-in-src-block-p (&optional inside)
21680 "Whether point is in a code source block.
21681 When INSIDE is non-nil, don't consider we are within a src block
21682 when point is at #+BEGIN_SRC or #+END_SRC."
21683 (let ((case-fold-search t) ov)
21684 (or (and (setq ov (overlays-at (point)))
21685 (memq 'org-block-background
21686 (overlay-properties (car ov))))
21687 (and (not inside)
21688 (save-match-data
21689 (save-excursion
21690 (beginning-of-line)
21691 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21693 (defun org-context ()
21694 "Return a list of contexts of the current cursor position.
21695 If several contexts apply, all are returned.
21696 Each context entry is a list with a symbol naming the context, and
21697 two positions indicating start and end of the context. Possible
21698 contexts are:
21700 :headline anywhere in a headline
21701 :headline-stars on the leading stars in a headline
21702 :todo-keyword on a TODO keyword (including DONE) in a headline
21703 :tags on the TAGS in a headline
21704 :priority on the priority cookie in a headline
21705 :item on the first line of a plain list item
21706 :item-bullet on the bullet/number of a plain list item
21707 :checkbox on the checkbox in a plain list item
21708 :table in an org-mode table
21709 :table-special on a special filed in a table
21710 :table-table in a table.el table
21711 :clocktable in a clocktable
21712 :src-block in a source block
21713 :link on a hyperlink
21714 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
21715 :target on a <<target>>
21716 :radio-target on a <<<radio-target>>>
21717 :latex-fragment on a LaTeX fragment
21718 :latex-preview on a LaTeX fragment with overlaid preview image
21720 This function expects the position to be visible because it uses font-lock
21721 faces as a help to recognize the following contexts: :table-special, :link,
21722 and :keyword."
21723 (let* ((f (get-text-property (point) 'face))
21724 (faces (if (listp f) f (list f)))
21725 (case-fold-search t)
21726 (p (point)) clist o)
21727 ;; First the large context
21728 (cond
21729 ((org-at-heading-p t)
21730 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21731 (when (progn
21732 (beginning-of-line 1)
21733 (looking-at org-todo-line-tags-regexp))
21734 (push (org-point-in-group p 1 :headline-stars) clist)
21735 (push (org-point-in-group p 2 :todo-keyword) clist)
21736 (push (org-point-in-group p 4 :tags) clist))
21737 (goto-char p)
21738 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21739 (if (looking-at "\\[#[A-Z0-9]\\]")
21740 (push (org-point-in-group p 0 :priority) clist)))
21742 ((org-at-item-p)
21743 (push (org-point-in-group p 2 :item-bullet) clist)
21744 (push (list :item (point-at-bol)
21745 (save-excursion (org-end-of-item) (point)))
21746 clist)
21747 (and (org-at-item-checkbox-p)
21748 (push (org-point-in-group p 0 :checkbox) clist)))
21750 ((org-at-table-p)
21751 (push (list :table (org-table-begin) (org-table-end)) clist)
21752 (if (memq 'org-formula faces)
21753 (push (list :table-special
21754 (previous-single-property-change p 'face)
21755 (next-single-property-change p 'face)) clist)))
21756 ((org-at-table-p 'any)
21757 (push (list :table-table) clist)))
21758 (goto-char p)
21760 (let ((case-fold-search t))
21761 ;; New the "medium" contexts: clocktables, source blocks
21762 (cond ((org-in-clocktable-p)
21763 (push (list :clocktable
21764 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
21765 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
21766 (match-beginning 1))
21767 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
21768 (match-end 0))) clist))
21769 ((org-in-src-block-p)
21770 (push (list :src-block
21771 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
21772 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
21773 (match-beginning 1))
21774 (and (search-forward "#+END_SRC" nil t)
21775 (match-beginning 0))) clist))))
21776 (goto-char p)
21778 ;; Now the small context
21779 (cond
21780 ((org-at-timestamp-p)
21781 (push (org-point-in-group p 0 :timestamp) clist))
21782 ((memq 'org-link faces)
21783 (push (list :link
21784 (previous-single-property-change p 'face)
21785 (next-single-property-change p 'face)) clist))
21786 ((memq 'org-special-keyword faces)
21787 (push (list :keyword
21788 (previous-single-property-change p 'face)
21789 (next-single-property-change p 'face)) clist))
21790 ((org-at-target-p)
21791 (push (org-point-in-group p 0 :target) clist)
21792 (goto-char (1- (match-beginning 0)))
21793 (if (looking-at org-radio-target-regexp)
21794 (push (org-point-in-group p 0 :radio-target) clist))
21795 (goto-char p))
21796 ((setq o (car (delq nil
21797 (mapcar
21798 (lambda (x)
21799 (if (memq x org-latex-fragment-image-overlays) x))
21800 (overlays-at (point))))))
21801 (push (list :latex-fragment
21802 (overlay-start o) (overlay-end o)) clist)
21803 (push (list :latex-preview
21804 (overlay-start o) (overlay-end o)) clist))
21805 ((org-inside-LaTeX-fragment-p)
21806 ;; FIXME: positions wrong.
21807 (push (list :latex-fragment (point) (point)) clist)))
21809 (setq clist (nreverse (delq nil clist)))
21810 clist))
21812 ;; FIXME: Compare with at-regexp-p Do we need both?
21813 (defun org-in-regexp (re &optional nlines visually)
21814 "Check if point is inside a match of regexp.
21815 Normally only the current line is checked, but you can include NLINES extra
21816 lines both before and after point into the search.
21817 If VISUALLY is set, require that the cursor is not after the match but
21818 really on, so that the block visually is on the match."
21819 (catch 'exit
21820 (let ((pos (point))
21821 (eol (point-at-eol (+ 1 (or nlines 0))))
21822 (inc (if visually 1 0)))
21823 (save-excursion
21824 (beginning-of-line (- 1 (or nlines 0)))
21825 (while (re-search-forward re eol t)
21826 (if (and (<= (match-beginning 0) pos)
21827 (>= (+ inc (match-end 0)) pos))
21828 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21830 (defun org-at-regexp-p (regexp)
21831 "Is point inside a match of REGEXP in the current line?"
21832 (catch 'exit
21833 (save-excursion
21834 (let ((pos (point)) (end (point-at-eol)))
21835 (beginning-of-line 1)
21836 (while (re-search-forward regexp end t)
21837 (if (and (<= (match-beginning 0) pos)
21838 (>= (match-end 0) pos))
21839 (throw 'exit t)))
21840 nil))))
21842 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21843 "Non-nil when point is between matches of START-RE and END-RE.
21845 Also return a non-nil value when point is on one of the matches.
21847 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21848 buffer positions. Default values are the positions of headlines
21849 surrounding the point.
21851 The functions returns a cons cell whose car (resp. cdr) is the
21852 position before START-RE (resp. after END-RE)."
21853 (save-match-data
21854 (let ((pos (point))
21855 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21856 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21857 beg end)
21858 (save-excursion
21859 ;; Point is on a block when on START-RE or if START-RE can be
21860 ;; found before it...
21861 (and (or (org-at-regexp-p start-re)
21862 (re-search-backward start-re limit-up t))
21863 (setq beg (match-beginning 0))
21864 ;; ... and END-RE after it...
21865 (goto-char (match-end 0))
21866 (re-search-forward end-re limit-down t)
21867 (> (setq end (match-end 0)) pos)
21868 ;; ... without another START-RE in-between.
21869 (goto-char (match-beginning 0))
21870 (not (re-search-backward start-re (1+ beg) t))
21871 ;; Return value.
21872 (cons beg end))))))
21874 (defun org-in-block-p (names)
21875 "Non-nil when point belongs to a block whose name belongs to NAMES.
21877 NAMES is a list of strings containing names of blocks.
21879 Return first block name matched, or nil. Beware that in case of
21880 nested blocks, the returned name may not belong to the closest
21881 block from point."
21882 (save-match-data
21883 (catch 'exit
21884 (let ((case-fold-search t)
21885 (lim-up (save-excursion (outline-previous-heading)))
21886 (lim-down (save-excursion (outline-next-heading))))
21887 (mapc (lambda (name)
21888 (let ((n (regexp-quote name)))
21889 (when (org-between-regexps-p
21890 (concat "^[ \t]*#\\+begin_" n)
21891 (concat "^[ \t]*#\\+end_" n)
21892 lim-up lim-down)
21893 (throw 'exit n))))
21894 names))
21895 nil)))
21897 (defun org-in-drawer-p ()
21898 "Non-nil if point is within a drawer.
21899 If point is within a drawer, return it, as parsed data."
21900 (let ((element (save-match-data (org-element-at-point))))
21901 (while (and element (not (memq (org-element-type element)
21902 '(drawer property-drawer))))
21903 (setq element (org-element-property :parent element)))
21904 element))
21906 (defun org-occur-in-agenda-files (regexp &optional nlines)
21907 "Call `multi-occur' with buffers for all agenda files."
21908 (interactive "sOrg-files matching: \np")
21909 (let* ((files (org-agenda-files))
21910 (tnames (mapcar 'file-truename files))
21911 (extra org-agenda-text-search-extra-files)
21913 (when (eq (car extra) 'agenda-archives)
21914 (setq extra (cdr extra))
21915 (setq files (org-add-archive-files files)))
21916 (while (setq f (pop extra))
21917 (unless (member (file-truename f) tnames)
21918 (add-to-list 'files f 'append)
21919 (add-to-list 'tnames (file-truename f) 'append)))
21920 (multi-occur
21921 (mapcar (lambda (x)
21922 (with-current-buffer
21923 (or (get-file-buffer x) (find-file-noselect x))
21924 (widen)
21925 (current-buffer)))
21926 files)
21927 regexp)))
21929 (if (boundp 'occur-mode-find-occurrence-hook)
21930 ;; Emacs 23
21931 (add-hook 'occur-mode-find-occurrence-hook
21932 (lambda ()
21933 (when (derived-mode-p 'org-mode)
21934 (org-reveal))))
21935 ;; Emacs 22
21936 (defadvice occur-mode-goto-occurrence
21937 (after org-occur-reveal activate)
21938 (and (derived-mode-p 'org-mode) (org-reveal)))
21939 (defadvice occur-mode-goto-occurrence-other-window
21940 (after org-occur-reveal activate)
21941 (and (derived-mode-p 'org-mode) (org-reveal)))
21942 (defadvice occur-mode-display-occurrence
21943 (after org-occur-reveal activate)
21944 (when (derived-mode-p 'org-mode)
21945 (let ((pos (occur-mode-find-occurrence)))
21946 (with-current-buffer (marker-buffer pos)
21947 (save-excursion
21948 (goto-char pos)
21949 (org-reveal)))))))
21951 (defun org-occur-link-in-agenda-files ()
21952 "Create a link and search for it in the agendas.
21953 The link is not stored in `org-stored-links', it is just created
21954 for the search purpose."
21955 (interactive)
21956 (let ((link (condition-case nil
21957 (org-store-link nil)
21958 (error "Unable to create a link to here"))))
21959 (org-occur-in-agenda-files (regexp-quote link))))
21961 (defun org-reverse-string (string)
21962 "Return the reverse of STRING."
21963 (apply 'string (reverse (string-to-list string))))
21965 (defun org-uniquify-alist (alist)
21966 "Merge elements of ALIST with the same key.
21968 For example, in this alist:
21970 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
21971 => '((a 1 3) (b 2))
21973 merge (a 1) and (a 3) into (a 1 3).
21975 The function returns the new ALIST."
21976 (let (rtn)
21977 (mapc
21978 (lambda (e)
21979 (let (n)
21980 (if (not (assoc (car e) rtn))
21981 (push e rtn)
21982 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
21983 (setq rtn (assq-delete-all (car e) rtn))
21984 (push n rtn))))
21985 alist)
21986 rtn))
21988 (defun org-delete-all (elts list)
21989 "Remove all elements in ELTS from LIST."
21990 (while elts
21991 (setq list (delete (pop elts) list)))
21992 list)
21994 (defun org-count (cl-item cl-seq)
21995 "Count the number of occurrences of ITEM in SEQ.
21996 Taken from `count' in cl-seq.el with all keyword arguments removed."
21997 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21998 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21999 (while (< cl-start cl-end)
22000 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
22001 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
22002 (setq cl-start (1+ cl-start)))
22003 cl-count))
22005 (defun org-remove-if (predicate seq)
22006 "Remove everything from SEQ that fulfills PREDICATE."
22007 (let (res e)
22008 (while seq
22009 (setq e (pop seq))
22010 (if (not (funcall predicate e)) (push e res)))
22011 (nreverse res)))
22013 (defun org-remove-if-not (predicate seq)
22014 "Remove everything from SEQ that does not fulfill PREDICATE."
22015 (let (res e)
22016 (while seq
22017 (setq e (pop seq))
22018 (if (funcall predicate e) (push e res)))
22019 (nreverse res)))
22021 (defun org-reduce (cl-func cl-seq &rest cl-keys)
22022 "Reduce two-argument FUNCTION across SEQ.
22023 Taken from `reduce' in cl-seq.el with all keyword arguments but
22024 \":initial-value\" removed."
22025 (let ((cl-accum (cond ((memq :initial-value cl-keys)
22026 (cadr (memq :initial-value cl-keys)))
22027 (cl-seq (pop cl-seq))
22028 (t (funcall cl-func)))))
22029 (while cl-seq
22030 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
22031 cl-accum))
22033 (defun org-every (pred seq)
22034 "Return true if PREDICATE is true of every element of SEQ.
22035 Adapted from `every' in cl.el."
22036 (catch 'org-every
22037 (mapc (lambda (e) (unless (funcall pred e) (throw 'org-every nil))) seq)
22040 (defun org-some (pred seq)
22041 "Return true if PREDICATE is true of any element of SEQ.
22042 Adapted from `some' in cl.el."
22043 (catch 'org-some
22044 (mapc (lambda (e) (when (funcall pred e) (throw 'org-some t))) seq)
22045 nil))
22047 (defun org-back-over-empty-lines ()
22048 "Move backwards over whitespace, to the beginning of the first empty line.
22049 Returns the number of empty lines passed."
22050 (let ((pos (point)))
22051 (if (cdr (assoc 'heading org-blank-before-new-entry))
22052 (skip-chars-backward " \t\n\r")
22053 (unless (eobp)
22054 (forward-line -1)))
22055 (beginning-of-line 2)
22056 (goto-char (min (point) pos))
22057 (count-lines (point) pos)))
22059 (defun org-skip-whitespace ()
22060 (skip-chars-forward " \t\n\r"))
22062 (defun org-point-in-group (point group &optional context)
22063 "Check if POINT is in match-group GROUP.
22064 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22065 match. If the match group does not exist or point is not inside it,
22066 return nil."
22067 (and (match-beginning group)
22068 (>= point (match-beginning group))
22069 (<= point (match-end group))
22070 (if context
22071 (list context (match-beginning group) (match-end group))
22072 t)))
22074 (defun org-switch-to-buffer-other-window (&rest args)
22075 "Switch to buffer in a second window on the current frame.
22076 In particular, do not allow pop-up frames.
22077 Returns the newly created buffer."
22078 (org-no-popups
22079 (apply 'switch-to-buffer-other-window args)))
22081 (defun org-combine-plists (&rest plists)
22082 "Create a single property list from all plists in PLISTS.
22083 The process starts by copying the first list, and then setting properties
22084 from the other lists. Settings in the last list are the most significant
22085 ones and overrule settings in the other lists."
22086 (let ((rtn (copy-sequence (pop plists)))
22087 p v ls)
22088 (while plists
22089 (setq ls (pop plists))
22090 (while ls
22091 (setq p (pop ls) v (pop ls))
22092 (setq rtn (plist-put rtn p v))))
22093 rtn))
22095 (defun org-replace-escapes (string table)
22096 "Replace %-escapes in STRING with values in TABLE.
22097 TABLE is an association list with keys like \"%a\" and string values.
22098 The sequences in STRING may contain normal field width and padding information,
22099 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22100 so values can contain further %-escapes if they are define later in TABLE."
22101 (let ((tbl (copy-alist table))
22102 (case-fold-search nil)
22103 (pchg 0)
22104 e re rpl)
22105 (while (setq e (pop tbl))
22106 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22107 (when (and (cdr e) (string-match re (cdr e)))
22108 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22109 (safe "SREF"))
22110 (add-text-properties 0 3 (list 'sref sref) safe)
22111 (setcdr e (replace-match safe t t (cdr e)))))
22112 (while (string-match re string)
22113 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22114 (cdr e)))
22115 (setq string (replace-match rpl t t string))))
22116 (while (setq pchg (next-property-change pchg string))
22117 (let ((sref (get-text-property pchg 'sref string)))
22118 (when (and sref (string-match "SREF" string pchg))
22119 (setq string (replace-match sref t t string)))))
22120 string))
22122 (defun org-sublist (list start end)
22123 "Return a section of LIST, from START to END.
22124 Counting starts at 1."
22125 (let (rtn (c start))
22126 (setq list (nthcdr (1- start) list))
22127 (while (and list (<= c end))
22128 (push (pop list) rtn)
22129 (setq c (1+ c)))
22130 (nreverse rtn)))
22132 (defun org-find-base-buffer-visiting (file)
22133 "Like `find-buffer-visiting' but always return the base buffer and
22134 not an indirect buffer."
22135 (let ((buf (or (get-file-buffer file)
22136 (find-buffer-visiting file))))
22137 (if buf
22138 (or (buffer-base-buffer buf) buf)
22139 nil)))
22141 (defun org-image-file-name-regexp (&optional extensions)
22142 "Return regexp matching the file names of images.
22143 If EXTENSIONS is given, only match these."
22144 (if (and (not extensions) (fboundp 'image-file-name-regexp))
22145 (image-file-name-regexp)
22146 (let ((image-file-name-extensions
22147 (or extensions
22148 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
22149 "xbm" "xpm" "pbm" "pgm" "ppm"))))
22150 (concat "\\."
22151 (regexp-opt (nconc (mapcar 'upcase
22152 image-file-name-extensions)
22153 image-file-name-extensions)
22155 "\\'"))))
22157 (defun org-file-image-p (file &optional extensions)
22158 "Return non-nil if FILE is an image."
22159 (save-match-data
22160 (string-match (org-image-file-name-regexp extensions) file)))
22162 (defun org-get-cursor-date (&optional with-time)
22163 "Return the date at cursor in as a time.
22164 This works in the calendar and in the agenda, anywhere else it just
22165 returns the current time.
22166 If WITH-TIME is non-nil, returns the time of the event at point (in
22167 the agenda) or the current time of the day."
22168 (let (date day defd tp tm hod mod)
22169 (when with-time
22170 (setq tp (get-text-property (point) 'time))
22171 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22172 (setq hod (string-to-number (match-string 1 tp))
22173 mod (string-to-number (match-string 2 tp))))
22174 (or tp (setq hod (nth 2 (decode-time (current-time)))
22175 mod (nth 1 (decode-time (current-time))))))
22176 (cond
22177 ((eq major-mode 'calendar-mode)
22178 (setq date (calendar-cursor-to-date)
22179 defd (encode-time 0 (or mod 0) (or hod 0)
22180 (nth 1 date) (nth 0 date) (nth 2 date))))
22181 ((eq major-mode 'org-agenda-mode)
22182 (setq day (get-text-property (point) 'day))
22183 (if day
22184 (setq date (calendar-gregorian-from-absolute day)
22185 defd (encode-time 0 (or mod 0) (or hod 0)
22186 (nth 1 date) (nth 0 date) (nth 2 date))))))
22187 (or defd (current-time))))
22189 (defun org-mark-subtree (&optional up)
22190 "Mark the current subtree.
22191 This puts point at the start of the current subtree, and mark at
22192 the end. If a numeric prefix UP is given, move up into the
22193 hierarchy of headlines by UP levels before marking the subtree."
22194 (interactive "P")
22195 (org-with-limited-levels
22196 (cond ((org-at-heading-p) (beginning-of-line))
22197 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22198 (t (outline-previous-visible-heading 1))))
22199 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
22200 (if (org-called-interactively-p 'any)
22201 (call-interactively 'org-mark-element)
22202 (org-mark-element)))
22205 ;;; Indentation
22207 (defun org-indent-line ()
22208 "Indent line depending on context."
22209 (interactive)
22210 (let* ((pos (point))
22211 (itemp (org-at-item-p))
22212 (case-fold-search t)
22213 (org-drawer-regexp (or org-drawer-regexp "\000"))
22214 (inline-task-p (and (featurep 'org-inlinetask)
22215 (org-inlinetask-in-task-p)))
22216 (inline-re (and inline-task-p
22217 (org-inlinetask-outline-regexp)))
22218 column)
22219 (if (and orgstruct-is-++ (eq pos (point)))
22220 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
22221 (indent-according-to-mode))
22222 (beginning-of-line 1)
22223 (cond
22224 ;; Headings
22225 ((looking-at org-outline-regexp) (setq column 0))
22226 ;; Footnote definition
22227 ((looking-at org-footnote-definition-re) (setq column 0))
22228 ;; Literal examples
22229 ((looking-at "[ \t]*:\\( \\|$\\)")
22230 (setq column (org-get-indentation))) ; do nothing
22231 ;; Lists
22232 ((ignore-errors (goto-char (org-in-item-p)))
22233 (setq column (if itemp
22234 (org-get-indentation)
22235 (org-list-item-body-column (point))))
22236 (goto-char pos))
22237 ;; Drawers
22238 ((and (looking-at "[ \t]*:END:")
22239 (save-excursion (re-search-backward org-drawer-regexp nil t)))
22240 (save-excursion
22241 (goto-char (1- (match-beginning 1)))
22242 (setq column (current-column))))
22243 ;; Special blocks
22244 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
22245 (save-excursion
22246 (re-search-backward
22247 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
22248 (setq column (org-get-indentation (match-string 0))))
22249 ((and (not (looking-at "[ \t]*#\\+begin_"))
22250 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
22251 (save-excursion
22252 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
22253 (setq column
22254 (cond ((equal (downcase (match-string 1)) "src")
22255 ;; src blocks: let `org-edit-src-exit' handle them
22256 (org-get-indentation))
22257 ((equal (downcase (match-string 1)) "example")
22258 (max (org-get-indentation)
22259 (org-get-indentation (match-string 0))))
22261 (org-get-indentation (match-string 0))))))
22262 ;; This line has nothing special, look at the previous relevant
22263 ;; line to compute indentation
22265 (beginning-of-line 0)
22266 (while (and (not (bobp))
22267 (not (looking-at org-table-line-regexp))
22268 (not (looking-at org-drawer-regexp))
22269 ;; When point started in an inline task, do not move
22270 ;; above task starting line.
22271 (not (and inline-task-p (looking-at inline-re)))
22272 ;; Skip drawers, blocks, empty lines, verbatim,
22273 ;; comments, tables, footnotes definitions, lists,
22274 ;; inline tasks.
22275 (or (and (looking-at "[ \t]*:END:")
22276 (re-search-backward org-drawer-regexp nil t))
22277 (and (looking-at "[ \t]*#\\+end_")
22278 (re-search-backward "[ \t]*#\\+begin_"nil t))
22279 (looking-at "[ \t]*[\n:#|]")
22280 (looking-at org-footnote-definition-re)
22281 (and (not inline-task-p)
22282 (featurep 'org-inlinetask)
22283 (org-inlinetask-in-task-p)
22284 (or (org-inlinetask-goto-beginning) t))))
22285 (beginning-of-line 0))
22286 (cond
22287 ;; There was a list item above.
22288 ((ignore-errors (goto-char (org-in-item-p)))
22289 (goto-char (org-list-get-top-point (org-list-struct)))
22290 (setq column (org-get-indentation)))
22291 ;; There was an heading above.
22292 ((looking-at "\\*+[ \t]+")
22293 (if (not org-adapt-indentation)
22294 (setq column 0)
22295 (goto-char (match-end 0))
22296 (setq column (current-column))))
22297 ;; A drawer had started and is unfinished
22298 ((looking-at org-drawer-regexp)
22299 (goto-char (1- (match-beginning 1)))
22300 (setq column (current-column)))
22301 ;; Else, nothing noticeable found: get indentation and go on.
22302 (t (setq column (org-get-indentation))))))
22303 ;; Now apply indentation and move cursor accordingly
22304 (goto-char pos)
22305 (if (<= (current-column) (current-indentation))
22306 (org-indent-line-to column)
22307 (save-excursion (org-indent-line-to column)))
22308 ;; Special polishing for properties, see `org-property-format'
22309 (setq column (current-column))
22310 (beginning-of-line 1)
22311 (if (looking-at org-property-re)
22312 (replace-match (concat (match-string 4)
22313 (format org-property-format
22314 (match-string 1) (match-string 3)))
22315 t t))
22316 (org-move-to-column column))))
22318 (defun org-indent-drawer ()
22319 "Indent the drawer at point."
22320 (interactive)
22321 (let ((p (point))
22322 (e (and (save-excursion (re-search-forward ":END:" nil t))
22323 (match-end 0)))
22324 (folded
22325 (save-excursion
22326 (end-of-line)
22327 (when (overlays-at (point))
22328 (member 'invisible (overlay-properties
22329 (car (overlays-at (point)))))))))
22330 (when folded (org-cycle))
22331 (indent-for-tab-command)
22332 (while (and (move-beginning-of-line 2) (< (point) e))
22333 (indent-for-tab-command))
22334 (goto-char p)
22335 (when folded (org-cycle)))
22336 (message "Drawer at point indented"))
22338 (defun org-indent-block ()
22339 "Indent the block at point."
22340 (interactive)
22341 (let ((p (point))
22342 (case-fold-search t)
22343 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
22344 (match-end 0)))
22345 (folded
22346 (save-excursion
22347 (end-of-line)
22348 (when (overlays-at (point))
22349 (member 'invisible (overlay-properties
22350 (car (overlays-at (point)))))))))
22351 (when folded (org-cycle))
22352 (indent-for-tab-command)
22353 (while (and (move-beginning-of-line 2) (< (point) e))
22354 (indent-for-tab-command))
22355 (goto-char p)
22356 (when folded (org-cycle)))
22357 (message "Block at point indented"))
22359 (defun org-indent-region (start end)
22360 "Indent region."
22361 (interactive "r")
22362 (save-excursion
22363 (let ((line-end (org-current-line end)))
22364 (goto-char start)
22365 (while (< (org-current-line) line-end)
22366 (cond ((org-in-src-block-p t) (org-src-native-tab-command-maybe))
22367 (t (call-interactively 'org-indent-line)))
22368 (move-beginning-of-line 2)))))
22371 ;;; Filling
22373 ;; We use our own fill-paragraph and auto-fill functions.
22375 ;; `org-fill-paragraph' relies on adaptive filling and context
22376 ;; checking. Appropriate `fill-prefix' is computed with
22377 ;; `org-adaptive-fill-function'.
22379 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22380 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22381 ;; `org-adaptive-fill-function' value. Internally,
22382 ;; `org-comment-line-break-function' breaks the line.
22384 ;; `org-setup-filling' installs filling and auto-filling related
22385 ;; variables during `org-mode' initialization.
22387 (defvar org-element-paragraph-separate) ; org-element.el
22388 (defun org-setup-filling ()
22389 (require 'org-element)
22390 ;; Prevent auto-fill from inserting unwanted new items.
22391 (when (boundp 'fill-nobreak-predicate)
22392 (org-set-local
22393 'fill-nobreak-predicate
22394 (org-uniquify
22395 (append fill-nobreak-predicate
22396 '(org-fill-line-break-nobreak-p
22397 org-fill-paragraph-with-timestamp-nobreak-p)))))
22398 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22399 (org-set-local 'paragraph-start paragraph-ending)
22400 (org-set-local 'paragraph-separate paragraph-ending))
22401 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22402 (org-set-local 'auto-fill-inhibit-regexp nil)
22403 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22404 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22405 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22407 (defun org-fill-line-break-nobreak-p ()
22408 "Non-nil when a new line at point would create an Org line break."
22409 (save-excursion
22410 (skip-chars-backward "[ \t]")
22411 (skip-chars-backward "\\\\")
22412 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22414 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22415 "Non-nil when a new line at point would split a timestamp."
22416 (and (org-at-timestamp-p t)
22417 (not (looking-at org-ts-regexp-both))))
22419 (declare-function message-in-body-p "message" ())
22420 (defvar orgtbl-line-start-regexp) ; From org-table.el
22421 (defun org-adaptive-fill-function ()
22422 "Compute a fill prefix for the current line.
22423 Return fill prefix, as a string, or nil if current line isn't
22424 meant to be filled. For convenience, if `adaptive-fill-regexp'
22425 matches in paragraphs or comments, use it."
22426 (catch 'exit
22427 (when (derived-mode-p 'message-mode)
22428 (save-excursion
22429 (beginning-of-line)
22430 (cond ((or (not (message-in-body-p))
22431 (looking-at orgtbl-line-start-regexp))
22432 (throw 'exit nil))
22433 ((looking-at message-cite-prefix-regexp)
22434 (throw 'exit (match-string-no-properties 0)))
22435 ((looking-at org-outline-regexp)
22436 (throw 'exit (make-string (length (match-string 0)) ? ))))))
22437 (org-with-wide-buffer
22438 (let* ((p (line-beginning-position))
22439 (element (save-excursion
22440 (beginning-of-line)
22441 (or (ignore-errors (org-element-at-point))
22442 (user-error "An element cannot be parsed line %d"
22443 (line-number-at-pos (point))))))
22444 (type (org-element-type element))
22445 (post-affiliated (org-element-property :post-affiliated element)))
22446 (unless (and post-affiliated (< p post-affiliated))
22447 (case type
22448 (comment
22449 (save-excursion
22450 (beginning-of-line)
22451 (looking-at "[ \t]*")
22452 (concat (match-string 0) "# ")))
22453 (footnote-definition "")
22454 ((item plain-list)
22455 (make-string (org-list-item-body-column
22456 (or post-affiliated
22457 (org-element-property :begin element)))
22458 ? ))
22459 (paragraph
22460 ;; Fill prefix is usually the same as the current line,
22461 ;; unless the paragraph is at the beginning of an item.
22462 (let ((parent (org-element-property :parent element)))
22463 (save-excursion
22464 (beginning-of-line)
22465 (cond ((eq (org-element-type parent) 'item)
22466 (make-string (org-list-item-body-column
22467 (org-element-property :begin parent))
22468 ? ))
22469 ((and adaptive-fill-regexp
22470 ;; Locally disable
22471 ;; `adaptive-fill-function' to let
22472 ;; `fill-context-prefix' handle
22473 ;; `adaptive-fill-regexp' variable.
22474 (let (adaptive-fill-function)
22475 (fill-context-prefix
22476 post-affiliated
22477 (org-element-property :end element)))))
22478 ((looking-at "[ \t]+") (match-string 0))
22479 (t "")))))
22480 (comment-block
22481 ;; Only fill contents if P is within block boundaries.
22482 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22483 (forward-line)
22484 (point)))
22485 (cend (save-excursion
22486 (goto-char (org-element-property :end element))
22487 (skip-chars-backward " \r\t\n")
22488 (line-beginning-position))))
22489 (when (and (>= p cbeg) (< p cend))
22490 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22491 (match-string 0)
22492 ""))))))))))
22494 (declare-function message-goto-body "message" ())
22495 (defvar message-cite-prefix-regexp) ; From message.el
22496 (defun org-fill-paragraph (&optional justify)
22497 "Fill element at point, when applicable.
22499 This function only applies to comment blocks, comments, example
22500 blocks and paragraphs. Also, as a special case, re-align table
22501 when point is at one.
22503 If JUSTIFY is non-nil (interactively, with prefix argument),
22504 justify as well. If `sentence-end-double-space' is non-nil, then
22505 period followed by one space does not end a sentence, so don't
22506 break a line there. The variable `fill-column' controls the
22507 width for filling.
22509 For convenience, when point is at a plain list, an item or
22510 a footnote definition, try to fill the first paragraph within."
22511 (interactive)
22512 (if (and (derived-mode-p 'message-mode)
22513 (or (not (message-in-body-p))
22514 (save-excursion (move-beginning-of-line 1)
22515 (looking-at message-cite-prefix-regexp))))
22516 ;; First ensure filling is correct in message-mode.
22517 (let ((fill-paragraph-function
22518 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22519 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22520 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22521 (paragraph-separate
22522 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22523 (fill-paragraph nil))
22524 (with-syntax-table org-mode-transpose-word-syntax-table
22525 ;; Move to end of line in order to get the first paragraph
22526 ;; within a plain list or a footnote definition.
22527 (let ((element (save-excursion
22528 (end-of-line)
22529 (or (ignore-errors (org-element-at-point))
22530 (user-error "An element cannot be parsed line %d"
22531 (line-number-at-pos (point)))))))
22532 ;; First check if point is in a blank line at the beginning of
22533 ;; the buffer. In that case, ignore filling.
22534 (case (org-element-type element)
22535 ;; Use major mode filling function is src blocks.
22536 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22537 ;; Align Org tables, leave table.el tables as-is.
22538 (table-row (org-table-align) t)
22539 (table
22540 (when (eq (org-element-property :type element) 'org)
22541 (save-excursion
22542 (goto-char (org-element-property :post-affiliated element))
22543 (org-table-align)))
22545 (paragraph
22546 ;; Paragraphs may contain `line-break' type objects.
22547 (let ((beg (max (point-min)
22548 (org-element-property :contents-begin element)))
22549 (end (min (point-max)
22550 (org-element-property :contents-end element))))
22551 ;; Do nothing if point is at an affiliated keyword.
22552 (if (< (line-end-position) beg) t
22553 (when (derived-mode-p 'message-mode)
22554 ;; In `message-mode', do not fill following citation
22555 ;; in current paragraph nor text before message body.
22556 (let ((body-start (save-excursion (message-goto-body))))
22557 (when body-start (setq beg (max body-start beg))))
22558 (when (save-excursion
22559 (re-search-forward
22560 (concat "^" message-cite-prefix-regexp) end t))
22561 (setq end (match-beginning 0))))
22562 ;; Fill paragraph, taking line breaks into account.
22563 ;; For that, slice the paragraph using line breaks as
22564 ;; separators, and fill the parts in reverse order to
22565 ;; avoid messing with markers.
22566 (save-excursion
22567 (goto-char end)
22568 (mapc
22569 (lambda (pos)
22570 (fill-region-as-paragraph pos (point) justify)
22571 (goto-char pos))
22572 ;; Find the list of ending positions for line breaks
22573 ;; in the current paragraph. Add paragraph
22574 ;; beginning to include first slice.
22575 (nreverse
22576 (cons beg
22577 (org-element-map
22578 (org-element--parse-objects
22579 beg end nil (org-element-restriction 'paragraph))
22580 'line-break
22581 (lambda (lb) (org-element-property :end lb)))))))
22582 t)))
22583 ;; Contents of `comment-block' type elements should be
22584 ;; filled as plain text, but only if point is within block
22585 ;; markers.
22586 (comment-block
22587 (let* ((case-fold-search t)
22588 (beg (save-excursion
22589 (goto-char (org-element-property :begin element))
22590 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22591 (forward-line)
22592 (point)))
22593 (end (save-excursion
22594 (goto-char (org-element-property :end element))
22595 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22596 (line-beginning-position))))
22597 (if (or (< (point) beg) (> (point) end)) t
22598 (fill-region-as-paragraph
22599 (save-excursion (end-of-line)
22600 (re-search-backward "^[ \t]*$" beg 'move)
22601 (line-beginning-position))
22602 (save-excursion (beginning-of-line)
22603 (re-search-forward "^[ \t]*$" end 'move)
22604 (line-beginning-position))
22605 justify))))
22606 ;; Fill comments.
22607 (comment
22608 (let ((begin (org-element-property :post-affiliated element))
22609 (end (org-element-property :end element)))
22610 (when (and (>= (point) begin) (<= (point) end))
22611 (let ((begin (save-excursion
22612 (end-of-line)
22613 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22614 (progn (forward-line) (point))
22615 begin)))
22616 (end (save-excursion
22617 (end-of-line)
22618 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22619 (1- (line-beginning-position))
22620 (skip-chars-backward " \r\t\n")
22621 (line-end-position)))))
22622 ;; Do not fill comments when at a blank line.
22623 (when (> end begin)
22624 (let ((fill-prefix
22625 (save-excursion
22626 (beginning-of-line)
22627 (looking-at "[ \t]*#")
22628 (let ((comment-prefix (match-string 0)))
22629 (goto-char (match-end 0))
22630 (if (looking-at adaptive-fill-regexp)
22631 (concat comment-prefix (match-string 0))
22632 (concat comment-prefix " "))))))
22633 (save-excursion
22634 (fill-region-as-paragraph begin end justify))))))
22636 ;; Ignore every other element.
22637 (otherwise t))))))
22639 (defun org-auto-fill-function ()
22640 "Auto-fill function."
22641 ;; Check if auto-filling is meaningful.
22642 (let ((fc (current-fill-column)))
22643 (when (and fc (> (current-column) fc))
22644 (let* ((fill-prefix (org-adaptive-fill-function))
22645 ;; Enforce empty fill prefix, if required. Otherwise, it
22646 ;; will be computed again.
22647 (adaptive-fill-mode (not (equal fill-prefix ""))))
22648 (when fill-prefix (do-auto-fill))))))
22650 (defun org-comment-line-break-function (&optional soft)
22651 "Break line at point and indent, continuing comment if within one.
22652 The inserted newline is marked hard if variable
22653 `use-hard-newlines' is true, unless optional argument SOFT is
22654 non-nil."
22655 (if soft (insert-and-inherit ?\n) (newline 1))
22656 (save-excursion (forward-char -1) (delete-horizontal-space))
22657 (delete-horizontal-space)
22658 (indent-to-left-margin)
22659 (insert-before-markers-and-inherit fill-prefix))
22662 ;;; Fixed Width Areas
22664 (defun org-toggle-fixed-width ()
22665 "Toggle fixed-width markup.
22667 Add or remove fixed-width markup on current line, whenever it
22668 makes sense. Return an error otherwise.
22670 If a region is active and if it contains only fixed-width areas
22671 or blank lines, remove all fixed-width markup in it. If the
22672 region contains anything else, convert all non-fixed-width lines
22673 to fixed-width ones.
22675 Blank lines at the end of the region are ignored unless the
22676 region only contains such lines."
22677 (interactive)
22678 (if (not (org-region-active-p))
22679 ;; No region:
22681 ;; Remove fixed width marker only in a fixed-with element.
22683 ;; Add fixed width maker in paragraphs, in blank lines after
22684 ;; elements or at the beginning of a headline or an inlinetask,
22685 ;; and before any one-line elements (e.g., a clock).
22686 (progn
22687 (beginning-of-line)
22688 (let* ((element (org-element-at-point))
22689 (type (org-element-type element)))
22690 (cond
22691 ((and (eq type 'fixed-width)
22692 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
22693 (replace-match
22694 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
22695 ((and (memq type '(babel-call clock comment diary-sexp headline
22696 horizontal-rule keyword paragraph
22697 planning))
22698 (or (not (org-element-property :post-affiliated element))
22699 (<= (org-element-property :post-affiliated element)
22700 (point))))
22701 (skip-chars-forward " \t")
22702 (insert ": "))
22703 ((and (org-looking-at-p "[ \t]*$")
22704 (or (eq type 'inlinetask)
22705 (save-excursion
22706 (skip-chars-forward " \r\t\n")
22707 (<= (org-element-property :end element) (point)))))
22708 (delete-region (point) (line-end-position))
22709 (org-indent-line)
22710 (insert ": "))
22711 (t (user-error "Cannot insert a fixed-width line here")))))
22712 ;; Region active.
22713 (let* ((begin (save-excursion
22714 (goto-char (region-beginning))
22715 (line-beginning-position)))
22716 (end (copy-marker
22717 (save-excursion
22718 (goto-char (region-end))
22719 (unless (eolp) (beginning-of-line))
22720 (if (save-excursion (re-search-backward "\\S-" begin t))
22721 (progn (skip-chars-backward " \r\t\n") (point))
22722 (point)))))
22723 (all-fixed-width-p
22724 (catch 'not-all-p
22725 (save-excursion
22726 (goto-char begin)
22727 (skip-chars-forward " \r\t\n")
22728 (when (eobp) (throw 'not-all-p nil))
22729 (while (< (point) end)
22730 (let ((element (org-element-at-point)))
22731 (if (eq (org-element-type element) 'fixed-width)
22732 (goto-char (org-element-property :end element))
22733 (throw 'not-all-p nil))))
22734 t))))
22735 (if all-fixed-width-p
22736 (save-excursion
22737 (goto-char begin)
22738 (while (< (point) end)
22739 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
22740 (replace-match
22741 "" nil nil nil
22742 (if (= (line-end-position) (match-end 0)) 0 1)))
22743 (forward-line)))
22744 (let ((min-ind (point-max)))
22745 ;; Find minimum indentation across all lines.
22746 (save-excursion
22747 (goto-char begin)
22748 (if (not (save-excursion (re-search-forward "\\S-" end t)))
22749 (setq min-ind 0)
22750 (catch 'zerop
22751 (while (< (point) end)
22752 (unless (org-looking-at-p "[ \t]*$")
22753 (let ((ind (org-get-indentation)))
22754 (setq min-ind (min min-ind ind))
22755 (when (zerop ind) (throw 'zerop t))))
22756 (forward-line)))))
22757 ;; Loop over all lines and add fixed-width markup everywhere
22758 ;; but in fixed-width lines.
22759 (save-excursion
22760 (goto-char begin)
22761 (while (< (point) end)
22762 (cond
22763 ((org-at-heading-p)
22764 (insert ": ")
22765 (forward-line)
22766 (while (and (< (point) end) (org-looking-at-p "[ \t]*$"))
22767 (insert ":")
22768 (forward-line)))
22769 ((org-looking-at-p "[ \t]*:\\( \\|$\\)")
22770 (let* ((element (org-element-at-point))
22771 (element-end (org-element-property :end element)))
22772 (if (eq (org-element-type element) 'fixed-width)
22773 (progn (goto-char element-end)
22774 (skip-chars-backward " \r\t\n")
22775 (forward-line))
22776 (let ((limit (min end element-end)))
22777 (while (< (point) limit)
22778 (org-move-to-column min-ind t)
22779 (insert ": ")
22780 (forward-line))))))
22782 (org-move-to-column min-ind t)
22783 (insert ": ")
22784 (forward-line)))))))
22785 (set-marker end nil))))
22788 ;;; Comments
22790 ;; Org comments syntax is quite complex. It requires the entire line
22791 ;; to be just a comment. Also, even with the right syntax at the
22792 ;; beginning of line, some some elements (i.e. verse-block or
22793 ;; example-block) don't accept comments. Usual Emacs comment commands
22794 ;; cannot cope with those requirements. Therefore, Org replaces them.
22796 ;; Org still relies on `comment-dwim', but cannot trust
22797 ;; `comment-only-p'. So, `comment-region-function' and
22798 ;; `uncomment-region-function' both point
22799 ;; to`org-comment-or-uncomment-region'. Eventually,
22800 ;; `org-insert-comment' takes care of insertion of comments at the
22801 ;; beginning of line.
22803 ;; `org-setup-comments-handling' install comments related variables
22804 ;; during `org-mode' initialization.
22806 (defun org-setup-comments-handling ()
22807 (interactive)
22808 (org-set-local 'comment-use-syntax nil)
22809 (org-set-local 'comment-start "# ")
22810 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22811 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22812 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22813 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22815 (defun org-insert-comment ()
22816 "Insert an empty comment above current line.
22817 If the line is empty, insert comment at its beginning. When
22818 point is within a source block, comment according to the related
22819 major mode."
22820 (if (let ((element (org-element-at-point)))
22821 (and (eq (org-element-type element) 'src-block)
22822 (< (save-excursion
22823 (goto-char (org-element-property :post-affiliated element))
22824 (line-end-position))
22825 (point))
22826 (> (save-excursion
22827 (goto-char (org-element-property :end element))
22828 (skip-chars-backward " \r\t\n")
22829 (line-beginning-position))
22830 (point))))
22831 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim))
22832 (beginning-of-line)
22833 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
22834 (open-line 1))
22835 (org-indent-line)
22836 (insert "# ")))
22838 (defvar comment-empty-lines) ; From newcomment.el.
22839 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22840 "Comment or uncomment each non-blank line in the region.
22841 Uncomment each non-blank line between BEG and END if it only
22842 contains commented lines. Otherwise, comment them. If region is
22843 strictly within a source block, use appropriate comment syntax."
22844 (if (let ((element (org-element-at-point)))
22845 (and (eq (org-element-type element) 'src-block)
22846 (< (save-excursion
22847 (goto-char (org-element-property :post-affiliated element))
22848 (line-end-position))
22849 beg)
22850 (>= (save-excursion
22851 (goto-char (org-element-property :end element))
22852 (skip-chars-backward " \r\t\n")
22853 (line-beginning-position))
22854 end)))
22855 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim))
22856 (save-restriction
22857 ;; Restrict region
22858 (narrow-to-region (save-excursion (goto-char beg)
22859 (skip-chars-forward " \r\t\n" end)
22860 (line-beginning-position))
22861 (save-excursion (goto-char end)
22862 (skip-chars-backward " \r\t\n" beg)
22863 (line-end-position)))
22864 (let ((uncommentp
22865 ;; UNCOMMENTP is non-nil when every non blank line between
22866 ;; BEG and END is a comment.
22867 (save-excursion
22868 (goto-char (point-min))
22869 (while (and (not (eobp))
22870 (let ((element (org-element-at-point)))
22871 (and (eq (org-element-type element) 'comment)
22872 (goto-char (min (point-max)
22873 (org-element-property
22874 :end element)))))))
22875 (eobp))))
22876 (if uncommentp
22877 ;; Only blank lines and comments in region: uncomment it.
22878 (save-excursion
22879 (goto-char (point-min))
22880 (while (not (eobp))
22881 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22882 (replace-match "" nil nil nil 1))
22883 (forward-line)))
22884 ;; Comment each line in region.
22885 (let ((min-indent (point-max)))
22886 ;; First find the minimum indentation across all lines.
22887 (save-excursion
22888 (goto-char (point-min))
22889 (while (and (not (eobp)) (not (zerop min-indent)))
22890 (unless (looking-at "[ \t]*$")
22891 (setq min-indent (min min-indent (current-indentation))))
22892 (forward-line)))
22893 ;; Then loop over all lines.
22894 (save-excursion
22895 (goto-char (point-min))
22896 (while (not (eobp))
22897 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22898 ;; Don't get fooled by invisible text (e.g. link path)
22899 ;; when moving to column MIN-INDENT.
22900 (let ((buffer-invisibility-spec nil))
22901 (org-move-to-column min-indent t))
22902 (insert comment-start))
22903 (forward-line)))))))))
22905 (defun org-comment-dwim (arg)
22906 (interactive "*P")
22907 "Call `comment-dwim' within a source edit buffer if needed."
22908 (if (org-in-src-block-p)
22909 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim))
22910 (call-interactively #'comment-dwim)))
22913 ;;; Planning
22915 ;; This section contains tools to operate on timestamp objects, as
22916 ;; returned by, e.g. `org-element-context'.
22918 (defun org-timestamp-has-time-p (timestamp)
22919 "Non-nil when TIMESTAMP has a time specified."
22920 (org-element-property :hour-start timestamp))
22922 (defun org-timestamp-format (timestamp format &optional end utc)
22923 "Format a TIMESTAMP element into a string.
22925 FORMAT is a format specifier to be passed to
22926 `format-time-string'.
22928 When optional argument END is non-nil, use end of date-range or
22929 time-range, if possible.
22931 When optional argument UTC is non-nil, time will be expressed as
22932 Universal Time."
22933 (format-time-string
22934 format
22935 (apply 'encode-time
22936 (cons 0
22937 (mapcar
22938 (lambda (prop) (or (org-element-property prop timestamp) 0))
22939 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22940 '(:minute-start :hour-start :day-start :month-start
22941 :year-start)))))
22942 utc))
22944 (defun org-timestamp-split-range (timestamp &optional end)
22945 "Extract a timestamp object from a date or time range.
22947 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22948 the end of the range. Otherwise, extract its start.
22950 Return a new timestamp object sharing the same parent as
22951 TIMESTAMP."
22952 (let ((type (org-element-property :type timestamp)))
22953 (if (memq type '(active inactive diary)) timestamp
22954 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22955 ;; Set new type.
22956 (org-element-put-property
22957 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22958 ;; Copy start properties over end properties if END is
22959 ;; non-nil. Otherwise, copy end properties over `start' ones.
22960 (let ((p-alist '((:minute-start . :minute-end)
22961 (:hour-start . :hour-end)
22962 (:day-start . :day-end)
22963 (:month-start . :month-end)
22964 (:year-start . :year-end))))
22965 (dolist (p-cell p-alist)
22966 (org-element-put-property
22967 split-ts
22968 (funcall (if end 'car 'cdr) p-cell)
22969 (org-element-property
22970 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22971 ;; Eventually refresh `:raw-value'.
22972 (org-element-put-property split-ts :raw-value nil)
22973 (org-element-put-property
22974 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22976 (defun org-timestamp-translate (timestamp &optional boundary)
22977 "Apply `org-translate-time' on a TIMESTAMP object.
22978 When optional argument BOUNDARY is non-nil, it is either the
22979 symbol `start' or `end'. In this case, only translate the
22980 starting or ending part of TIMESTAMP if it is a date or time
22981 range. Otherwise, translate both parts."
22982 (if (and (not boundary)
22983 (memq (org-element-property :type timestamp)
22984 '(active-range inactive-range)))
22985 (concat
22986 (org-translate-time
22987 (org-element-property :raw-value
22988 (org-timestamp-split-range timestamp)))
22989 "--"
22990 (org-translate-time
22991 (org-element-property :raw-value
22992 (org-timestamp-split-range timestamp t))))
22993 (org-translate-time
22994 (org-element-property
22995 :raw-value
22996 (if (not boundary) timestamp
22997 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
23001 ;;; Other stuff.
23003 (defun org-reftex-citation ()
23004 "Use reftex-citation to insert a citation into the buffer.
23005 This looks for a line like
23007 #+BIBLIOGRAPHY: foo plain option:-d
23009 and derives from it that foo.bib is the bibliography file relevant
23010 for this document. It then installs the necessary environment for RefTeX
23011 to work in this buffer and calls `reftex-citation' to insert a citation
23012 into the buffer.
23014 Export of such citations to both LaTeX and HTML is handled by the contributed
23015 package ox-bibtex by Taru Karttunen."
23016 (interactive)
23017 (let ((reftex-docstruct-symbol 'rds)
23018 (reftex-cite-format "\\cite{%l}")
23019 rds bib)
23020 (save-excursion
23021 (save-restriction
23022 (widen)
23023 (let ((case-fold-search t)
23024 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23025 (if (not (save-excursion
23026 (or (re-search-forward re nil t)
23027 (re-search-backward re nil t))))
23028 (error "No bibliography defined in file")
23029 (setq bib (concat (match-string 1) ".bib")
23030 rds (list (list 'bib bib)))))))
23031 (call-interactively 'reftex-citation)))
23033 ;;;; Functions extending outline functionality
23035 (defun org-beginning-of-line (&optional arg)
23036 "Go to the beginning of the current line. If that is invisible, continue
23037 to a visible line beginning. This makes the function of C-a more intuitive.
23038 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
23039 first attempt, and only move to after the tags when the cursor is already
23040 beyond the end of the headline."
23041 (interactive "P")
23042 (let ((pos (point))
23043 (special (if (consp org-special-ctrl-a/e)
23044 (car org-special-ctrl-a/e)
23045 org-special-ctrl-a/e))
23046 deactivate-mark refpos)
23047 (if (org-bound-and-true-p visual-line-mode)
23048 (beginning-of-visual-line 1)
23049 (beginning-of-line 1))
23050 (if (and arg (fboundp 'move-beginning-of-line))
23051 (call-interactively 'move-beginning-of-line)
23052 (if (bobp)
23054 (backward-char 1)
23055 (if (org-truely-invisible-p)
23056 (while (and (not (bobp)) (org-truely-invisible-p))
23057 (backward-char 1)
23058 (beginning-of-line 1))
23059 (forward-char 1))))
23060 (when special
23061 (cond
23062 ((and (looking-at org-complex-heading-regexp)
23063 (= (char-after (match-end 1)) ?\ ))
23064 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23065 (point-at-eol)))
23066 (goto-char
23067 (if (eq special t)
23068 (cond ((> pos refpos) refpos)
23069 ((= pos (point)) refpos)
23070 (t (point)))
23071 (cond ((> pos (point)) (point))
23072 ((not (eq last-command this-command)) (point))
23073 (t refpos)))))
23074 ((org-at-item-p)
23075 ;; Being at an item and not looking at an the item means point
23076 ;; was previously moved to beginning of a visual line, which
23077 ;; doesn't contain the item. Therefore, do nothing special,
23078 ;; just stay here.
23079 (when (looking-at org-list-full-item-re)
23080 ;; Set special position at first white space character after
23081 ;; bullet, and check-box, if any.
23082 (let ((after-bullet
23083 (let ((box (match-end 3)))
23084 (if (not box) (match-end 1)
23085 (let ((after (char-after box)))
23086 (if (and after (= after ? )) (1+ box) box))))))
23087 ;; Special case: Move point to special position when
23088 ;; currently after it or at beginning of line.
23089 (if (eq special t)
23090 (when (or (> pos after-bullet) (= (point) pos))
23091 (goto-char after-bullet))
23092 ;; Reversed case: Move point to special position when
23093 ;; point was already at beginning of line and command is
23094 ;; repeated.
23095 (when (and (= (point) pos) (eq last-command this-command))
23096 (goto-char after-bullet))))))))
23097 (org-no-warnings
23098 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23099 (setq disable-point-adjustment
23100 (or (not (invisible-p (point)))
23101 (not (invisible-p (max (point-min) (1- (point))))))))
23103 (defun org-end-of-line (&optional arg)
23104 "Go to the end of the line.
23105 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23106 tags on the first attempt, and only move to after the tags when
23107 the cursor is already beyond the end of the headline."
23108 (interactive "P")
23109 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
23110 org-special-ctrl-a/e))
23111 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
23112 'end-of-visual-line)
23113 ((fboundp 'move-end-of-line) 'move-end-of-line)
23114 (t 'end-of-line)))
23115 deactivate-mark)
23116 (if (or (not special) arg) (call-interactively move-fun)
23117 (let* ((element (save-excursion (beginning-of-line)
23118 (org-element-at-point)))
23119 (type (org-element-type element)))
23120 (cond
23121 ((memq type '(headline inlinetask))
23122 (let ((pos (point)))
23123 (beginning-of-line 1)
23124 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
23125 (if (eq special t)
23126 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
23127 (goto-char (match-beginning 1))
23128 (goto-char (match-end 0)))
23129 (if (or (< pos (match-end 0))
23130 (not (eq this-command last-command)))
23131 (goto-char (match-end 0))
23132 (goto-char (match-beginning 1))))
23133 (call-interactively move-fun))))
23134 ((outline-invisible-p (line-end-position))
23135 ;; If element is hidden, `move-end-of-line' would put point
23136 ;; after it. Use `end-of-line' to stay on current line.
23137 (call-interactively 'end-of-line))
23138 (t (call-interactively move-fun)))))
23139 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23140 (setq disable-point-adjustment
23141 (or (not (invisible-p (point)))
23142 (not (invisible-p (max (point-min) (1- (point))))))))
23144 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23145 (define-key org-mode-map "\C-e" 'org-end-of-line)
23147 (defun org-backward-sentence (&optional arg)
23148 "Go to beginning of sentence, or beginning of table field.
23149 This will call `backward-sentence' or `org-table-beginning-of-field',
23150 depending on context."
23151 (interactive "P")
23152 (cond
23153 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
23154 (t (call-interactively 'backward-sentence))))
23156 (defun org-forward-sentence (&optional arg)
23157 "Go to end of sentence, or end of table field.
23158 This will call `forward-sentence' or `org-table-end-of-field',
23159 depending on context."
23160 (interactive "P")
23161 (cond
23162 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
23163 (t (call-interactively 'forward-sentence))))
23165 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23166 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23168 (defun org-kill-line (&optional arg)
23169 "Kill line, to tags or end of line."
23170 (interactive "P")
23171 (cond
23172 ((or (not org-special-ctrl-k)
23173 (bolp)
23174 (not (org-at-heading-p)))
23175 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23176 org-ctrl-k-protect-subtree)
23177 (if (or (eq org-ctrl-k-protect-subtree 'error)
23178 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
23179 (user-error "C-k aborted as it would kill a hidden subtree")))
23180 (call-interactively
23181 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23182 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
23183 (kill-region (point) (match-beginning 1))
23184 (org-set-tags nil t))
23185 (t (kill-region (point) (point-at-eol)))))
23187 (define-key org-mode-map "\C-k" 'org-kill-line)
23189 (defun org-yank (&optional arg)
23190 "Yank. If the kill is a subtree, treat it specially.
23191 This command will look at the current kill and check if is a single
23192 subtree, or a series of subtrees[1]. If it passes the test, and if the
23193 cursor is at the beginning of a line or after the stars of a currently
23194 empty headline, then the yank is handled specially. How exactly depends
23195 on the value of the following variables, both set by default.
23197 org-yank-folded-subtrees
23198 When set, the subtree(s) will be folded after insertion, but only
23199 if doing so would now swallow text after the yanked text.
23201 org-yank-adjusted-subtrees
23202 When set, the subtree will be promoted or demoted in order to
23203 fit into the local outline tree structure, which means that the level
23204 will be adjusted so that it becomes the smaller one of the two
23205 *visible* surrounding headings.
23207 Any prefix to this command will cause `yank' to be called directly with
23208 no special treatment. In particular, a simple \\[universal-argument] prefix \
23209 will just
23210 plainly yank the text as it is.
23212 \[1] The test checks if the first non-white line is a heading
23213 and if there are no other headings with fewer stars."
23214 (interactive "P")
23215 (org-yank-generic 'yank arg))
23217 (defun org-yank-generic (command arg)
23218 "Perform some yank-like command.
23220 This function implements the behavior described in the `org-yank'
23221 documentation. However, it has been generalized to work for any
23222 interactive command with similar behavior."
23224 ;; pretend to be command COMMAND
23225 (setq this-command command)
23227 (if arg
23228 (call-interactively command)
23230 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23231 (and (org-kill-is-subtree-p)
23232 (or (bolp)
23233 (and (looking-at "[ \t]*$")
23234 (string-match
23235 "\\`\\*+\\'"
23236 (buffer-substring (point-at-bol) (point)))))))
23237 swallowp)
23238 (cond
23239 ((and subtreep org-yank-folded-subtrees)
23240 (let ((beg (point))
23241 end)
23242 (if (and subtreep org-yank-adjusted-subtrees)
23243 (org-paste-subtree nil nil 'for-yank)
23244 (call-interactively command))
23246 (setq end (point))
23247 (goto-char beg)
23248 (when (and (bolp) subtreep
23249 (not (setq swallowp
23250 (org-yank-folding-would-swallow-text beg end))))
23251 (org-with-limited-levels
23252 (or (looking-at org-outline-regexp)
23253 (re-search-forward org-outline-regexp-bol end t))
23254 (while (and (< (point) end) (looking-at org-outline-regexp))
23255 (hide-subtree)
23256 (org-cycle-show-empty-lines 'folded)
23257 (condition-case nil
23258 (outline-forward-same-level 1)
23259 (error (goto-char end))))))
23260 (when swallowp
23261 (message
23262 "Inserted text not folded because that would swallow text"))
23264 (goto-char end)
23265 (skip-chars-forward " \t\n\r")
23266 (beginning-of-line 1)
23267 (push-mark beg 'nomsg)))
23268 ((and subtreep org-yank-adjusted-subtrees)
23269 (let ((beg (point-at-bol)))
23270 (org-paste-subtree nil nil 'for-yank)
23271 (push-mark beg 'nomsg)))
23273 (call-interactively command))))))
23275 (defun org-yank-folding-would-swallow-text (beg end)
23276 "Would hide-subtree at BEG swallow any text after END?"
23277 (let (level)
23278 (org-with-limited-levels
23279 (save-excursion
23280 (goto-char beg)
23281 (when (or (looking-at org-outline-regexp)
23282 (re-search-forward org-outline-regexp-bol end t))
23283 (setq level (org-outline-level)))
23284 (goto-char end)
23285 (skip-chars-forward " \t\r\n\v\f")
23286 (if (or (eobp)
23287 (and (bolp) (looking-at org-outline-regexp)
23288 (<= (org-outline-level) level)))
23289 nil ; Nothing would be swallowed
23290 t))))) ; something would swallow
23292 (define-key org-mode-map "\C-y" 'org-yank)
23294 (defun org-truely-invisible-p ()
23295 "Check if point is at a character currently not visible.
23296 This version does not only check the character property, but also
23297 `visible-mode'."
23298 ;; Early versions of noutline don't have `outline-invisible-p'.
23299 (if (org-bound-and-true-p visible-mode)
23301 (outline-invisible-p)))
23303 (defun org-invisible-p2 ()
23304 "Check if point is at a character currently not visible."
23305 (save-excursion
23306 (if (and (eolp) (not (bobp))) (backward-char 1))
23307 ;; Early versions of noutline don't have `outline-invisible-p'.
23308 (outline-invisible-p)))
23310 (defun org-back-to-heading (&optional invisible-ok)
23311 "Call `outline-back-to-heading', but provide a better error message."
23312 (condition-case nil
23313 (outline-back-to-heading invisible-ok)
23314 (error (error "Before first headline at position %d in buffer %s"
23315 (point) (current-buffer)))))
23317 (defun org-before-first-heading-p ()
23318 "Before first heading?"
23319 (save-excursion
23320 (end-of-line)
23321 (null (re-search-backward org-outline-regexp-bol nil t))))
23323 (defun org-at-heading-p (&optional ignored)
23324 (outline-on-heading-p t))
23325 ;; Compatibility alias with Org versions < 7.8.03
23326 (defalias 'org-on-heading-p 'org-at-heading-p)
23328 (defun org-in-commented-heading-p (&optional no-inheritance)
23329 "Non-nil if point is under a commented heading.
23330 This function also checks ancestors of the current headline,
23331 unless optional argument NO-INHERITANCE is non-nil."
23332 (cond
23333 ((org-before-first-heading-p) nil)
23334 ((let ((headline (nth 4 (org-heading-components))))
23335 (and headline
23336 (let ((case-fold-search nil))
23337 (org-string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
23338 headline)))))
23339 (no-inheritance nil)
23341 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
23343 (defun org-at-comment-p nil
23344 "Is cursor in a line starting with a # character?"
23345 (save-excursion
23346 (beginning-of-line)
23347 (looking-at "^#")))
23349 (defun org-at-drawer-p nil
23350 "Is cursor at a drawer keyword?"
23351 (save-excursion
23352 (move-beginning-of-line 1)
23353 (looking-at org-drawer-regexp)))
23355 (defun org-at-block-p nil
23356 "Is cursor at a block keyword?"
23357 (save-excursion
23358 (move-beginning-of-line 1)
23359 (looking-at org-block-regexp)))
23361 (defun org-point-at-end-of-empty-headline ()
23362 "If point is at the end of an empty headline, return t, else nil.
23363 If the heading only contains a TODO keyword, it is still still considered
23364 empty."
23365 (and (looking-at "[ \t]*$")
23366 (when org-todo-line-regexp
23367 (save-excursion
23368 (beginning-of-line 1)
23369 (let ((case-fold-search nil))
23370 (looking-at org-todo-line-regexp)
23371 (string= (match-string 3) ""))))))
23373 (defun org-at-heading-or-item-p ()
23374 (or (org-at-heading-p) (org-at-item-p)))
23376 (defun org-at-target-p ()
23377 (or (org-in-regexp org-radio-target-regexp)
23378 (org-in-regexp org-target-regexp)))
23379 ;; Compatibility alias with Org versions < 7.8.03
23380 (defalias 'org-on-target-p 'org-at-target-p)
23382 (defun org-up-heading-all (arg)
23383 "Move to the heading line of which the present line is a subheading.
23384 This function considers both visible and invisible heading lines.
23385 With argument, move up ARG levels."
23386 (if (fboundp 'outline-up-heading-all)
23387 (outline-up-heading-all arg) ; emacs 21 version of outline.el
23388 (outline-up-heading arg t))) ; emacs 22 version of outline.el
23390 (defun org-up-heading-safe ()
23391 "Move to the heading line of which the present line is a subheading.
23392 This version will not throw an error. It will return the level of the
23393 headline found, or nil if no higher level is found.
23395 Also, this function will be a lot faster than `outline-up-heading',
23396 because it relies on stars being the outline starters. This can really
23397 make a significant difference in outlines with very many siblings."
23398 (let (start-level re)
23399 (org-back-to-heading t)
23400 (setq start-level (funcall outline-level))
23401 (if (equal start-level 1)
23403 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
23404 (if (re-search-backward re nil t)
23405 (funcall outline-level)))))
23407 (defun org-first-sibling-p ()
23408 "Is this heading the first child of its parents?"
23409 (interactive)
23410 (let ((re org-outline-regexp-bol)
23411 level l)
23412 (unless (org-at-heading-p t)
23413 (user-error "Not at a heading"))
23414 (setq level (funcall outline-level))
23415 (save-excursion
23416 (if (not (re-search-backward re nil t))
23418 (setq l (funcall outline-level))
23419 (< l level)))))
23421 (defun org-goto-sibling (&optional previous)
23422 "Goto the next sibling, even if it is invisible.
23423 When PREVIOUS is set, go to the previous sibling instead. Returns t
23424 when a sibling was found. When none is found, return nil and don't
23425 move point."
23426 (let ((fun (if previous 're-search-backward 're-search-forward))
23427 (pos (point))
23428 (re org-outline-regexp-bol)
23429 level l)
23430 (when (condition-case nil (org-back-to-heading t) (error nil))
23431 (setq level (funcall outline-level))
23432 (catch 'exit
23433 (or previous (forward-char 1))
23434 (while (funcall fun re nil t)
23435 (setq l (funcall outline-level))
23436 (when (< l level) (goto-char pos) (throw 'exit nil))
23437 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23438 (goto-char pos)
23439 nil))))
23441 (defun org-show-siblings ()
23442 "Show all siblings of the current headline."
23443 (save-excursion
23444 (while (org-goto-sibling) (org-flag-heading nil)))
23445 (save-excursion
23446 (while (org-goto-sibling 'previous)
23447 (org-flag-heading nil))))
23449 (defun org-goto-first-child ()
23450 "Goto the first child, even if it is invisible.
23451 Return t when a child was found. Otherwise don't move point and
23452 return nil."
23453 (let (level (pos (point)) (re org-outline-regexp-bol))
23454 (when (condition-case nil (org-back-to-heading t) (error nil))
23455 (setq level (outline-level))
23456 (forward-char 1)
23457 (if (and (re-search-forward re nil t) (> (outline-level) level))
23458 (progn (goto-char (match-beginning 0)) t)
23459 (goto-char pos) nil))))
23461 (defun org-show-hidden-entry ()
23462 "Show an entry where even the heading is hidden."
23463 (save-excursion
23464 (org-show-entry)))
23466 (defun org-flag-heading (flag &optional entry)
23467 "Flag the current heading. FLAG non-nil means make invisible.
23468 When ENTRY is non-nil, show the entire entry."
23469 (save-excursion
23470 (org-back-to-heading t)
23471 ;; Check if we should show the entire entry
23472 (if entry
23473 (progn
23474 (org-show-entry)
23475 (save-excursion
23476 (and (outline-next-heading)
23477 (org-flag-heading nil))))
23478 (outline-flag-region (max (point-min) (1- (point)))
23479 (save-excursion (outline-end-of-heading) (point))
23480 flag))))
23482 (defun org-get-next-sibling ()
23483 "Move to next heading of the same level, and return point.
23484 If there is no such heading, return nil.
23485 This is like outline-next-sibling, but invisible headings are ok."
23486 (let ((level (funcall outline-level)))
23487 (outline-next-heading)
23488 (while (and (not (eobp)) (> (funcall outline-level) level))
23489 (outline-next-heading))
23490 (if (or (eobp) (< (funcall outline-level) level))
23492 (point))))
23494 (defun org-get-last-sibling ()
23495 "Move to previous heading of the same level, and return point.
23496 If there is no such heading, return nil."
23497 (let ((opoint (point))
23498 (level (funcall outline-level)))
23499 (outline-previous-heading)
23500 (when (and (/= (point) opoint) (outline-on-heading-p t))
23501 (while (and (> (funcall outline-level) level)
23502 (not (bobp)))
23503 (outline-previous-heading))
23504 (if (< (funcall outline-level) level)
23506 (point)))))
23508 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23509 "Goto to the end of a subtree."
23510 ;; This contains an exact copy of the original function, but it uses
23511 ;; `org-back-to-heading', to make it work also in invisible
23512 ;; trees. And is uses an invisible-ok argument.
23513 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23514 ;; Furthermore, when used inside Org, finding the end of a large subtree
23515 ;; with many children and grandchildren etc, this can be much faster
23516 ;; than the outline version.
23517 (org-back-to-heading invisible-ok)
23518 (let ((first t)
23519 (level (funcall outline-level)))
23520 (if (and (derived-mode-p 'org-mode) (< level 1000))
23521 ;; A true heading (not a plain list item), in Org-mode
23522 ;; This means we can easily find the end by looking
23523 ;; only for the right number of stars. Using a regexp to do
23524 ;; this is so much faster than using a Lisp loop.
23525 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23526 (forward-char 1)
23527 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23528 ;; something else, do it the slow way
23529 (while (and (not (eobp))
23530 (or first (> (funcall outline-level) level)))
23531 (setq first nil)
23532 (outline-next-heading)))
23533 (unless to-heading
23534 (if (memq (preceding-char) '(?\n ?\^M))
23535 (progn
23536 ;; Go to end of line before heading
23537 (forward-char -1)
23538 (if (memq (preceding-char) '(?\n ?\^M))
23539 ;; leave blank line before heading
23540 (forward-char -1))))))
23541 (point))
23543 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
23544 "Use Org version in org-mode, for dramatic speed-up."
23545 (if (derived-mode-p 'org-mode)
23546 (progn
23547 (org-end-of-subtree nil t)
23548 (unless (eobp) (backward-char 1)))
23549 ad-do-it))
23551 (defun org-end-of-meta-data-and-drawers ()
23552 "Jump to the first text after meta data and drawers in the current entry.
23553 This will move over empty lines, lines with planning time stamps,
23554 clocking lines, and drawers."
23555 (org-back-to-heading t)
23556 (let ((end (save-excursion (outline-next-heading) (point)))
23557 (re (concat "\\(" org-drawer-regexp "\\)"
23558 "\\|" "[ \t]*" org-keyword-time-regexp)))
23559 (forward-line 1)
23560 (while (re-search-forward re end t)
23561 (if (not (match-end 1))
23562 ;; empty or planning line
23563 (forward-line 1)
23564 ;; a drawer, find the end
23565 (re-search-forward "^[ \t]*:END:" end 'move)
23566 (forward-line 1)))
23567 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23568 (point)))
23570 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23571 "Move forward to the ARG'th subheading at same level as this one.
23572 Stop at the first and last subheadings of a superior heading.
23573 Normally this only looks at visible headings, but when INVISIBLE-OK is
23574 non-nil it will also look at invisible ones."
23575 (interactive "p")
23576 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23577 (if (and arg (< arg 0))
23578 (goto-char (point-min))
23579 (outline-next-heading))
23580 (org-at-heading-p)
23581 (let ((level (- (match-end 0) (match-beginning 0) 1))
23582 (f (if (and arg (< arg 0))
23583 're-search-backward
23584 're-search-forward))
23585 (count (if arg (abs arg) 1))
23586 (result (point)))
23587 (while (and (prog1 (> count 0)
23588 (forward-char (if (and arg (< arg 0)) -1 1)))
23589 (funcall f org-outline-regexp-bol nil 'move))
23590 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23591 (cond ((< l level) (setq count 0))
23592 ((and (= l level)
23593 (or invisible-ok
23594 (progn
23595 (goto-char (line-beginning-position))
23596 (not (outline-invisible-p)))))
23597 (setq count (1- count))
23598 (when (eq l level)
23599 (setq result (point)))))))
23600 (goto-char result))
23601 (beginning-of-line 1)))
23603 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23604 "Move backward to the ARG'th subheading at same level as this one.
23605 Stop at the first and last subheadings of a superior heading."
23606 (interactive "p")
23607 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23609 (defun org-next-block (arg &optional backward block-regexp)
23610 "Jump to the next block.
23611 With a prefix argument ARG, jump forward ARG many source blocks.
23612 When BACKWARD is non-nil, jump to the previous block.
23613 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23614 (interactive "p")
23615 (let ((re (or block-regexp org-block-regexp))
23616 (re-search-fn (or (and backward 're-search-backward)
23617 're-search-forward)))
23618 (if (looking-at re) (forward-char 1))
23619 (condition-case nil
23620 (funcall re-search-fn re nil nil arg)
23621 (error (error "No %s code blocks" (if backward "previous" "further" ))))
23622 (goto-char (match-beginning 0)) (org-show-context)))
23624 (defun org-previous-block (arg &optional block-regexp)
23625 "Jump to the previous block.
23626 With a prefix argument ARG, jump backward ARG many source blocks.
23627 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23628 (interactive "p")
23629 (org-next-block arg t block-regexp))
23631 (defun org-forward-paragraph ()
23632 "Move forward to beginning of next paragraph or equivalent.
23634 The function moves point to the beginning of the next visible
23635 structural element, which can be a paragraph, a table, a list
23636 item, etc. It also provides some special moves for convenience:
23638 - On an affiliated keyword, jump to the beginning of the
23639 relative element.
23640 - On an item or a footnote definition, move to the second
23641 element inside, if any.
23642 - On a table or a property drawer, jump after it.
23643 - On a verse or source block, stop after blank lines."
23644 (interactive)
23645 (when (eobp) (user-error "Cannot move further down"))
23646 (let* ((deactivate-mark nil)
23647 (element (org-element-at-point))
23648 (type (org-element-type element))
23649 (post-affiliated (org-element-property :post-affiliated element))
23650 (contents-begin (org-element-property :contents-begin element))
23651 (contents-end (org-element-property :contents-end element))
23652 (end (let ((end (org-element-property :end element)) (parent element))
23653 (while (and (setq parent (org-element-property :parent parent))
23654 (= (org-element-property :contents-end parent) end))
23655 (setq end (org-element-property :end parent)))
23656 end)))
23657 (cond ((not element)
23658 (skip-chars-forward " \r\t\n")
23659 (or (eobp) (beginning-of-line)))
23660 ;; On affiliated keywords, move to element's beginning.
23661 ((and post-affiliated (< (point) post-affiliated))
23662 (goto-char post-affiliated))
23663 ;; At a table row, move to the end of the table. Similarly,
23664 ;; at a node property, move to the end of the property
23665 ;; drawer.
23666 ((memq type '(node-property table-row))
23667 (goto-char (org-element-property
23668 :end (org-element-property :parent element))))
23669 ((memq type '(property-drawer table)) (goto-char end))
23670 ;; Consider blank lines as separators in verse and source
23671 ;; blocks to ease editing.
23672 ((memq type '(src-block verse-block))
23673 (when (eq type 'src-block)
23674 (setq contents-end
23675 (save-excursion (goto-char end)
23676 (skip-chars-backward " \r\t\n")
23677 (line-beginning-position))))
23678 (beginning-of-line)
23679 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23680 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23681 (goto-char end)
23682 (skip-chars-forward " \r\t\n")
23683 (if (= (point) contents-end) (goto-char end)
23684 (beginning-of-line))))
23685 ;; With no contents, just skip element.
23686 ((not contents-begin) (goto-char end))
23687 ;; If contents are invisible, skip the element altogether.
23688 ((outline-invisible-p (line-end-position))
23689 (case type
23690 (headline
23691 (org-with-limited-levels (outline-next-visible-heading 1)))
23692 ;; At a plain list, make sure we move to the next item
23693 ;; instead of skipping the whole list.
23694 (plain-list (forward-char)
23695 (org-forward-paragraph))
23696 (otherwise (goto-char end))))
23697 ((>= (point) contents-end) (goto-char end))
23698 ((>= (point) contents-begin)
23699 ;; This can only happen on paragraphs and plain lists.
23700 (case type
23701 (paragraph (goto-char end))
23702 ;; At a plain list, try to move to second element in
23703 ;; first item, if possible.
23704 (plain-list (end-of-line)
23705 (org-forward-paragraph))))
23706 ;; When contents start on the middle of a line (e.g. in
23707 ;; items and footnote definitions), try to reach first
23708 ;; element starting after current line.
23709 ((> (line-end-position) contents-begin)
23710 (end-of-line)
23711 (org-forward-paragraph))
23712 (t (goto-char contents-begin)))))
23714 (defun org-backward-paragraph ()
23715 "Move backward to start of previous paragraph or equivalent.
23717 The function moves point to the beginning of the current
23718 structural element, which can be a paragraph, a table, a list
23719 item, etc., or to the beginning of the previous visible one if
23720 point is already there. It also provides some special moves for
23721 convenience:
23723 - On an affiliated keyword, jump to the first one.
23724 - On a table or a property drawer, move to its beginning.
23725 - On a verse or source block, stop before blank lines."
23726 (interactive)
23727 (when (bobp) (user-error "Cannot move further up"))
23728 (let* ((deactivate-mark nil)
23729 (element (org-element-at-point))
23730 (type (org-element-type element))
23731 (contents-begin (org-element-property :contents-begin element))
23732 (contents-end (org-element-property :contents-end element))
23733 (post-affiliated (org-element-property :post-affiliated element))
23734 (begin (org-element-property :begin element)))
23735 (cond
23736 ((not element) (goto-char (point-min)))
23737 ((= (point) begin)
23738 (backward-char)
23739 (org-backward-paragraph))
23740 ((and post-affiliated (<= (point) post-affiliated)) (goto-char begin))
23741 ((memq type '(node-property table-row))
23742 (goto-char (org-element-property
23743 :post-affiliated (org-element-property :parent element))))
23744 ((memq type '(property-drawer table)) (goto-char begin))
23745 ((memq type '(src-block verse-block))
23746 (when (eq type 'src-block)
23747 (setq contents-begin
23748 (save-excursion (goto-char begin) (forward-line) (point))))
23749 (if (= (point) contents-begin) (goto-char post-affiliated)
23750 ;; Inside a verse block, see blank lines as paragraph
23751 ;; separators.
23752 (let ((origin (point)))
23753 (skip-chars-backward " \r\t\n" contents-begin)
23754 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
23755 (skip-chars-forward " \r\t\n" origin)
23756 (if (= (point) origin) (goto-char contents-begin)
23757 (beginning-of-line))))))
23758 ((not contents-begin) (goto-char (or post-affiliated begin)))
23759 ((eq type 'paragraph)
23760 (goto-char contents-begin)
23761 ;; When at first paragraph in an item or a footnote definition,
23762 ;; move directly to beginning of line.
23763 (let ((parent-contents
23764 (org-element-property
23765 :contents-begin (org-element-property :parent element))))
23766 (when (and parent-contents (= parent-contents contents-begin))
23767 (beginning-of-line))))
23768 ;; At the end of a greater element, move to the beginning of the
23769 ;; last element within.
23770 ((>= (point) contents-end)
23771 (goto-char (1- contents-end))
23772 (org-backward-paragraph))
23773 (t (goto-char (or post-affiliated begin))))
23774 ;; Ensure we never leave point invisible.
23775 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
23777 (defun org-forward-element ()
23778 "Move forward by one element.
23779 Move to the next element at the same level, when possible."
23780 (interactive)
23781 (cond ((eobp) (user-error "Cannot move further down"))
23782 ((org-with-limited-levels (org-at-heading-p))
23783 (let ((origin (point)))
23784 (goto-char (org-end-of-subtree nil t))
23785 (unless (org-with-limited-levels (org-at-heading-p))
23786 (goto-char origin)
23787 (user-error "Cannot move further down"))))
23789 (let* ((elem (org-element-at-point))
23790 (end (org-element-property :end elem))
23791 (parent (org-element-property :parent elem)))
23792 (cond ((and parent (= (org-element-property :contents-end parent) end))
23793 (goto-char (org-element-property :end parent)))
23794 ((integer-or-marker-p end) (goto-char end))
23795 (t (message "No element at point")))))))
23797 (defun org-backward-element ()
23798 "Move backward by one element.
23799 Move to the previous element at the same level, when possible."
23800 (interactive)
23801 (cond ((bobp) (user-error "Cannot move further up"))
23802 ((org-with-limited-levels (org-at-heading-p))
23803 ;; At a headline, move to the previous one, if any, or stay
23804 ;; here.
23805 (let ((origin (point)))
23806 (org-with-limited-levels (org-backward-heading-same-level 1))
23807 ;; When current headline has no sibling above, move to its
23808 ;; parent.
23809 (when (= (point) origin)
23810 (or (org-with-limited-levels (org-up-heading-safe))
23811 (progn (goto-char origin)
23812 (user-error "Cannot move further up"))))))
23814 (let* ((elem (org-element-at-point))
23815 (beg (org-element-property :begin elem)))
23816 (cond
23817 ;; Move to beginning of current element if point isn't
23818 ;; there already.
23819 ((null beg) (message "No element at point"))
23820 ((/= (point) beg) (goto-char beg))
23821 (t (goto-char beg)
23822 (skip-chars-backward " \r\t\n")
23823 (unless (bobp)
23824 (let ((prev (org-element-at-point)))
23825 (goto-char (org-element-property :begin prev))
23826 (while (and (setq prev (org-element-property :parent prev))
23827 (<= (org-element-property :end prev) beg))
23828 (goto-char (org-element-property :begin prev)))))))))))
23830 (defun org-up-element ()
23831 "Move to upper element."
23832 (interactive)
23833 (if (org-with-limited-levels (org-at-heading-p))
23834 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23835 (let* ((elem (org-element-at-point))
23836 (parent (org-element-property :parent elem)))
23837 (if parent (goto-char (org-element-property :begin parent))
23838 (if (org-with-limited-levels (org-before-first-heading-p))
23839 (user-error "No surrounding element")
23840 (org-with-limited-levels (org-back-to-heading)))))))
23842 (defvar org-element-greater-elements)
23843 (defun org-down-element ()
23844 "Move to inner element."
23845 (interactive)
23846 (let ((element (org-element-at-point)))
23847 (cond
23848 ((memq (org-element-type element) '(plain-list table))
23849 (goto-char (org-element-property :contents-begin element))
23850 (forward-char))
23851 ((memq (org-element-type element) org-element-greater-elements)
23852 ;; If contents are hidden, first disclose them.
23853 (when (outline-invisible-p (line-end-position)) (org-cycle))
23854 (goto-char (or (org-element-property :contents-begin element)
23855 (user-error "No content for this element"))))
23856 (t (user-error "No inner element")))))
23858 (defun org-drag-element-backward ()
23859 "Move backward element at point."
23860 (interactive)
23861 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
23862 (let* ((elem (org-element-at-point))
23863 (prev-elem
23864 (save-excursion
23865 (goto-char (org-element-property :begin elem))
23866 (skip-chars-backward " \r\t\n")
23867 (unless (bobp)
23868 (let* ((beg (org-element-property :begin elem))
23869 (prev (org-element-at-point))
23870 (up prev))
23871 (while (and (setq up (org-element-property :parent up))
23872 (<= (org-element-property :end prev) beg))
23873 (setq prev up))
23874 prev)))))
23875 ;; Error out if no previous element or previous element is
23876 ;; a parent of the current one.
23877 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23878 (user-error "Cannot drag element backward")
23879 (let ((pos (point)))
23880 (org-element-swap-A-B prev-elem elem)
23881 (goto-char (+ (org-element-property :begin prev-elem)
23882 (- pos (org-element-property :begin elem)))))))))
23884 (defun org-drag-element-forward ()
23885 "Move forward element at point."
23886 (interactive)
23887 (let* ((pos (point))
23888 (elem (org-element-at-point)))
23889 (when (= (point-max) (org-element-property :end elem))
23890 (user-error "Cannot drag element forward"))
23891 (goto-char (org-element-property :end elem))
23892 (let ((next-elem (org-element-at-point)))
23893 (when (or (org-element-nested-p elem next-elem)
23894 (and (eq (org-element-type next-elem) 'headline)
23895 (not (eq (org-element-type elem) 'headline))))
23896 (goto-char pos)
23897 (user-error "Cannot drag element forward"))
23898 ;; Compute new position of point: it's shifted by NEXT-ELEM
23899 ;; body's length (without final blanks) and by the length of
23900 ;; blanks between ELEM and NEXT-ELEM.
23901 (let ((size-next (- (save-excursion
23902 (goto-char (org-element-property :end next-elem))
23903 (skip-chars-backward " \r\t\n")
23904 (forward-line)
23905 ;; Small correction if buffer doesn't end
23906 ;; with a newline character.
23907 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23908 (org-element-property :begin next-elem)))
23909 (size-blank (- (org-element-property :end elem)
23910 (save-excursion
23911 (goto-char (org-element-property :end elem))
23912 (skip-chars-backward " \r\t\n")
23913 (forward-line)
23914 (point)))))
23915 (org-element-swap-A-B elem next-elem)
23916 (goto-char (+ pos size-next size-blank))))))
23918 (defun org-drag-line-forward (arg)
23919 "Drag the line at point ARG lines forward."
23920 (interactive "p")
23921 (dotimes (n (abs arg))
23922 (let ((c (current-column)))
23923 (if (< 0 arg)
23924 (progn
23925 (beginning-of-line 2)
23926 (transpose-lines 1)
23927 (beginning-of-line 0))
23928 (transpose-lines 1)
23929 (beginning-of-line -1))
23930 (org-move-to-column c))))
23932 (defun org-drag-line-backward (arg)
23933 "Drag the line at point ARG lines backward."
23934 (interactive "p")
23935 (org-drag-line-forward (- arg)))
23937 (defun org-mark-element ()
23938 "Put point at beginning of this element, mark at end.
23940 Interactively, if this command is repeated or (in Transient Mark
23941 mode) if the mark is active, it marks the next element after the
23942 ones already marked."
23943 (interactive)
23944 (let (deactivate-mark)
23945 (if (and (org-called-interactively-p 'any)
23946 (or (and (eq last-command this-command) (mark t))
23947 (and transient-mark-mode mark-active)))
23948 (set-mark
23949 (save-excursion
23950 (goto-char (mark))
23951 (goto-char (org-element-property :end (org-element-at-point)))))
23952 (let ((element (org-element-at-point)))
23953 (end-of-line)
23954 (push-mark (org-element-property :end element) t t)
23955 (goto-char (org-element-property :begin element))))))
23957 (defun org-narrow-to-element ()
23958 "Narrow buffer to current element."
23959 (interactive)
23960 (let ((elem (org-element-at-point)))
23961 (cond
23962 ((eq (car elem) 'headline)
23963 (narrow-to-region
23964 (org-element-property :begin elem)
23965 (org-element-property :end elem)))
23966 ((memq (car elem) org-element-greater-elements)
23967 (narrow-to-region
23968 (org-element-property :contents-begin elem)
23969 (org-element-property :contents-end elem)))
23971 (narrow-to-region
23972 (org-element-property :begin elem)
23973 (org-element-property :end elem))))))
23975 (defun org-transpose-element ()
23976 "Transpose current and previous elements, keeping blank lines between.
23977 Point is moved after both elements."
23978 (interactive)
23979 (org-skip-whitespace)
23980 (let ((end (org-element-property :end (org-element-at-point))))
23981 (org-drag-element-backward)
23982 (goto-char end)))
23984 (defun org-unindent-buffer ()
23985 "Un-indent the visible part of the buffer.
23986 Relative indentation (between items, inside blocks, etc.) isn't
23987 modified."
23988 (interactive)
23989 (unless (eq major-mode 'org-mode)
23990 (user-error "Cannot un-indent a buffer not in Org mode"))
23991 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23992 unindent-tree ; For byte-compiler.
23993 (unindent-tree
23994 (function
23995 (lambda (contents)
23996 (mapc
23997 (lambda (element)
23998 (if (memq (org-element-type element) '(headline section))
23999 (funcall unindent-tree (org-element-contents element))
24000 (save-excursion
24001 (save-restriction
24002 (narrow-to-region
24003 (org-element-property :begin element)
24004 (org-element-property :end element))
24005 (org-do-remove-indentation)))))
24006 (reverse contents))))))
24007 (funcall unindent-tree (org-element-contents parse-tree))))
24009 (defun org-show-subtree ()
24010 "Show everything after this heading at deeper levels."
24011 (interactive)
24012 (outline-flag-region
24013 (point)
24014 (save-excursion
24015 (org-end-of-subtree t t))
24016 nil))
24018 (defun org-show-entry ()
24019 "Show the body directly following this heading.
24020 Show the heading too, if it is currently invisible."
24021 (interactive)
24022 (save-excursion
24023 (condition-case nil
24024 (progn
24025 (org-back-to-heading t)
24026 (outline-flag-region
24027 (max (point-min) (1- (point)))
24028 (save-excursion
24029 (if (re-search-forward
24030 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24031 (match-beginning 1)
24032 (point-max)))
24033 nil)
24034 (org-cycle-hide-drawers 'children))
24035 (error nil))))
24037 (defun org-make-options-regexp (kwds &optional extra)
24038 "Make a regular expression for keyword lines."
24039 (concat
24040 "^[ \t]*#\\+\\("
24041 (mapconcat 'regexp-quote kwds "\\|")
24042 (if extra (concat "\\|" extra))
24043 "\\):[ \t]*\\(.*\\)"))
24045 ;; Make isearch reveal the necessary context
24046 (defun org-isearch-end ()
24047 "Reveal context after isearch exits."
24048 (when isearch-success ; only if search was successful
24049 (if (featurep 'xemacs)
24050 ;; Under XEmacs, the hook is run in the correct place,
24051 ;; we directly show the context.
24052 (org-show-context 'isearch)
24053 ;; In Emacs the hook runs *before* restoring the overlays.
24054 ;; So we have to use a one-time post-command-hook to do this.
24055 ;; (Emacs 22 has a special variable, see function `org-mode')
24056 (unless (and (boundp 'isearch-mode-end-hook-quit)
24057 isearch-mode-end-hook-quit)
24058 ;; Only when the isearch was not quitted.
24059 (org-add-hook 'post-command-hook 'org-isearch-post-command
24060 'append 'local)))
24061 (org-fix-ellipsis-at-bol)))
24063 (defun org-isearch-post-command ()
24064 "Remove self from hook, and show context."
24065 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
24066 (org-show-context 'isearch))
24069 ;;;; Integration with and fixes for other packages
24071 ;;; Imenu support
24073 (defvar org-imenu-markers nil
24074 "All markers currently used by Imenu.")
24075 (make-variable-buffer-local 'org-imenu-markers)
24077 (defun org-imenu-new-marker (&optional pos)
24078 "Return a new marker for use by Imenu, and remember the marker."
24079 (let ((m (make-marker)))
24080 (move-marker m (or pos (point)))
24081 (push m org-imenu-markers)
24084 (defun org-imenu-get-tree ()
24085 "Produce the index for Imenu."
24086 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
24087 (setq org-imenu-markers nil)
24088 (let* ((n org-imenu-depth)
24089 (re (concat "^" (org-get-limited-outline-regexp)))
24090 (subs (make-vector (1+ n) nil))
24091 (last-level 0)
24092 m level head0 head)
24093 (save-excursion
24094 (save-restriction
24095 (widen)
24096 (goto-char (point-max))
24097 (while (re-search-backward re nil t)
24098 (setq level (org-reduced-level (funcall outline-level)))
24099 (when (and (<= level n)
24100 (looking-at org-complex-heading-regexp)
24101 (setq head0 (org-match-string-no-properties 4)))
24102 (setq head (org-link-display-format head0)
24103 m (org-imenu-new-marker))
24104 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24105 (if (>= level last-level)
24106 (push (cons head m) (aref subs level))
24107 (push (cons head (aref subs (1+ level))) (aref subs level))
24108 (loop for i from (1+ level) to n do (aset subs i nil)))
24109 (setq last-level level)))))
24110 (aref subs 1)))
24112 (eval-after-load "imenu"
24113 '(progn
24114 (add-hook 'imenu-after-jump-hook
24115 (lambda ()
24116 (if (derived-mode-p 'org-mode)
24117 (org-show-context 'org-goto))))))
24119 (defun org-link-display-format (link)
24120 "Replace a link with its the description.
24121 If there is no description, use the link target."
24122 (save-match-data
24123 (if (string-match org-bracket-link-analytic-regexp link)
24124 (replace-match (if (match-end 5)
24125 (match-string 5 link)
24126 (concat (match-string 1 link)
24127 (match-string 3 link)))
24128 nil t link)
24129 link)))
24131 (defun org-toggle-link-display ()
24132 "Toggle the literal or descriptive display of links."
24133 (interactive)
24134 (if org-descriptive-links
24135 (progn (org-remove-from-invisibility-spec '(org-link))
24136 (org-restart-font-lock)
24137 (setq org-descriptive-links nil))
24138 (progn (add-to-invisibility-spec '(org-link))
24139 (org-restart-font-lock)
24140 (setq org-descriptive-links t))))
24142 ;; Speedbar support
24144 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24145 "Overlay marking the agenda restriction line in speedbar.")
24146 (overlay-put org-speedbar-restriction-lock-overlay
24147 'face 'org-agenda-restriction-lock)
24148 (overlay-put org-speedbar-restriction-lock-overlay
24149 'help-echo "Agendas are currently limited to this item.")
24150 (org-detach-overlay org-speedbar-restriction-lock-overlay)
24152 (defun org-speedbar-set-agenda-restriction ()
24153 "Restrict future agenda commands to the location at point in speedbar.
24154 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
24155 (interactive)
24156 (require 'org-agenda)
24157 (let (p m tp np dir txt)
24158 (cond
24159 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24160 'org-imenu t))
24161 (setq m (get-text-property p 'org-imenu-marker))
24162 (with-current-buffer (marker-buffer m)
24163 (goto-char m)
24164 (org-agenda-set-restriction-lock 'subtree)))
24165 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24166 'speedbar-function 'speedbar-find-file))
24167 (setq tp (previous-single-property-change
24168 (1+ p) 'speedbar-function)
24169 np (next-single-property-change
24170 tp 'speedbar-function)
24171 dir (speedbar-line-directory)
24172 txt (buffer-substring-no-properties (or tp (point-min))
24173 (or np (point-max))))
24174 (with-current-buffer (find-file-noselect
24175 (let ((default-directory dir))
24176 (expand-file-name txt)))
24177 (unless (derived-mode-p 'org-mode)
24178 (user-error "Cannot restrict to non-Org-mode file"))
24179 (org-agenda-set-restriction-lock 'file)))
24180 (t (user-error "Don't know how to restrict Org-mode's agenda")))
24181 (move-overlay org-speedbar-restriction-lock-overlay
24182 (point-at-bol) (point-at-eol))
24183 (setq current-prefix-arg nil)
24184 (org-agenda-maybe-redo)))
24186 (defvar speedbar-file-key-map)
24187 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24188 (eval-after-load "speedbar"
24189 '(progn
24190 (speedbar-add-supported-extension ".org")
24191 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24192 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24193 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24194 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24195 (add-hook 'speedbar-visiting-tag-hook
24196 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24198 ;;; Fixes and Hacks for problems with other packages
24200 (defun org-mode-flyspell-verify ()
24201 "Function used for `flyspell-generic-check-word-predicate'."
24202 (if (org-at-heading-p)
24203 ;; At a headline or an inlinetask, check title only. This is
24204 ;; faster than relying on `org-element-at-point'.
24205 (and (save-excursion (beginning-of-line)
24206 (and (let ((case-fold-search t))
24207 (not (looking-at "\\*+ END[ \t]*$")))
24208 (looking-at org-complex-heading-regexp)))
24209 (match-beginning 4)
24210 (>= (point) (match-beginning 4))
24211 (or (not (match-beginning 5))
24212 (< (point) (match-beginning 5))))
24213 (let* ((element (org-element-at-point))
24214 (post-affiliated (org-element-property :post-affiliated element))
24215 (object-check
24216 (function
24217 ;; Non-nil if checks can be done for object at point.
24218 (lambda ()
24219 (let ((object (save-excursion
24220 (when (org-looking-at-p "\\>") (backward-char))
24221 (org-element-context element))))
24222 (case (org-element-type object)
24223 ;; Prevent checks in links due to keybinding conflict
24224 ;; with Flyspell.
24225 ((code entity export-snippet inline-babel-call
24226 inline-src-block line-break latex-fragment link macro
24227 statistics-cookie target timestamp verbatim)
24228 nil)
24229 (footnote-reference
24230 ;; Only in inline footnotes, within the definition.
24231 (and (eq (org-element-property :type object) 'inline)
24232 (< (save-excursion
24233 (goto-char (org-element-property :begin object))
24234 (search-forward ":" nil t 2))
24235 (point))))
24236 (otherwise t)))))))
24237 (cond
24238 ;; Ignore checks in all affiliated keywords but captions.
24239 ((and post-affiliated (< (point) post-affiliated))
24240 (and (save-excursion
24241 (beginning-of-line)
24242 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
24243 (> (point) (match-end 0))
24244 (funcall object-check)))
24245 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
24246 ((and org-log-into-drawer
24247 (let ((log (or (org-string-nw-p org-log-into-drawer) "LOGBOOK"))
24248 (parent element))
24249 (while (and parent (not (eq (org-element-type parent) 'drawer)))
24250 (setq parent (org-element-property :parent parent)))
24251 (and parent
24252 (eq (compare-strings
24253 log nil nil
24254 (org-element-property :drawer-name parent) nil nil t)
24255 t))))
24256 nil)
24258 (case (org-element-type element)
24259 ((comment quote-section) t)
24260 (comment-block
24261 ;; Allow checks between block markers, not on them.
24262 (and (> (line-beginning-position)
24263 (org-element-property :post-affiliated element))
24264 (save-excursion
24265 (end-of-line)
24266 (skip-chars-forward " \r\t\n")
24267 (< (point) (org-element-property :end element)))))
24268 ;; Arbitrary list of keywords where checks are meaningful.
24269 ;; Make sure point is on the value part of the element.
24270 (keyword
24271 (and (member (org-element-property :key element)
24272 '("DESCRIPTION" "TITLE"))
24273 (< (save-excursion
24274 (beginning-of-line) (search-forward ":") (point))
24275 (point))))
24276 ;; Check is globally allowed in paragraphs verse blocks and
24277 ;; table rows (after affiliated keywords) but some objects
24278 ;; must not be affected.
24279 ((paragraph table-row verse-block)
24280 (and (>= (point) (org-element-property :contents-begin element))
24281 (< (point) (org-element-property :contents-end element))
24282 (funcall object-check)))))))))
24283 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
24285 (defun org-remove-flyspell-overlays-in (beg end)
24286 "Remove flyspell overlays in region."
24287 (and (org-bound-and-true-p flyspell-mode)
24288 (fboundp 'flyspell-delete-region-overlays)
24289 (flyspell-delete-region-overlays beg end)))
24291 (defvar flyspell-delayed-commands)
24292 (eval-after-load "flyspell"
24293 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
24295 ;; Make `bookmark-jump' shows the jump location if it was hidden.
24296 (eval-after-load "bookmark"
24297 '(if (boundp 'bookmark-after-jump-hook)
24298 ;; We can use the hook
24299 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
24300 ;; Hook not available, use advice
24301 (defadvice bookmark-jump (after org-make-visible activate)
24302 "Make the position visible."
24303 (org-bookmark-jump-unhide))))
24305 ;; Make sure saveplace shows the location if it was hidden
24306 (eval-after-load "saveplace"
24307 '(defadvice save-place-find-file-hook (after org-make-visible activate)
24308 "Make the position visible."
24309 (org-bookmark-jump-unhide)))
24311 ;; Make sure ecb shows the location if it was hidden
24312 (eval-after-load "ecb"
24313 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
24314 "Make hierarchy visible when jumping into location from ECB tree buffer."
24315 (if (derived-mode-p 'org-mode)
24316 (org-show-context))))
24318 (defun org-bookmark-jump-unhide ()
24319 "Unhide the current position, to show the bookmark location."
24320 (and (derived-mode-p 'org-mode)
24321 (or (outline-invisible-p)
24322 (save-excursion (goto-char (max (point-min) (1- (point))))
24323 (outline-invisible-p)))
24324 (org-show-context 'bookmark-jump)))
24326 ;; Make session.el ignore our circular variable
24327 (defvar session-globals-exclude)
24328 (eval-after-load "session"
24329 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24331 ;;;; Finish up
24333 (provide 'org)
24335 (run-hooks 'org-load-hook)
24337 ;;; org.el ends here