Merge branch 'maint'
[org-mode/org-tableheadings.git] / lisp / org.el
blob64b00709879ef3bc061d1761d8820e0d57a1ad43
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" sh)
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 in the echo area.
301 With prefix argument HERE, insert it at point.
302 When FULL is non-nil, use a verbose version string.
303 When MESSAGE is non-nil, display a message with the version."
304 (interactive "P")
305 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
306 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
307 (load-suffixes (list ".el"))
308 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
309 (org-trash (or
310 (and (fboundp 'org-release) (fboundp 'org-git-version))
311 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
312 (load-suffixes save-load-suffixes)
313 (org-version (org-release))
314 (git-version (org-git-version))
315 (version (format "Org-mode version %s (%s @ %s)"
316 org-version
317 git-version
318 (if org-install-dir
319 (if (string= org-dir org-install-dir)
320 org-install-dir
321 (concat "mixed installation! " org-install-dir " and " org-dir))
322 "org-loaddefs.el can not be found!")))
323 (version1 (if full version org-version)))
324 (if (org-called-interactively-p 'interactive)
325 (if here
326 (insert version)
327 (message version))
328 (if message (message version1))
329 version1)))
331 (defconst org-version (org-version))
334 ;;; Syntax Constants
336 ;;;; Block
338 (defconst org-block-regexp
339 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
340 "Regular expression for hiding blocks.")
342 (defconst org-dblock-start-re
343 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
344 "Matches the start line of a dynamic block, with parameters.")
346 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
347 "Matches the end of a dynamic block.")
349 ;;;; Clock and Planning
351 (defconst org-clock-string "CLOCK:"
352 "String used as prefix for timestamps clocking work hours on an item.")
354 (defconst org-closed-string "CLOSED:"
355 "String used as the prefix for timestamps logging closing a TODO entry.")
357 (defconst org-deadline-string "DEADLINE:"
358 "String to mark deadline entries.
359 A deadline is this string, followed by a time stamp. Should be a word,
360 terminated by a colon. You can insert a schedule keyword and
361 a timestamp with \\[org-deadline].")
363 (defconst org-scheduled-string "SCHEDULED:"
364 "String to mark scheduled TODO entries.
365 A schedule is this string, followed by a time stamp. Should be a word,
366 terminated by a colon. You can insert a schedule keyword and
367 a timestamp with \\[org-schedule].")
369 (defconst org-planning-or-clock-line-re
370 (concat "^[ \t]*"
371 (regexp-opt
372 (list org-clock-string org-closed-string org-deadline-string
373 org-scheduled-string)
375 "Matches a line with planning or clock info.
376 Matched keyword is in group 1.")
378 ;;;; Drawer
380 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
381 "Matches first or last line of a hidden block.
382 Group 1 contains drawer's name or \"END\".")
384 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
385 "Regular expression matching the first line of a property drawer.")
387 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
388 "Regular expression matching the last line of a property drawer.")
390 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
391 "Regular expression matching the first line of a clock drawer.")
393 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
394 "Regular expression matching the last line of a clock drawer.")
396 (defconst org-property-drawer-re
397 (concat "\\(" org-property-start-re "\\)[^\000]*?\\("
398 org-property-end-re "\\)\n?")
399 "Matches an entire property drawer.")
401 (defconst org-clock-drawer-re
402 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
403 org-clock-drawer-end-re "\\)\n?")
404 "Matches an entire clock drawer.")
406 ;;;; Headline
408 (defconst org-heading-keyword-regexp-format
409 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
410 "Printf format for a regexp matching a headline with some keyword.
411 This regexp will match the headline of any node which has the
412 exact keyword that is put into the format. The keyword isn't in
413 any group by default, but the stars and the body are.")
415 (defconst org-heading-keyword-maybe-regexp-format
416 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
417 "Printf format for a regexp matching a headline, possibly with some keyword.
418 This regexp can match any headline with the specified keyword, or
419 without a keyword. The keyword isn't in any group by default,
420 but the stars and the body are.")
422 (defconst org-archive-tag "ARCHIVE"
423 "The tag that marks a subtree as archived.
424 An archived subtree does not open during visibility cycling, and does
425 not contribute to the agenda listings.")
427 (defconst org-comment-string "COMMENT"
428 "Entries starting with this keyword will never be exported.
429 An entry can be toggled between COMMENT and normal with
430 \\[org-toggle-comment].")
432 (defconst org-quote-string "QUOTE"
433 "Entries starting with this keyword will be exported in fixed-width font.
434 Quoting applies only to the text in the entry following the headline, and does
435 not extend beyond the next headline, even if that is lower level.
436 An entry can be toggled between QUOTE and normal with
437 \\[org-toggle-fixed-width-section].")
439 ;;;; LaTeX Environments and Fragments
441 (defconst org-latex-regexps
442 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
443 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
444 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
445 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
446 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
447 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
448 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
449 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
450 "Regular expressions for matching embedded LaTeX.")
452 ;;;; Node Property
454 (defconst org-effort-property "Effort"
455 "The property that is being used to keep track of effort estimates.
456 Effort estimates given in this property need to have the format H:MM.")
458 ;;;; Table
460 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
461 "Detect an org-type or table-type table.")
463 (defconst org-table-line-regexp "^[ \t]*|"
464 "Detect an org-type table line.")
466 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
467 "Detect an org-type table line.")
469 (defconst org-table-hline-regexp "^[ \t]*|-"
470 "Detect an org-type table hline.")
472 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
473 "Detect a table-type table hline.")
475 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
476 "Detect the first line outside a table when searching from within it.
477 This works for both table types.")
479 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
480 "Detect a #+TBLFM line.")
482 ;;;; Timestamp
484 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
485 "Regular expression for fast time stamp matching.")
487 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
488 "Regular expression for fast time stamp matching.")
490 (defconst org-ts-regexp0
491 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
492 "Regular expression matching time strings for analysis.
493 This one does not require the space after the date, so it can be used
494 on a string that terminates immediately after the date.")
496 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
497 "Regular expression matching time strings for analysis.")
499 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
500 "Regular expression matching time stamps, with groups.")
502 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
503 "Regular expression matching time stamps (also [..]), with groups.")
505 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
506 "Regular expression matching a time stamp range.")
508 (defconst org-tr-regexp-both
509 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
510 "Regular expression matching a time stamp range.")
512 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
513 org-ts-regexp "\\)?")
514 "Regular expression matching a time stamp or time stamp range.")
516 (defconst org-tsr-regexp-both
517 (concat org-ts-regexp-both "\\(--?-?"
518 org-ts-regexp-both "\\)?")
519 "Regular expression matching a time stamp or time stamp range.
520 The time stamps may be either active or inactive.")
522 (defconst org-repeat-re
523 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
524 "Regular expression for specifying repeated events.
525 After a match, group 1 contains the repeat expression.")
527 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
528 "Formats for `format-time-string' which are used for time stamps.")
531 ;;; The custom variables
533 (defgroup org nil
534 "Outline-based notes management and organizer."
535 :tag "Org"
536 :group 'outlines
537 :group 'calendar)
539 (defcustom org-mode-hook nil
540 "Mode hook for Org-mode, run after the mode was turned on."
541 :group 'org
542 :type 'hook)
544 (defcustom org-load-hook nil
545 "Hook that is run after org.el has been loaded."
546 :group 'org
547 :type 'hook)
549 (defcustom org-log-buffer-setup-hook nil
550 "Hook that is run after an Org log buffer is created."
551 :group 'org
552 :version "24.1"
553 :type 'hook)
555 (defvar org-modules) ; defined below
556 (defvar org-modules-loaded nil
557 "Have the modules been loaded already?")
559 (defun org-load-modules-maybe (&optional force)
560 "Load all extensions listed in `org-modules'."
561 (when (or force (not org-modules-loaded))
562 (mapc (lambda (ext)
563 (condition-case nil (require ext)
564 (error (message "Problems while trying to load feature `%s'" ext))))
565 org-modules)
566 (setq org-modules-loaded t)))
568 (defun org-set-modules (var value)
569 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
570 (set var value)
571 (when (featurep 'org)
572 (org-load-modules-maybe 'force)
573 (org-element-cache-reset 'all)))
575 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
576 "Modules that should always be loaded together with org.el.
578 If a description starts with <C>, the file is not part of Emacs
579 and loading it will require that you have downloaded and properly
580 installed the Org mode distribution.
582 You can also use this system to load external packages (i.e. neither Org
583 core modules, nor modules from the CONTRIB directory). Just add symbols
584 to the end of the list. If the package is called org-xyz.el, then you need
585 to add the symbol `xyz', and the package must have a call to:
587 \(provide 'org-xyz)
589 For export specific modules, see also `org-export-backends'."
590 :group 'org
591 :set 'org-set-modules
592 :version "24.4"
593 :package-version '(Org . "8.0")
594 :type
595 '(set :greedy t
596 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
597 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
598 (const :tag " crypt: Encryption of subtrees" org-crypt)
599 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
600 (const :tag " docview: Links to doc-view buffers" org-docview)
601 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
602 (const :tag " habit: Track your consistency with habits" org-habit)
603 (const :tag " id: Global IDs for identifying entries" org-id)
604 (const :tag " info: Links to Info nodes" org-info)
605 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
606 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
607 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
608 (const :tag " mouse: Additional mouse support" org-mouse)
609 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
610 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
611 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
613 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
614 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
615 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
616 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
617 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
618 (const :tag "C collector: Collect properties into tables" org-collector)
619 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
620 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
621 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
622 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
623 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
624 (const :tag "C eval: Include command output as text" org-eval)
625 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
626 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
627 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
628 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
629 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
630 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
631 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
632 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
633 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
634 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
635 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
636 (const :tag "C mew: Links to Mew folders/messages" org-mew)
637 (const :tag "C mtags: Support for muse-like tags" org-mtags)
638 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
639 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
640 (const :tag "C registry: A registry for Org-mode links" org-registry)
641 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
642 (const :tag "C secretary: Team management with org-mode" org-secretary)
643 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
644 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
645 (const :tag "C track: Keep up with Org-mode development" org-track)
646 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
647 (const :tag "C vm: Links to VM folders/messages" org-vm)
648 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
649 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
650 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
652 (defvar org-export--registered-backends) ; From ox.el.
653 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
654 (declare-function org-export-backend-name "ox" (backend))
655 (defcustom org-export-backends '(ascii html icalendar latex)
656 "List of export back-ends that should be always available.
658 If a description starts with <C>, the file is not part of Emacs
659 and loading it will require that you have downloaded and properly
660 installed the Org mode distribution.
662 Unlike to `org-modules', libraries in this list will not be
663 loaded along with Org, but only once the export framework is
664 needed.
666 This variable needs to be set before org.el is loaded. If you
667 need to make a change while Emacs is running, use the customize
668 interface or run the following code, where VAL stands for the new
669 value of the variable, after updating it:
671 \(progn
672 \(setq org-export--registered-backends
673 \(org-remove-if-not
674 \(lambda (backend)
675 \(let ((name (org-export-backend-name backend)))
676 \(or (memq name val)
677 \(catch 'parentp
678 \(dolist (b val)
679 \(and (org-export-derived-backend-p b name)
680 \(throw 'parentp t)))))))
681 org-export--registered-backends))
682 \(let ((new-list (mapcar 'org-export-backend-name
683 org-export--registered-backends)))
684 \(dolist (backend val)
685 \(cond
686 \((not (load (format \"ox-%s\" backend) t t))
687 \(message \"Problems while trying to load export back-end `%s'\"
688 backend))
689 \((not (memq backend new-list)) (push backend new-list))))
690 \(set-default 'org-export-backends new-list)))
692 Adding a back-end to this list will also pull the back-end it
693 depends on, if any."
694 :group 'org
695 :group 'org-export
696 :version "24.4"
697 :package-version '(Org . "8.0")
698 :initialize 'custom-initialize-set
699 :set (lambda (var val)
700 (if (not (featurep 'ox)) (set-default var val)
701 ;; Any back-end not required anymore (not present in VAL and not
702 ;; a parent of any back-end in the new value) is removed from the
703 ;; list of registered back-ends.
704 (setq org-export--registered-backends
705 (org-remove-if-not
706 (lambda (backend)
707 (let ((name (org-export-backend-name backend)))
708 (or (memq name val)
709 (catch 'parentp
710 (dolist (b val)
711 (and (org-export-derived-backend-p b name)
712 (throw 'parentp t)))))))
713 org-export--registered-backends))
714 ;; Now build NEW-LIST of both new back-ends and required
715 ;; parents.
716 (let ((new-list (mapcar 'org-export-backend-name
717 org-export--registered-backends)))
718 (dolist (backend val)
719 (cond
720 ((not (load (format "ox-%s" backend) t t))
721 (message "Problems while trying to load export back-end `%s'"
722 backend))
723 ((not (memq backend new-list)) (push backend new-list))))
724 ;; Set VAR to that list with fixed dependencies.
725 (set-default var new-list))))
726 :type '(set :greedy t
727 (const :tag " ascii Export buffer to ASCII format" ascii)
728 (const :tag " beamer Export buffer to Beamer presentation" beamer)
729 (const :tag " html Export buffer to HTML format" html)
730 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
731 (const :tag " latex Export buffer to LaTeX format" latex)
732 (const :tag " man Export buffer to MAN format" man)
733 (const :tag " md Export buffer to Markdown format" md)
734 (const :tag " odt Export buffer to ODT format" odt)
735 (const :tag " org Export buffer to Org format" org)
736 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
737 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
738 (const :tag "C deck Export buffer to deck.js presentations" deck)
739 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
740 (const :tag "C groff Export buffer to Groff format" groff)
741 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
742 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
743 (const :tag "C s5 Export buffer to s5 presentations" s5)
744 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
746 (eval-after-load 'ox
747 '(mapc
748 (lambda (backend)
749 (condition-case nil (require (intern (format "ox-%s" backend)))
750 (error (message "Problems while trying to load export back-end `%s'"
751 backend))))
752 org-export-backends))
754 (defcustom org-support-shift-select nil
755 "Non-nil means make shift-cursor commands select text when possible.
757 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
758 start selecting a region, or enlarge regions started in this way.
759 In Org-mode, in special contexts, these same keys are used for
760 other purposes, important enough to compete with shift selection.
761 Org tries to balance these needs by supporting `shift-select-mode'
762 outside these special contexts, under control of this variable.
764 The default of this variable is nil, to avoid confusing behavior. Shifted
765 cursor keys will then execute Org commands in the following contexts:
766 - on a headline, changing TODO state (left/right) and priority (up/down)
767 - on a time stamp, changing the time
768 - in a plain list item, changing the bullet type
769 - in a property definition line, switching between allowed values
770 - in the BEGIN line of a clock table (changing the time block).
771 Outside these contexts, the commands will throw an error.
773 When this variable is t and the cursor is not in a special
774 context, Org-mode will support shift-selection for making and
775 enlarging regions. To make this more effective, the bullet
776 cycling will no longer happen anywhere in an item line, but only
777 if the cursor is exactly on the bullet.
779 If you set this variable to the symbol `always', then the keys
780 will not be special in headlines, property lines, and item lines,
781 to make shift selection work there as well. If this is what you
782 want, you can use the following alternative commands: `C-c C-t'
783 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
784 can be used to switch TODO sets, `C-c -' to cycle item bullet
785 types, and properties can be edited by hand or in column view.
787 However, when the cursor is on a timestamp, shift-cursor commands
788 will still edit the time stamp - this is just too good to give up.
790 XEmacs user should have this variable set to nil, because
791 `shift-select-mode' is in Emacs 23 or later only."
792 :group 'org
793 :type '(choice
794 (const :tag "Never" nil)
795 (const :tag "When outside special context" t)
796 (const :tag "Everywhere except timestamps" always)))
798 (defcustom org-loop-over-headlines-in-active-region nil
799 "Shall some commands act upon headlines in the active region?
801 When set to `t', some commands will be performed in all headlines
802 within the active region.
804 When set to `start-level', some commands will be performed in all
805 headlines within the active region, provided that these headlines
806 are of the same level than the first one.
808 When set to a string, those commands will be performed on the
809 matching headlines within the active region. Such string must be
810 a tags/property/todo match as it is used in the agenda tags view.
812 The list of commands is: `org-schedule', `org-deadline',
813 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
814 `org-archive-to-archive-sibling'. The archiving commands skip
815 already archived entries."
816 :type '(choice (const :tag "Don't loop" nil)
817 (const :tag "All headlines in active region" t)
818 (const :tag "In active region, headlines at the same level than the first one" start-level)
819 (string :tag "Tags/Property/Todo matcher"))
820 :version "24.1"
821 :group 'org-todo
822 :group 'org-archive)
824 (defgroup org-startup nil
825 "Options concerning startup of Org-mode."
826 :tag "Org Startup"
827 :group 'org)
829 (defcustom org-startup-folded t
830 "Non-nil means entering Org-mode will switch to OVERVIEW.
831 This can also be configured on a per-file basis by adding one of
832 the following lines anywhere in the buffer:
834 #+STARTUP: fold (or `overview', this is equivalent)
835 #+STARTUP: nofold (or `showall', this is equivalent)
836 #+STARTUP: content
837 #+STARTUP: showeverything
839 By default, this option is ignored when Org opens agenda files
840 for the first time. If you want the agenda to honor the startup
841 option, set `org-agenda-inhibit-startup' to nil."
842 :group 'org-startup
843 :type '(choice
844 (const :tag "nofold: show all" nil)
845 (const :tag "fold: overview" t)
846 (const :tag "content: all headlines" content)
847 (const :tag "show everything, even drawers" showeverything)))
849 (defcustom org-startup-truncated t
850 "Non-nil means entering Org-mode will set `truncate-lines'.
851 This is useful since some lines containing links can be very long and
852 uninteresting. Also tables look terrible when wrapped."
853 :group 'org-startup
854 :type 'boolean)
856 (defcustom org-startup-indented nil
857 "Non-nil means turn on `org-indent-mode' on startup.
858 This can also be configured on a per-file basis by adding one of
859 the following lines anywhere in the buffer:
861 #+STARTUP: indent
862 #+STARTUP: noindent"
863 :group 'org-structure
864 :type '(choice
865 (const :tag "Not" nil)
866 (const :tag "Globally (slow on startup in large files)" t)))
868 (defcustom org-use-sub-superscripts t
869 "Non-nil means interpret \"_\" and \"^\" for display.
871 If you want to control how Org exports those characters, see
872 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
873 used to be an alias for `org-export-with-sub-superscripts' in
874 Org <8.0, it is not anymore.
876 When this option is turned on, you can use TeX-like syntax for
877 sub- and superscripts within the buffer. Several characters after
878 \"_\" or \"^\" will be considered as a single item - so grouping
879 with {} is normally not needed. For example, the following things
880 will be parsed as single sub- or superscripts:
882 10^24 or 10^tau several digits will be considered 1 item.
883 10^-12 or 10^-tau a leading sign with digits or a word
884 x^2-y^3 will be read as x^2 - y^3, because items are
885 terminated by almost any nonword/nondigit char.
886 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
888 Still, ambiguity is possible. So when in doubt, use {} to enclose
889 the sub/superscript. If you set this variable to the symbol `{}',
890 the braces are *required* in order to trigger interpretations as
891 sub/superscript. This can be helpful in documents that need \"_\"
892 frequently in plain text."
893 :group 'org-startup
894 :version "24.4"
895 :package-version '(Org . "8.0")
896 :type '(choice
897 (const :tag "Always interpret" t)
898 (const :tag "Only with braces" {})
899 (const :tag "Never interpret" nil)))
901 (defcustom org-startup-with-beamer-mode nil
902 "Non-nil means turn on `org-beamer-mode' on startup.
903 This can also be configured on a per-file basis by adding one of
904 the following lines anywhere in the buffer:
906 #+STARTUP: beamer"
907 :group 'org-startup
908 :version "24.1"
909 :type 'boolean)
911 (defcustom org-startup-align-all-tables nil
912 "Non-nil means align all tables when visiting a file.
913 This is useful when the column width in tables is forced with <N> cookies
914 in table fields. Such tables will look correct only after the first re-align.
915 This can also be configured on a per-file basis by adding one of
916 the following lines anywhere in the buffer:
917 #+STARTUP: align
918 #+STARTUP: noalign"
919 :group 'org-startup
920 :type 'boolean)
922 (defcustom org-startup-with-inline-images nil
923 "Non-nil means show inline images when loading a new Org file.
924 This can also be configured on a per-file basis by adding one of
925 the following lines anywhere in the buffer:
926 #+STARTUP: inlineimages
927 #+STARTUP: noinlineimages"
928 :group 'org-startup
929 :version "24.1"
930 :type 'boolean)
932 (defcustom org-startup-with-latex-preview nil
933 "Non-nil means preview LaTeX fragments when loading a new Org file.
935 This can also be configured on a per-file basis by adding one of
936 the following lines anywhere in the buffer:
937 #+STARTUP: latexpreview
938 #+STARTUP: nolatexpreview"
939 :group 'org-startup
940 :version "24.4"
941 :package-version '(Org . "8.0")
942 :type 'boolean)
944 (defcustom org-insert-mode-line-in-empty-file nil
945 "Non-nil means insert the first line setting Org-mode in empty files.
946 When the function `org-mode' is called interactively in an empty file, this
947 normally means that the file name does not automatically trigger Org-mode.
948 To ensure that the file will always be in Org-mode in the future, a
949 line enforcing Org-mode will be inserted into the buffer, if this option
950 has been set."
951 :group 'org-startup
952 :type 'boolean)
954 (defcustom org-replace-disputed-keys nil
955 "Non-nil means use alternative key bindings for some keys.
956 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
957 These keys are also used by other packages like shift-selection-mode'
958 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
959 If you want to use Org-mode together with one of these other modes,
960 or more generally if you would like to move some Org-mode commands to
961 other keys, set this variable and configure the keys with the variable
962 `org-disputed-keys'.
964 This option is only relevant at load-time of Org-mode, and must be set
965 *before* org.el is loaded. Changing it requires a restart of Emacs to
966 become effective."
967 :group 'org-startup
968 :type 'boolean)
970 (defcustom org-use-extra-keys nil
971 "Non-nil means use extra key sequence definitions for certain commands.
972 This happens automatically if you run XEmacs or if `window-system'
973 is nil. This variable lets you do the same manually. You must
974 set it before loading org.
976 Example: on Carbon Emacs 22 running graphically, with an external
977 keyboard on a Powerbook, the default way of setting M-left might
978 not work for either Alt or ESC. Setting this variable will make
979 it work for ESC."
980 :group 'org-startup
981 :type 'boolean)
983 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
985 (defcustom org-disputed-keys
986 '(([(shift up)] . [(meta p)])
987 ([(shift down)] . [(meta n)])
988 ([(shift left)] . [(meta -)])
989 ([(shift right)] . [(meta +)])
990 ([(control shift right)] . [(meta shift +)])
991 ([(control shift left)] . [(meta shift -)]))
992 "Keys for which Org-mode and other modes compete.
993 This is an alist, cars are the default keys, second element specifies
994 the alternative to use when `org-replace-disputed-keys' is t.
996 Keys can be specified in any syntax supported by `define-key'.
997 The value of this option takes effect only at Org-mode's startup,
998 therefore you'll have to restart Emacs to apply it after changing."
999 :group 'org-startup
1000 :type 'alist)
1002 (defun org-key (key)
1003 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1004 Or return the original if not disputed.
1005 Also apply the translations defined in `org-xemacs-key-equivalents'."
1006 (when org-replace-disputed-keys
1007 (let* ((nkey (key-description key))
1008 (x (org-find-if (lambda (x)
1009 (equal (key-description (car x)) nkey))
1010 org-disputed-keys)))
1011 (setq key (if x (cdr x) key))))
1012 (when (featurep 'xemacs)
1013 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
1014 key)
1016 (defun org-find-if (predicate seq)
1017 (catch 'exit
1018 (while seq
1019 (if (funcall predicate (car seq))
1020 (throw 'exit (car seq))
1021 (pop seq)))))
1023 (defun org-defkey (keymap key def)
1024 "Define a key, possibly translated, as returned by `org-key'."
1025 (define-key keymap (org-key key) def))
1027 (defcustom org-ellipsis nil
1028 "The ellipsis to use in the Org-mode outline.
1029 When nil, just use the standard three dots. When a string, use that instead,
1030 When a face, use the standard 3 dots, but with the specified face.
1031 The change affects only Org-mode (which will then use its own display table).
1032 Changing this requires executing `M-x org-mode' in a buffer to become
1033 effective."
1034 :group 'org-startup
1035 :type '(choice (const :tag "Default" nil)
1036 (face :tag "Face" :value org-warning)
1037 (string :tag "String" :value "...#")))
1039 (defvar org-display-table nil
1040 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
1042 (defgroup org-keywords nil
1043 "Keywords in Org-mode."
1044 :tag "Org Keywords"
1045 :group 'org)
1047 (defcustom org-closed-keep-when-no-todo nil
1048 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1049 :group 'org-todo
1050 :group 'org-keywords
1051 :version "24.4"
1052 :package-version '(Org . "8.0")
1053 :type 'boolean)
1055 (defgroup org-structure nil
1056 "Options concerning the general structure of Org-mode files."
1057 :tag "Org Structure"
1058 :group 'org)
1060 (defgroup org-reveal-location nil
1061 "Options about how to make context of a location visible."
1062 :tag "Org Reveal Location"
1063 :group 'org-structure)
1065 (defconst org-context-choice
1066 '(choice
1067 (const :tag "Always" t)
1068 (const :tag "Never" nil)
1069 (repeat :greedy t :tag "Individual contexts"
1070 (cons
1071 (choice :tag "Context"
1072 (const agenda)
1073 (const org-goto)
1074 (const occur-tree)
1075 (const tags-tree)
1076 (const link-search)
1077 (const mark-goto)
1078 (const bookmark-jump)
1079 (const isearch)
1080 (const default))
1081 (boolean))))
1082 "Contexts for the reveal options.")
1084 (defcustom org-show-hierarchy-above '((default . t))
1085 "Non-nil means show full hierarchy when revealing a location.
1086 Org-mode often shows locations in an org-mode file which might have
1087 been invisible before. When this is set, the hierarchy of headings
1088 above the exposed location is shown.
1089 Turning this off for example for sparse trees makes them very compact.
1090 Instead of t, this can also be an alist specifying this option for different
1091 contexts. Valid contexts are
1092 agenda when exposing an entry from the agenda
1093 org-goto when using the command `org-goto' on key C-c C-j
1094 occur-tree when using the command `org-occur' on key C-c /
1095 tags-tree when constructing a sparse tree based on tags matches
1096 link-search when exposing search matches associated with a link
1097 mark-goto when exposing the jump goal of a mark
1098 bookmark-jump when exposing a bookmark location
1099 isearch when exiting from an incremental search
1100 default default for all contexts not set explicitly"
1101 :group 'org-reveal-location
1102 :type org-context-choice)
1104 (defcustom org-show-following-heading '((default . nil))
1105 "Non-nil means show following heading when revealing a location.
1106 Org-mode often shows locations in an org-mode file which might have
1107 been invisible before. When this is set, the heading following the
1108 match is shown.
1109 Turning this off for example for sparse trees makes them very compact,
1110 but makes it harder to edit the location of the match. In such a case,
1111 use the command \\[org-reveal] to show more context.
1112 Instead of t, this can also be an alist specifying this option for different
1113 contexts. See `org-show-hierarchy-above' for valid contexts."
1114 :group 'org-reveal-location
1115 :type org-context-choice)
1117 (defcustom org-show-siblings '((default . nil) (isearch t) (bookmark-jump t))
1118 "Non-nil means show all sibling heading when revealing a location.
1119 Org-mode often shows locations in an org-mode file which might have
1120 been invisible before. When this is set, the sibling of the current entry
1121 heading are all made visible. If `org-show-hierarchy-above' is t,
1122 the same happens on each level of the hierarchy above the current entry.
1124 By default this is on for the isearch context, off for all other contexts.
1125 Turning this off for example for sparse trees makes them very compact,
1126 but makes it harder to edit the location of the match. In such a case,
1127 use the command \\[org-reveal] to show more context.
1128 Instead of t, this can also be an alist specifying this option for different
1129 contexts. See `org-show-hierarchy-above' for valid contexts."
1130 :group 'org-reveal-location
1131 :type org-context-choice
1132 :version "24.4"
1133 :package-version '(Org . "8.0"))
1135 (defcustom org-show-entry-below '((default . nil))
1136 "Non-nil means show the entry below a headline when revealing a location.
1137 Org-mode often shows locations in an org-mode file which might have
1138 been invisible before. When this is set, the text below the headline that is
1139 exposed is also shown.
1141 By default this is off for all contexts.
1142 Instead of t, this can also be an alist specifying this option for different
1143 contexts. See `org-show-hierarchy-above' for valid contexts."
1144 :group 'org-reveal-location
1145 :type org-context-choice)
1147 (defcustom org-indirect-buffer-display 'other-window
1148 "How should indirect tree buffers be displayed?
1149 This applies to indirect buffers created with the commands
1150 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
1151 Valid values are:
1152 current-window Display in the current window
1153 other-window Just display in another window.
1154 dedicated-frame Create one new frame, and re-use it each time.
1155 new-frame Make a new frame each time. Note that in this case
1156 previously-made indirect buffers are kept, and you need to
1157 kill these buffers yourself."
1158 :group 'org-structure
1159 :group 'org-agenda-windows
1160 :type '(choice
1161 (const :tag "In current window" current-window)
1162 (const :tag "In current frame, other window" other-window)
1163 (const :tag "Each time a new frame" new-frame)
1164 (const :tag "One dedicated frame" dedicated-frame)))
1166 (defcustom org-use-speed-commands nil
1167 "Non-nil means activate single letter commands at beginning of a headline.
1168 This may also be a function to test for appropriate locations where speed
1169 commands should be active.
1171 For example, to activate speed commands when the point is on any
1172 star at the beginning of the headline, you can do this:
1174 (setq org-use-speed-commands
1175 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1176 :group 'org-structure
1177 :type '(choice
1178 (const :tag "Never" nil)
1179 (const :tag "At beginning of headline stars" t)
1180 (function)))
1182 (defcustom org-speed-commands-user nil
1183 "Alist of additional speed commands.
1184 This list will be checked before `org-speed-commands-default'
1185 when the variable `org-use-speed-commands' is non-nil
1186 and when the cursor is at the beginning of a headline.
1187 The car if each entry is a string with a single letter, which must
1188 be assigned to `self-insert-command' in the global map.
1189 The cdr is either a command to be called interactively, a function
1190 to be called, or a form to be evaluated.
1191 An entry that is just a list with a single string will be interpreted
1192 as a descriptive headline that will be added when listing the speed
1193 commands in the Help buffer using the `?' speed command."
1194 :group 'org-structure
1195 :type '(repeat :value ("k" . ignore)
1196 (choice :value ("k" . ignore)
1197 (list :tag "Descriptive Headline" (string :tag "Headline"))
1198 (cons :tag "Letter and Command"
1199 (string :tag "Command letter")
1200 (choice
1201 (function)
1202 (sexp))))))
1204 (defcustom org-bookmark-names-plist
1205 '(:last-capture "org-capture-last-stored"
1206 :last-refile "org-refile-last-stored"
1207 :last-capture-marker "org-capture-last-stored-marker")
1208 "Names for bookmarks automatically set by some Org commands.
1209 This can provide strings as names for a number of bookmarks Org sets
1210 automatically. The following keys are currently implemented:
1211 :last-capture
1212 :last-capture-marker
1213 :last-refile
1214 When a key does not show up in the property list, the corresponding bookmark
1215 is not set."
1216 :group 'org-structure
1217 :type 'plist)
1219 (defgroup org-cycle nil
1220 "Options concerning visibility cycling in Org-mode."
1221 :tag "Org Cycle"
1222 :group 'org-structure)
1224 (defcustom org-cycle-skip-children-state-if-no-children t
1225 "Non-nil means skip CHILDREN state in entries that don't have any."
1226 :group 'org-cycle
1227 :type 'boolean)
1229 (defcustom org-cycle-max-level nil
1230 "Maximum level which should still be subject to visibility cycling.
1231 Levels higher than this will, for cycling, be treated as text, not a headline.
1232 When `org-odd-levels-only' is set, a value of N in this variable actually
1233 means 2N-1 stars as the limiting headline.
1234 When nil, cycle all levels.
1235 Note that the limiting level of cycling is also influenced by
1236 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1237 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1238 than its value."
1239 :group 'org-cycle
1240 :type '(choice
1241 (const :tag "No limit" nil)
1242 (integer :tag "Maximum level")))
1244 (defcustom org-hide-block-startup nil
1245 "Non-nil means entering Org-mode will fold all blocks.
1246 This can also be set in on a per-file basis with
1248 #+STARTUP: hideblocks
1249 #+STARTUP: showblocks"
1250 :group 'org-startup
1251 :group 'org-cycle
1252 :type 'boolean)
1254 (defcustom org-cycle-global-at-bob nil
1255 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1256 This makes it possible to do global cycling without having to use S-TAB or
1257 \\[universal-argument] TAB. For this special case to work, the first line
1258 of the buffer must not be a headline -- it may be empty or some other text.
1259 When used in this way, `org-cycle-hook' is disabled temporarily to make
1260 sure the cursor stays at the beginning of the buffer. When this option is
1261 nil, don't do anything special at the beginning of the buffer."
1262 :group 'org-cycle
1263 :type 'boolean)
1265 (defcustom org-cycle-level-after-item/entry-creation t
1266 "Non-nil means cycle entry level or item indentation in new empty entries.
1268 When the cursor is at the end of an empty headline, i.e., with only stars
1269 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1270 and then all possible ancestor states, before returning to the original state.
1271 This makes data entry extremely fast: M-RET to create a new headline,
1272 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1274 When the cursor is at the end of an empty plain list item, one TAB will
1275 make it a subitem, two or more tabs will back up to make this an item
1276 higher up in the item hierarchy."
1277 :group 'org-cycle
1278 :type 'boolean)
1280 (defcustom org-cycle-emulate-tab t
1281 "Where should `org-cycle' emulate TAB.
1282 nil Never
1283 white Only in completely white lines
1284 whitestart Only at the beginning of lines, before the first non-white char
1285 t Everywhere except in headlines
1286 exc-hl-bol Everywhere except at the start of a headline
1287 If TAB is used in a place where it does not emulate TAB, the current subtree
1288 visibility is cycled."
1289 :group 'org-cycle
1290 :type '(choice (const :tag "Never" nil)
1291 (const :tag "Only in completely white lines" white)
1292 (const :tag "Before first char in a line" whitestart)
1293 (const :tag "Everywhere except in headlines" t)
1294 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1296 (defcustom org-cycle-separator-lines 2
1297 "Number of empty lines needed to keep an empty line between collapsed trees.
1298 If you leave an empty line between the end of a subtree and the following
1299 headline, this empty line is hidden when the subtree is folded.
1300 Org-mode will leave (exactly) one empty line visible if the number of
1301 empty lines is equal or larger to the number given in this variable.
1302 So the default 2 means at least 2 empty lines after the end of a subtree
1303 are needed to produce free space between a collapsed subtree and the
1304 following headline.
1306 If the number is negative, and the number of empty lines is at least -N,
1307 all empty lines are shown.
1309 Special case: when 0, never leave empty lines in collapsed view."
1310 :group 'org-cycle
1311 :type 'integer)
1312 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1314 (defcustom org-pre-cycle-hook nil
1315 "Hook that is run before visibility cycling is happening.
1316 The function(s) in this hook must accept a single argument which indicates
1317 the new state that will be set right after running this hook. The
1318 argument is a symbol. Before a global state change, it can have the values
1319 `overview', `content', or `all'. Before a local state change, it can have
1320 the values `folded', `children', or `subtree'."
1321 :group 'org-cycle
1322 :type 'hook)
1324 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1325 org-cycle-hide-drawers
1326 org-cycle-hide-inline-tasks
1327 org-cycle-show-empty-lines
1328 org-optimize-window-after-visibility-change)
1329 "Hook that is run after `org-cycle' has changed the buffer visibility.
1330 The function(s) in this hook must accept a single argument which indicates
1331 the new state that was set by the most recent `org-cycle' command. The
1332 argument is a symbol. After a global state change, it can have the values
1333 `overview', `contents', or `all'. After a local state change, it can have
1334 the values `folded', `children', or `subtree'."
1335 :group 'org-cycle
1336 :type 'hook)
1338 (defgroup org-edit-structure nil
1339 "Options concerning structure editing in Org-mode."
1340 :tag "Org Edit Structure"
1341 :group 'org-structure)
1343 (defcustom org-odd-levels-only nil
1344 "Non-nil means skip even levels and only use odd levels for the outline.
1345 This has the effect that two stars are being added/taken away in
1346 promotion/demotion commands. It also influences how levels are
1347 handled by the exporters.
1348 Changing it requires restart of `font-lock-mode' to become effective
1349 for fontification also in regions already fontified.
1350 You may also set this on a per-file basis by adding one of the following
1351 lines to the buffer:
1353 #+STARTUP: odd
1354 #+STARTUP: oddeven"
1355 :group 'org-edit-structure
1356 :group 'org-appearance
1357 :type 'boolean)
1359 (defcustom org-adapt-indentation t
1360 "Non-nil means adapt indentation to outline node level.
1362 When this variable is set, Org assumes that you write outlines by
1363 indenting text in each node to align with the headline (after the stars).
1364 The following issues are influenced by this variable:
1366 - When this is set and the *entire* text in an entry is indented, the
1367 indentation is increased by one space in a demotion command, and
1368 decreased by one in a promotion command. If any line in the entry
1369 body starts with text at column 0, indentation is not changed at all.
1371 - Property drawers and planning information is inserted indented when
1372 this variable s set. When nil, they will not be indented.
1374 - TAB indents a line relative to context. The lines below a headline
1375 will be indented when this variable is set.
1377 Note that this is all about true indentation, by adding and removing
1378 space characters. See also `org-indent.el' which does level-dependent
1379 indentation in a virtual way, i.e. at display time in Emacs."
1380 :group 'org-edit-structure
1381 :type 'boolean)
1383 (defcustom org-special-ctrl-a/e nil
1384 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1386 When t, `C-a' will bring back the cursor to the beginning of the
1387 headline text, i.e. after the stars and after a possible TODO
1388 keyword. In an item, this will be the position after bullet and
1389 check-box, if any. When the cursor is already at that position,
1390 another `C-a' will bring it to the beginning of the line.
1392 `C-e' will jump to the end of the headline, ignoring the presence
1393 of tags in the headline. A second `C-e' will then jump to the
1394 true end of the line, after any tags. This also means that, when
1395 this variable is non-nil, `C-e' also will never jump beyond the
1396 end of the heading of a folded section, i.e. not after the
1397 ellipses.
1399 When set to the symbol `reversed', the first `C-a' or `C-e' works
1400 normally, going to the true line boundary first. Only a directly
1401 following, identical keypress will bring the cursor to the
1402 special positions.
1404 This may also be a cons cell where the behavior for `C-a' and
1405 `C-e' is set separately."
1406 :group 'org-edit-structure
1407 :type '(choice
1408 (const :tag "off" nil)
1409 (const :tag "on: after stars/bullet and before tags first" t)
1410 (const :tag "reversed: true line boundary first" reversed)
1411 (cons :tag "Set C-a and C-e separately"
1412 (choice :tag "Special C-a"
1413 (const :tag "off" nil)
1414 (const :tag "on: after stars/bullet first" t)
1415 (const :tag "reversed: before stars/bullet first" reversed))
1416 (choice :tag "Special C-e"
1417 (const :tag "off" nil)
1418 (const :tag "on: before tags first" t)
1419 (const :tag "reversed: after tags first" reversed)))))
1420 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1422 (defcustom org-special-ctrl-k nil
1423 "Non-nil means `C-k' will behave specially in headlines.
1424 When nil, `C-k' will call the default `kill-line' command.
1425 When t, the following will happen while the cursor is in the headline:
1427 - When the cursor is at the beginning of a headline, kill the entire
1428 line and possible the folded subtree below the line.
1429 - When in the middle of the headline text, kill the headline up to the tags.
1430 - When after the headline text, kill the tags."
1431 :group 'org-edit-structure
1432 :type 'boolean)
1434 (defcustom org-ctrl-k-protect-subtree nil
1435 "Non-nil means, do not delete a hidden subtree with C-k.
1436 When set to the symbol `error', simply throw an error when C-k is
1437 used to kill (part-of) a headline that has hidden text behind it.
1438 Any other non-nil value will result in a query to the user, if it is
1439 OK to kill that hidden subtree. When nil, kill without remorse."
1440 :group 'org-edit-structure
1441 :version "24.1"
1442 :type '(choice
1443 (const :tag "Do not protect hidden subtrees" nil)
1444 (const :tag "Protect hidden subtrees with a security query" t)
1445 (const :tag "Never kill a hidden subtree with C-k" error)))
1447 (defcustom org-special-ctrl-o t
1448 "Non-nil means, make `C-o' insert a row in tables."
1449 :group 'org-edit-structure
1450 :type 'boolean)
1452 (defcustom org-catch-invisible-edits nil
1453 "Check if in invisible region before inserting or deleting a character.
1454 Valid values are:
1456 nil Do not check, so just do invisible edits.
1457 error Throw an error and do nothing.
1458 show Make point visible, and do the requested edit.
1459 show-and-error Make point visible, then throw an error and abort the edit.
1460 smart Make point visible, and do insertion/deletion if it is
1461 adjacent to visible text and the change feels predictable.
1462 Never delete a previously invisible character or add in the
1463 middle or right after an invisible region. Basically, this
1464 allows insertion and backward-delete right before ellipses.
1465 FIXME: maybe in this case we should not even show?"
1466 :group 'org-edit-structure
1467 :version "24.1"
1468 :type '(choice
1469 (const :tag "Do not check" nil)
1470 (const :tag "Throw error when trying to edit" error)
1471 (const :tag "Unhide, but do not do the edit" show-and-error)
1472 (const :tag "Show invisible part and do the edit" show)
1473 (const :tag "Be smart and do the right thing" smart)))
1475 (defcustom org-yank-folded-subtrees t
1476 "Non-nil means when yanking subtrees, fold them.
1477 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1478 it starts with a heading and all other headings in it are either children
1479 or siblings, then fold all the subtrees. However, do this only if no
1480 text after the yank would be swallowed into a folded tree by this action."
1481 :group 'org-edit-structure
1482 :type 'boolean)
1484 (defcustom org-yank-adjusted-subtrees nil
1485 "Non-nil means when yanking subtrees, adjust the level.
1486 With this setting, `org-paste-subtree' is used to insert the subtree, see
1487 this function for details."
1488 :group 'org-edit-structure
1489 :type 'boolean)
1491 (defcustom org-M-RET-may-split-line '((default . t))
1492 "Non-nil means M-RET will split the line at the cursor position.
1493 When nil, it will go to the end of the line before making a
1494 new line.
1495 You may also set this option in a different way for different
1496 contexts. Valid contexts are:
1498 headline when creating a new headline
1499 item when creating a new item
1500 table in a table field
1501 default the value to be used for all contexts not explicitly
1502 customized"
1503 :group 'org-structure
1504 :group 'org-table
1505 :type '(choice
1506 (const :tag "Always" t)
1507 (const :tag "Never" nil)
1508 (repeat :greedy t :tag "Individual contexts"
1509 (cons
1510 (choice :tag "Context"
1511 (const headline)
1512 (const item)
1513 (const table)
1514 (const default))
1515 (boolean)))))
1518 (defcustom org-insert-heading-respect-content nil
1519 "Non-nil means insert new headings after the current subtree.
1520 When nil, the new heading is created directly after the current line.
1521 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1522 this variable on for the duration of the command."
1523 :group 'org-structure
1524 :type 'boolean)
1526 (defcustom org-blank-before-new-entry '((heading . auto)
1527 (plain-list-item . auto))
1528 "Should `org-insert-heading' leave a blank line before new heading/item?
1529 The value is an alist, with `heading' and `plain-list-item' as CAR,
1530 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1531 which case Org will look at the surrounding headings/items and try to
1532 make an intelligent decision whether to insert a blank line or not.
1534 For plain lists, if `org-list-empty-line-terminates-plain-lists' is set,
1535 the setting here is ignored and no empty line is inserted to avoid breaking
1536 the list structure."
1537 :group 'org-edit-structure
1538 :type '(list
1539 (cons (const heading)
1540 (choice (const :tag "Never" nil)
1541 (const :tag "Always" t)
1542 (const :tag "Auto" auto)))
1543 (cons (const plain-list-item)
1544 (choice (const :tag "Never" nil)
1545 (const :tag "Always" t)
1546 (const :tag "Auto" auto)))))
1548 (defcustom org-insert-heading-hook nil
1549 "Hook being run after inserting a new heading."
1550 :group 'org-edit-structure
1551 :type 'hook)
1553 (defcustom org-enable-fixed-width-editor t
1554 "Non-nil means lines starting with \":\" are treated as fixed-width.
1555 This currently only means they are never auto-wrapped.
1556 When nil, such lines will be treated like ordinary lines.
1557 See also the QUOTE keyword."
1558 :group 'org-edit-structure
1559 :type 'boolean)
1561 (defcustom org-goto-auto-isearch t
1562 "Non-nil means typing characters in `org-goto' starts incremental search.
1563 When nil, you can use these keybindings to navigate the buffer:
1565 q Quit the org-goto interface
1566 n Go to the next visible heading
1567 p Go to the previous visible heading
1568 f Go one heading forward on same level
1569 b Go one heading backward on same level
1570 u Go one heading up"
1571 :group 'org-edit-structure
1572 :type 'boolean)
1574 (defgroup org-sparse-trees nil
1575 "Options concerning sparse trees in Org-mode."
1576 :tag "Org Sparse Trees"
1577 :group 'org-structure)
1579 (defcustom org-highlight-sparse-tree-matches t
1580 "Non-nil means highlight all matches that define a sparse tree.
1581 The highlights will automatically disappear the next time the buffer is
1582 changed by an edit command."
1583 :group 'org-sparse-trees
1584 :type 'boolean)
1586 (defcustom org-remove-highlights-with-change t
1587 "Non-nil means any change to the buffer will remove temporary highlights.
1588 Such highlights are created by `org-occur' and `org-clock-display'.
1589 When nil, `C-c C-c needs to be used to get rid of the highlights.
1590 The highlights created by `org-preview-latex-fragment' always need
1591 `C-c C-c' to be removed."
1592 :group 'org-sparse-trees
1593 :group 'org-time
1594 :type 'boolean)
1597 (defcustom org-occur-hook '(org-first-headline-recenter)
1598 "Hook that is run after `org-occur' has constructed a sparse tree.
1599 This can be used to recenter the window to show as much of the structure
1600 as possible."
1601 :group 'org-sparse-trees
1602 :type 'hook)
1604 (defgroup org-imenu-and-speedbar nil
1605 "Options concerning imenu and speedbar in Org-mode."
1606 :tag "Org Imenu and Speedbar"
1607 :group 'org-structure)
1609 (defcustom org-imenu-depth 2
1610 "The maximum level for Imenu access to Org-mode headlines.
1611 This also applied for speedbar access."
1612 :group 'org-imenu-and-speedbar
1613 :type 'integer)
1615 (defgroup org-table nil
1616 "Options concerning tables in Org-mode."
1617 :tag "Org Table"
1618 :group 'org)
1620 (defcustom org-enable-table-editor 'optimized
1621 "Non-nil means lines starting with \"|\" are handled by the table editor.
1622 When nil, such lines will be treated like ordinary lines.
1624 When equal to the symbol `optimized', the table editor will be optimized to
1625 do the following:
1626 - Automatic overwrite mode in front of whitespace in table fields.
1627 This makes the structure of the table stay in tact as long as the edited
1628 field does not exceed the column width.
1629 - Minimize the number of realigns. Normally, the table is aligned each time
1630 TAB or RET are pressed to move to another field. With optimization this
1631 happens only if changes to a field might have changed the column width.
1632 Optimization requires replacing the functions `self-insert-command',
1633 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1634 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1635 very good at guessing when a re-align will be necessary, but you can always
1636 force one with \\[org-ctrl-c-ctrl-c].
1638 If you would like to use the optimized version in Org-mode, but the
1639 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1641 This variable can be used to turn on and off the table editor during a session,
1642 but in order to toggle optimization, a restart is required.
1644 See also the variable `org-table-auto-blank-field'."
1645 :group 'org-table
1646 :type '(choice
1647 (const :tag "off" nil)
1648 (const :tag "on" t)
1649 (const :tag "on, optimized" optimized)))
1651 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1652 (version<= emacs-version "24.1"))
1653 "Non-nil means cluster self-insert commands for undo when possible.
1654 If this is set, then, like in the Emacs command loop, 20 consecutive
1655 characters will be undone together.
1656 This is configurable, because there is some impact on typing performance."
1657 :group 'org-table
1658 :type 'boolean)
1660 (defcustom org-table-tab-recognizes-table.el t
1661 "Non-nil means TAB will automatically notice a table.el table.
1662 When it sees such a table, it moves point into it and - if necessary -
1663 calls `table-recognize-table'."
1664 :group 'org-table-editing
1665 :type 'boolean)
1667 (defgroup org-link nil
1668 "Options concerning links in Org-mode."
1669 :tag "Org Link"
1670 :group 'org)
1672 (defvar org-link-abbrev-alist-local nil
1673 "Buffer-local version of `org-link-abbrev-alist', which see.
1674 The value of this is taken from the #+LINK lines.")
1675 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1677 (defcustom org-link-abbrev-alist nil
1678 "Alist of link abbreviations.
1679 The car of each element is a string, to be replaced at the start of a link.
1680 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1681 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1683 [[linkkey:tag][description]]
1685 The 'linkkey' must be a word word, starting with a letter, followed
1686 by letters, numbers, '-' or '_'.
1688 If REPLACE is a string, the tag will simply be appended to create the link.
1689 If the string contains \"%s\", the tag will be inserted there. If the string
1690 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1691 at that point (see the function `url-hexify-string'). If the string contains
1692 the specifier \"%(my-function)\", then the custom function `my-function' will
1693 be invoked: this function takes the tag as its only argument and must return
1694 a string.
1696 REPLACE may also be a function that will be called with the tag as the
1697 only argument to create the link, which should be returned as a string.
1699 See the manual for examples."
1700 :group 'org-link
1701 :type '(repeat
1702 (cons
1703 (string :tag "Protocol")
1704 (choice
1705 (string :tag "Format")
1706 (function)))))
1708 (defcustom org-descriptive-links t
1709 "Non-nil means Org will display descriptive links.
1710 E.g. [[http://orgmode.org][Org website]] will be displayed as
1711 \"Org Website\", hiding the link itself and just displaying its
1712 description. When set to `nil', Org will display the full links
1713 literally.
1715 You can interactively set the value of this variable by calling
1716 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1717 :group 'org-link
1718 :type 'boolean)
1720 (defcustom org-link-file-path-type 'adaptive
1721 "How the path name in file links should be stored.
1722 Valid values are:
1724 relative Relative to the current directory, i.e. the directory of the file
1725 into which the link is being inserted.
1726 absolute Absolute path, if possible with ~ for home directory.
1727 noabbrev Absolute path, no abbreviation of home directory.
1728 adaptive Use relative path for files in the current directory and sub-
1729 directories of it. For other files, use an absolute path."
1730 :group 'org-link
1731 :type '(choice
1732 (const relative)
1733 (const absolute)
1734 (const noabbrev)
1735 (const adaptive)))
1737 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1738 "Types of links that should be activated in Org-mode files.
1739 This is a list of symbols, each leading to the activation of a certain link
1740 type. In principle, it does not hurt to turn on most link types - there may
1741 be a small gain when turning off unused link types. The types are:
1743 bracket The recommended [[link][description]] or [[link]] links with hiding.
1744 angle Links in angular brackets that may contain whitespace like
1745 <bbdb:Carsten Dominik>.
1746 plain Plain links in normal text, no whitespace, like http://google.com.
1747 radio Text that is matched by a radio target, see manual for details.
1748 tag Tag settings in a headline (link to tag search).
1749 date Time stamps (link to calendar).
1750 footnote Footnote labels.
1752 Changing this variable requires a restart of Emacs to become effective."
1753 :group 'org-link
1754 :type '(set :greedy t
1755 (const :tag "Double bracket links" bracket)
1756 (const :tag "Angular bracket links" angle)
1757 (const :tag "Plain text links" plain)
1758 (const :tag "Radio target matches" radio)
1759 (const :tag "Tags" tag)
1760 (const :tag "Timestamps" date)
1761 (const :tag "Footnotes" footnote)))
1763 (defcustom org-make-link-description-function nil
1764 "Function to use for generating link descriptions from links.
1765 When nil, the link location will be used. This function must take
1766 two parameters: the first one is the link, the second one is the
1767 description generated by `org-insert-link'. The function should
1768 return the description to use."
1769 :group 'org-link
1770 :type '(choice (const nil) (function)))
1772 (defgroup org-link-store nil
1773 "Options concerning storing links in Org-mode."
1774 :tag "Org Store Link"
1775 :group 'org-link)
1777 (defcustom org-url-hexify-p t
1778 "When non-nil, hexify URL when creating a link."
1779 :type 'boolean
1780 :version "24.3"
1781 :group 'org-link-store)
1783 (defcustom org-email-link-description-format "Email %c: %.30s"
1784 "Format of the description part of a link to an email or usenet message.
1785 The following %-escapes will be replaced by corresponding information:
1787 %F full \"From\" field
1788 %f name, taken from \"From\" field, address if no name
1789 %T full \"To\" field
1790 %t first name in \"To\" field, address if no name
1791 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1792 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1793 %s subject
1794 %d date
1795 %m message-id.
1797 You may use normal field width specification between the % and the letter.
1798 This is for example useful to limit the length of the subject.
1800 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1801 :group 'org-link-store
1802 :type 'string)
1804 (defcustom org-from-is-user-regexp
1805 (let (r1 r2)
1806 (when (and user-mail-address (not (string= user-mail-address "")))
1807 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1808 (when (and user-full-name (not (string= user-full-name "")))
1809 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1810 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1811 "Regexp matched against the \"From:\" header of an email or usenet message.
1812 It should match if the message is from the user him/herself."
1813 :group 'org-link-store
1814 :type 'regexp)
1816 (defcustom org-context-in-file-links t
1817 "Non-nil means file links from `org-store-link' contain context.
1818 A search string will be added to the file name with :: as separator and
1819 used to find the context when the link is activated by the command
1820 `org-open-at-point'. When this option is t, the entire active region
1821 will be placed in the search string of the file link. If set to a
1822 positive integer, only the first n lines of context will be stored.
1824 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1825 negates this setting for the duration of the command."
1826 :group 'org-link-store
1827 :type '(choice boolean integer))
1829 (defcustom org-keep-stored-link-after-insertion nil
1830 "Non-nil means keep link in list for entire session.
1832 The command `org-store-link' adds a link pointing to the current
1833 location to an internal list. These links accumulate during a session.
1834 The command `org-insert-link' can be used to insert links into any
1835 Org-mode file (offering completion for all stored links). When this
1836 option is nil, every link which has been inserted once using \\[org-insert-link]
1837 will be removed from the list, to make completing the unused links
1838 more efficient."
1839 :group 'org-link-store
1840 :type 'boolean)
1842 (defgroup org-link-follow nil
1843 "Options concerning following links in Org-mode."
1844 :tag "Org Follow Link"
1845 :group 'org-link)
1847 (defcustom org-link-translation-function nil
1848 "Function to translate links with different syntax to Org syntax.
1849 This can be used to translate links created for example by the Planner
1850 or emacs-wiki packages to Org syntax.
1851 The function must accept two parameters, a TYPE containing the link
1852 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1853 which is everything after the link protocol. It should return a cons
1854 with possibly modified values of type and path.
1855 Org contains a function for this, so if you set this variable to
1856 `org-translate-link-from-planner', you should be able follow many
1857 links created by planner."
1858 :group 'org-link-follow
1859 :type '(choice (const nil) (function)))
1861 (defcustom org-follow-link-hook nil
1862 "Hook that is run after a link has been followed."
1863 :group 'org-link-follow
1864 :type 'hook)
1866 (defcustom org-tab-follows-link nil
1867 "Non-nil means on links TAB will follow the link.
1868 Needs to be set before org.el is loaded.
1869 This really should not be used, it does not make sense, and the
1870 implementation is bad."
1871 :group 'org-link-follow
1872 :type 'boolean)
1874 (defcustom org-return-follows-link nil
1875 "Non-nil means on links RET will follow the link.
1876 In tables, the special behavior of RET has precedence."
1877 :group 'org-link-follow
1878 :type 'boolean)
1880 (defcustom org-mouse-1-follows-link
1881 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1882 "Non-nil means mouse-1 on a link will follow the link.
1883 A longer mouse click will still set point. Does not work on XEmacs.
1884 Needs to be set before org.el is loaded."
1885 :group 'org-link-follow
1886 :version "24.4"
1887 :package-version '(Org . "8.3")
1888 :type '(choice
1889 (const :tag "A double click follows the link" double)
1890 (const :tag "Unconditionally follow the link with mouse-1" t)
1891 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
1893 (defcustom org-mark-ring-length 4
1894 "Number of different positions to be recorded in the ring.
1895 Changing this requires a restart of Emacs to work correctly."
1896 :group 'org-link-follow
1897 :type 'integer)
1899 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1900 "Non-nil means internal links in Org files must exactly match a headline.
1901 When nil, the link search tries to match a phrase with all words
1902 in the search text."
1903 :group 'org-link-follow
1904 :version "24.1"
1905 :type '(choice
1906 (const :tag "Use fuzzy text search" nil)
1907 (const :tag "Match only exact headline" t)
1908 (const :tag "Match exact headline or query to create it"
1909 query-to-create)))
1911 (defcustom org-link-frame-setup
1912 '((vm . vm-visit-folder-other-frame)
1913 (vm-imap . vm-visit-imap-folder-other-frame)
1914 (gnus . org-gnus-no-new-news)
1915 (file . find-file-other-window)
1916 (wl . wl-other-frame))
1917 "Setup the frame configuration for following links.
1918 When following a link with Emacs, it may often be useful to display
1919 this link in another window or frame. This variable can be used to
1920 set this up for the different types of links.
1921 For VM, use any of
1922 `vm-visit-folder'
1923 `vm-visit-folder-other-window'
1924 `vm-visit-folder-other-frame'
1925 For Gnus, use any of
1926 `gnus'
1927 `gnus-other-frame'
1928 `org-gnus-no-new-news'
1929 For FILE, use any of
1930 `find-file'
1931 `find-file-other-window'
1932 `find-file-other-frame'
1933 For Wanderlust use any of
1934 `wl'
1935 `wl-other-frame'
1936 For the calendar, use the variable `calendar-setup'.
1937 For BBDB, it is currently only possible to display the matches in
1938 another window."
1939 :group 'org-link-follow
1940 :type '(list
1941 (cons (const vm)
1942 (choice
1943 (const vm-visit-folder)
1944 (const vm-visit-folder-other-window)
1945 (const vm-visit-folder-other-frame)))
1946 (cons (const vm-imap)
1947 (choice
1948 (const vm-visit-imap-folder)
1949 (const vm-visit-imap-folder-other-window)
1950 (const vm-visit-imap-folder-other-frame)))
1951 (cons (const gnus)
1952 (choice
1953 (const gnus)
1954 (const gnus-other-frame)
1955 (const org-gnus-no-new-news)))
1956 (cons (const file)
1957 (choice
1958 (const find-file)
1959 (const find-file-other-window)
1960 (const find-file-other-frame)))
1961 (cons (const wl)
1962 (choice
1963 (const wl)
1964 (const wl-other-frame)))))
1966 (defcustom org-display-internal-link-with-indirect-buffer nil
1967 "Non-nil means use indirect buffer to display infile links.
1968 Activating internal links (from one location in a file to another location
1969 in the same file) normally just jumps to the location. When the link is
1970 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1971 is displayed in
1972 another window. When this option is set, the other window actually displays
1973 an indirect buffer clone of the current buffer, to avoid any visibility
1974 changes to the current buffer."
1975 :group 'org-link-follow
1976 :type 'boolean)
1978 (defcustom org-open-non-existing-files nil
1979 "Non-nil means `org-open-file' will open non-existing files.
1980 When nil, an error will be generated.
1981 This variable applies only to external applications because they
1982 might choke on non-existing files. If the link is to a file that
1983 will be opened in Emacs, the variable is ignored."
1984 :group 'org-link-follow
1985 :type 'boolean)
1987 (defcustom org-open-directory-means-index-dot-org nil
1988 "Non-nil means a link to a directory really means to index.org.
1989 When nil, following a directory link will run dired or open a finder/explorer
1990 window on that directory."
1991 :group 'org-link-follow
1992 :type 'boolean)
1994 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1995 "Function and arguments to call for following mailto links.
1996 This is a list with the first element being a Lisp function, and the
1997 remaining elements being arguments to the function. In string arguments,
1998 %a will be replaced by the address, and %s will be replaced by the subject
1999 if one was given like in <mailto:arthur@galaxy.org::this subject>."
2000 :group 'org-link-follow
2001 :type '(choice
2002 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
2003 (const :tag "compose-mail" (compose-mail "%a" "%s"))
2004 (const :tag "message-mail" (message-mail "%a" "%s"))
2005 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
2007 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2008 "Non-nil means ask for confirmation before executing shell links.
2009 Shell links can be dangerous: just think about a link
2011 [[shell:rm -rf ~/*][Google Search]]
2013 This link would show up in your Org-mode document as \"Google Search\",
2014 but really it would remove your entire home directory.
2015 Therefore we advise against setting this variable to nil.
2016 Just change it to `y-or-n-p' if you want to confirm with a
2017 single keystroke rather than having to type \"yes\"."
2018 :group 'org-link-follow
2019 :type '(choice
2020 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2021 (const :tag "with y-or-n (faster)" y-or-n-p)
2022 (const :tag "no confirmation (dangerous)" nil)))
2023 (put 'org-confirm-shell-link-function
2024 'safe-local-variable
2025 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2027 (defcustom org-confirm-shell-link-not-regexp ""
2028 "A regexp to skip confirmation for shell links."
2029 :group 'org-link-follow
2030 :version "24.1"
2031 :type 'regexp)
2033 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2034 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2035 Elisp links can be dangerous: just think about a link
2037 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2039 This link would show up in your Org-mode document as \"Google Search\",
2040 but really it would remove your entire home directory.
2041 Therefore we advise against setting this variable to nil.
2042 Just change it to `y-or-n-p' if you want to confirm with a
2043 single keystroke rather than having to type \"yes\"."
2044 :group 'org-link-follow
2045 :type '(choice
2046 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2047 (const :tag "with y-or-n (faster)" y-or-n-p)
2048 (const :tag "no confirmation (dangerous)" nil)))
2049 (put 'org-confirm-shell-link-function
2050 'safe-local-variable
2051 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2053 (defcustom org-confirm-elisp-link-not-regexp ""
2054 "A regexp to skip confirmation for Elisp links."
2055 :group 'org-link-follow
2056 :version "24.1"
2057 :type 'regexp)
2059 (defconst org-file-apps-defaults-gnu
2060 '((remote . emacs)
2061 (system . mailcap)
2062 (t . mailcap))
2063 "Default file applications on a UNIX or GNU/Linux system.
2064 See `org-file-apps'.")
2066 (defconst org-file-apps-defaults-macosx
2067 '((remote . emacs)
2068 (t . "open %s")
2069 (system . "open %s")
2070 ("ps.gz" . "gv %s")
2071 ("eps.gz" . "gv %s")
2072 ("dvi" . "xdvi %s")
2073 ("fig" . "xfig %s"))
2074 "Default file applications on a MacOS X system.
2075 The system \"open\" is known as a default, but we use X11 applications
2076 for some files for which the OS does not have a good default.
2077 See `org-file-apps'.")
2079 (defconst org-file-apps-defaults-windowsnt
2080 (list
2081 '(remote . emacs)
2082 (cons t
2083 (list (if (featurep 'xemacs)
2084 'mswindows-shell-execute
2085 'w32-shell-execute)
2086 "open" 'file))
2087 (cons 'system
2088 (list (if (featurep 'xemacs)
2089 'mswindows-shell-execute
2090 'w32-shell-execute)
2091 "open" 'file)))
2092 "Default file applications on a Windows NT system.
2093 The system \"open\" is used for most files.
2094 See `org-file-apps'.")
2096 (defcustom org-file-apps
2097 '((auto-mode . emacs)
2098 ("\\.mm\\'" . default)
2099 ("\\.x?html?\\'" . default)
2100 ("\\.pdf\\'" . default))
2101 "External applications for opening `file:path' items in a document.
2102 Org-mode uses system defaults for different file types, but
2103 you can use this variable to set the application for a given file
2104 extension. The entries in this list are cons cells where the car identifies
2105 files and the cdr the corresponding command. Possible values for the
2106 file identifier are
2107 \"string\" A string as a file identifier can be interpreted in different
2108 ways, depending on its contents:
2110 - Alphanumeric characters only:
2111 Match links with this file extension.
2112 Example: (\"pdf\" . \"evince %s\")
2113 to open PDFs with evince.
2115 - Regular expression: Match links where the
2116 filename matches the regexp. If you want to
2117 use groups here, use shy groups.
2119 Example: (\"\\.x?html\\'\" . \"firefox %s\")
2120 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
2121 to open *.html and *.xhtml with firefox.
2123 - Regular expression which contains (non-shy) groups:
2124 Match links where the whole link, including \"::\", and
2125 anything after that, matches the regexp.
2126 In a custom command string, %1, %2, etc. are replaced with
2127 the parts of the link that were matched by the groups.
2128 For backwards compatibility, if a command string is given
2129 that does not use any of the group matches, this case is
2130 handled identically to the second one (i.e. match against
2131 file name only).
2132 In a custom lisp form, you can access the group matches with
2133 (match-string n link).
2135 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
2136 to open [[file:document.pdf::5]] with evince at page 5.
2138 `directory' Matches a directory
2139 `remote' Matches a remote file, accessible through tramp or efs.
2140 Remote files most likely should be visited through Emacs
2141 because external applications cannot handle such paths.
2142 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2143 so all files Emacs knows how to handle. Using this with
2144 command `emacs' will open most files in Emacs. Beware that this
2145 will also open html files inside Emacs, unless you add
2146 (\"html\" . default) to the list as well.
2147 t Default for files not matched by any of the other options.
2148 `system' The system command to open files, like `open' on Windows
2149 and Mac OS X, and mailcap under GNU/Linux. This is the command
2150 that will be selected if you call `C-c C-o' with a double
2151 \\[universal-argument] \\[universal-argument] prefix.
2153 Possible values for the command are:
2154 `emacs' The file will be visited by the current Emacs process.
2155 `default' Use the default application for this file type, which is the
2156 association for t in the list, most likely in the system-specific
2157 part.
2158 This can be used to overrule an unwanted setting in the
2159 system-specific variable.
2160 `system' Use the system command for opening files, like \"open\".
2161 This command is specified by the entry whose car is `system'.
2162 Most likely, the system-specific version of this variable
2163 does define this command, but you can overrule/replace it
2164 here.
2165 string A command to be executed by a shell; %s will be replaced
2166 by the path to the file.
2167 sexp A Lisp form which will be evaluated. The file path will
2168 be available in the Lisp variable `file'.
2169 For more examples, see the system specific constants
2170 `org-file-apps-defaults-macosx'
2171 `org-file-apps-defaults-windowsnt'
2172 `org-file-apps-defaults-gnu'."
2173 :group 'org-link-follow
2174 :type '(repeat
2175 (cons (choice :value ""
2176 (string :tag "Extension")
2177 (const :tag "System command to open files" system)
2178 (const :tag "Default for unrecognized files" t)
2179 (const :tag "Remote file" remote)
2180 (const :tag "Links to a directory" directory)
2181 (const :tag "Any files that have Emacs modes"
2182 auto-mode))
2183 (choice :value ""
2184 (const :tag "Visit with Emacs" emacs)
2185 (const :tag "Use default" default)
2186 (const :tag "Use the system command" system)
2187 (string :tag "Command")
2188 (sexp :tag "Lisp form")))))
2190 (defcustom org-doi-server-url "http://dx.doi.org/"
2191 "The URL of the DOI server."
2192 :type 'string
2193 :version "24.3"
2194 :group 'org-link-follow)
2196 (defgroup org-refile nil
2197 "Options concerning refiling entries in Org-mode."
2198 :tag "Org Refile"
2199 :group 'org)
2201 (defcustom org-directory "~/org"
2202 "Directory with org files.
2203 This is just a default location to look for Org files. There is no need
2204 at all to put your files into this directory. It is only used in the
2205 following situations:
2207 1. When a capture template specifies a target file that is not an
2208 absolute path. The path will then be interpreted relative to
2209 `org-directory'
2210 2. When a capture note is filed away in an interactive way (when exiting the
2211 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2212 with `org-directory' as the default path."
2213 :group 'org-refile
2214 :group 'org-capture
2215 :type 'directory)
2217 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2218 "Default target for storing notes.
2219 Used as a fall back file for org-capture.el, for templates that
2220 do not specify a target file."
2221 :group 'org-refile
2222 :group 'org-capture
2223 :type '(choice
2224 (const :tag "Default from remember-data-file" nil)
2225 file))
2227 (defcustom org-goto-interface 'outline
2228 "The default interface to be used for `org-goto'.
2229 Allowed values are:
2230 outline The interface shows an outline of the relevant file
2231 and the correct heading is found by moving through
2232 the outline or by searching with incremental search.
2233 outline-path-completion Headlines in the current buffer are offered via
2234 completion. This is the interface also used by
2235 the refile command."
2236 :group 'org-refile
2237 :type '(choice
2238 (const :tag "Outline" outline)
2239 (const :tag "Outline-path-completion" outline-path-completion)))
2241 (defcustom org-goto-max-level 5
2242 "Maximum target level when running `org-goto' with refile interface."
2243 :group 'org-refile
2244 :type 'integer)
2246 (defcustom org-reverse-note-order nil
2247 "Non-nil means store new notes at the beginning of a file or entry.
2248 When nil, new notes will be filed to the end of a file or entry.
2249 This can also be a list with cons cells of regular expressions that
2250 are matched against file names, and values."
2251 :group 'org-capture
2252 :group 'org-refile
2253 :type '(choice
2254 (const :tag "Reverse always" t)
2255 (const :tag "Reverse never" nil)
2256 (repeat :tag "By file name regexp"
2257 (cons regexp boolean))))
2259 (defcustom org-log-refile nil
2260 "Information to record when a task is refiled.
2262 Possible values are:
2264 nil Don't add anything
2265 time Add a time stamp to the task
2266 note Prompt for a note and add it with template `org-log-note-headings'
2268 This option can also be set with on a per-file-basis with
2270 #+STARTUP: nologrefile
2271 #+STARTUP: logrefile
2272 #+STARTUP: lognoterefile
2274 You can have local logging settings for a subtree by setting the LOGGING
2275 property to one or more of these keywords.
2277 When bulk-refiling from the agenda, the value `note' is forbidden and
2278 will temporarily be changed to `time'."
2279 :group 'org-refile
2280 :group 'org-progress
2281 :version "24.1"
2282 :type '(choice
2283 (const :tag "No logging" nil)
2284 (const :tag "Record timestamp" time)
2285 (const :tag "Record timestamp with note." note)))
2287 (defcustom org-refile-targets nil
2288 "Targets for refiling entries with \\[org-refile].
2289 This is a list of cons cells. Each cell contains:
2290 - a specification of the files to be considered, either a list of files,
2291 or a symbol whose function or variable value will be used to retrieve
2292 a file name or a list of file names. If you use `org-agenda-files' for
2293 that, all agenda files will be scanned for targets. Nil means consider
2294 headings in the current buffer.
2295 - A specification of how to find candidate refile targets. This may be
2296 any of:
2297 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2298 This tag has to be present in all target headlines, inheritance will
2299 not be considered.
2300 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2301 todo keyword.
2302 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2303 headlines that are refiling targets.
2304 - a cons cell (:level . N). Any headline of level N is considered a target.
2305 Note that, when `org-odd-levels-only' is set, level corresponds to
2306 order in hierarchy, not to the number of stars.
2307 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2308 Note that, when `org-odd-levels-only' is set, level corresponds to
2309 order in hierarchy, not to the number of stars.
2311 Each element of this list generates a set of possible targets.
2312 The union of these sets is presented (with completion) to
2313 the user by `org-refile'.
2315 You can set the variable `org-refile-target-verify-function' to a function
2316 to verify each headline found by the simple criteria above.
2318 When this variable is nil, all top-level headlines in the current buffer
2319 are used, equivalent to the value `((nil . (:level . 1))'."
2320 :group 'org-refile
2321 :type '(repeat
2322 (cons
2323 (choice :value org-agenda-files
2324 (const :tag "All agenda files" org-agenda-files)
2325 (const :tag "Current buffer" nil)
2326 (function) (variable) (file))
2327 (choice :tag "Identify target headline by"
2328 (cons :tag "Specific tag" (const :value :tag) (string))
2329 (cons :tag "TODO keyword" (const :value :todo) (string))
2330 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2331 (cons :tag "Level number" (const :value :level) (integer))
2332 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2334 (defcustom org-refile-target-verify-function nil
2335 "Function to verify if the headline at point should be a refile target.
2336 The function will be called without arguments, with point at the
2337 beginning of the headline. It should return t and leave point
2338 where it is if the headline is a valid target for refiling.
2340 If the target should not be selected, the function must return nil.
2341 In addition to this, it may move point to a place from where the search
2342 should be continued. For example, the function may decide that the entire
2343 subtree of the current entry should be excluded and move point to the end
2344 of the subtree."
2345 :group 'org-refile
2346 :type '(choice
2347 (const nil)
2348 (function)))
2350 (defcustom org-refile-use-cache nil
2351 "Non-nil means cache refile targets to speed up the process.
2352 The cache for a particular file will be updated automatically when
2353 the buffer has been killed, or when any of the marker used for flagging
2354 refile targets no longer points at a live buffer.
2355 If you have added new entries to a buffer that might themselves be targets,
2356 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2357 find that easier, `C-u C-u C-u C-c C-w'."
2358 :group 'org-refile
2359 :version "24.1"
2360 :type 'boolean)
2362 (defcustom org-refile-use-outline-path nil
2363 "Non-nil means provide refile targets as paths.
2364 So a level 3 headline will be available as level1/level2/level3.
2366 When the value is `file', also include the file name (without directory)
2367 into the path. In this case, you can also stop the completion after
2368 the file name, to get entries inserted as top level in the file.
2370 When `full-file-path', include the full file path."
2371 :group 'org-refile
2372 :type '(choice
2373 (const :tag "Not" nil)
2374 (const :tag "Yes" t)
2375 (const :tag "Start with file name" file)
2376 (const :tag "Start with full file path" full-file-path)))
2378 (defcustom org-outline-path-complete-in-steps t
2379 "Non-nil means complete the outline path in hierarchical steps.
2380 When Org-mode uses the refile interface to select an outline path
2381 \(see variable `org-refile-use-outline-path'), the completion of
2382 the path can be done is a single go, or if can be done in steps down
2383 the headline hierarchy. Going in steps is probably the best if you
2384 do not use a special completion package like `ido' or `icicles'.
2385 However, when using these packages, going in one step can be very
2386 fast, while still showing the whole path to the entry."
2387 :group 'org-refile
2388 :type 'boolean)
2390 (defcustom org-refile-allow-creating-parent-nodes nil
2391 "Non-nil means allow to create new nodes as refile targets.
2392 New nodes are then created by adding \"/new node name\" to the completion
2393 of an existing node. When the value of this variable is `confirm',
2394 new node creation must be confirmed by the user (recommended).
2395 When nil, the completion must match an existing entry.
2397 Note that, if the new heading is not seen by the criteria
2398 listed in `org-refile-targets', multiple instances of the same
2399 heading would be created by trying again to file under the new
2400 heading."
2401 :group 'org-refile
2402 :type '(choice
2403 (const :tag "Never" nil)
2404 (const :tag "Always" t)
2405 (const :tag "Prompt for confirmation" confirm)))
2407 (defcustom org-refile-active-region-within-subtree nil
2408 "Non-nil means also refile active region within a subtree.
2410 By default `org-refile' doesn't allow refiling regions if they
2411 don't contain a set of subtrees, but it might be convenient to
2412 do so sometimes: in that case, the first line of the region is
2413 converted to a headline before refiling."
2414 :group 'org-refile
2415 :version "24.1"
2416 :type 'boolean)
2418 (defgroup org-todo nil
2419 "Options concerning TODO items in Org-mode."
2420 :tag "Org TODO"
2421 :group 'org)
2423 (defgroup org-progress nil
2424 "Options concerning Progress logging in Org-mode."
2425 :tag "Org Progress"
2426 :group 'org-time)
2428 (defvar org-todo-interpretation-widgets
2429 '((:tag "Sequence (cycling hits every state)" sequence)
2430 (:tag "Type (cycling directly to DONE)" type))
2431 "The available interpretation symbols for customizing `org-todo-keywords'.
2432 Interested libraries should add to this list.")
2434 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2435 "List of TODO entry keyword sequences and their interpretation.
2436 \\<org-mode-map>This is a list of sequences.
2438 Each sequence starts with a symbol, either `sequence' or `type',
2439 indicating if the keywords should be interpreted as a sequence of
2440 action steps, or as different types of TODO items. The first
2441 keywords are states requiring action - these states will select a headline
2442 for inclusion into the global TODO list Org-mode produces. If one of
2443 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2444 signify that no further action is necessary. If \"|\" is not found,
2445 the last keyword is treated as the only DONE state of the sequence.
2447 The command \\[org-todo] cycles an entry through these states, and one
2448 additional state where no keyword is present. For details about this
2449 cycling, see the manual.
2451 TODO keywords and interpretation can also be set on a per-file basis with
2452 the special #+SEQ_TODO and #+TYP_TODO lines.
2454 Each keyword can optionally specify a character for fast state selection
2455 \(in combination with the variable `org-use-fast-todo-selection')
2456 and specifiers for state change logging, using the same syntax that
2457 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2458 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2459 indicates to record a time stamp each time this state is selected.
2461 Each keyword may also specify if a timestamp or a note should be
2462 recorded when entering or leaving the state, by adding additional
2463 characters in the parenthesis after the keyword. This looks like this:
2464 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2465 record only the time of the state change. With X and Y being either
2466 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2467 Y when leaving the state if and only if the *target* state does not
2468 define X. You may omit any of the fast-selection key or X or /Y,
2469 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2471 For backward compatibility, this variable may also be just a list
2472 of keywords. In this case the interpretation (sequence or type) will be
2473 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2474 :group 'org-todo
2475 :group 'org-keywords
2476 :type '(choice
2477 (repeat :tag "Old syntax, just keywords"
2478 (string :tag "Keyword"))
2479 (repeat :tag "New syntax"
2480 (cons
2481 (choice
2482 :tag "Interpretation"
2483 ;;Quick and dirty way to see
2484 ;;`org-todo-interpretations'. This takes the
2485 ;;place of item arguments
2486 :convert-widget
2487 (lambda (widget)
2488 (widget-put widget
2489 :args (mapcar
2490 #'(lambda (x)
2491 (widget-convert
2492 (cons 'const x)))
2493 org-todo-interpretation-widgets))
2494 widget))
2495 (repeat
2496 (string :tag "Keyword"))))))
2498 (defvar org-todo-keywords-1 nil
2499 "All TODO and DONE keywords active in a buffer.")
2500 (make-variable-buffer-local 'org-todo-keywords-1)
2501 (defvar org-todo-keywords-for-agenda nil)
2502 (defvar org-done-keywords-for-agenda nil)
2503 (defvar org-todo-keyword-alist-for-agenda nil)
2504 (defvar org-tag-alist-for-agenda nil
2505 "Alist of all tags from all agenda files.")
2506 (defvar org-tag-groups-alist-for-agenda nil
2507 "Alist of all groups tags from all current agenda files.")
2508 (defvar org-tag-groups-alist nil)
2509 (make-variable-buffer-local 'org-tag-groups-alist)
2510 (defvar org-agenda-contributing-files nil)
2511 (defvar org-not-done-keywords nil)
2512 (make-variable-buffer-local 'org-not-done-keywords)
2513 (defvar org-done-keywords nil)
2514 (make-variable-buffer-local 'org-done-keywords)
2515 (defvar org-todo-heads nil)
2516 (make-variable-buffer-local 'org-todo-heads)
2517 (defvar org-todo-sets nil)
2518 (make-variable-buffer-local 'org-todo-sets)
2519 (defvar org-todo-log-states nil)
2520 (make-variable-buffer-local 'org-todo-log-states)
2521 (defvar org-todo-kwd-alist nil)
2522 (make-variable-buffer-local 'org-todo-kwd-alist)
2523 (defvar org-todo-key-alist nil)
2524 (make-variable-buffer-local 'org-todo-key-alist)
2525 (defvar org-todo-key-trigger nil)
2526 (make-variable-buffer-local 'org-todo-key-trigger)
2528 (defcustom org-todo-interpretation 'sequence
2529 "Controls how TODO keywords are interpreted.
2530 This variable is in principle obsolete and is only used for
2531 backward compatibility, if the interpretation of todo keywords is
2532 not given already in `org-todo-keywords'. See that variable for
2533 more information."
2534 :group 'org-todo
2535 :group 'org-keywords
2536 :type '(choice (const sequence)
2537 (const type)))
2539 (defcustom org-use-fast-todo-selection t
2540 "Non-nil means use the fast todo selection scheme with C-c C-t.
2541 This variable describes if and under what circumstances the cycling
2542 mechanism for TODO keywords will be replaced by a single-key, direct
2543 selection scheme.
2545 When nil, fast selection is never used.
2547 When the symbol `prefix', it will be used when `org-todo' is called
2548 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2549 `C-u t' in an agenda buffer.
2551 When t, fast selection is used by default. In this case, the prefix
2552 argument forces cycling instead.
2554 In all cases, the special interface is only used if access keys have
2555 actually been assigned by the user, i.e. if keywords in the configuration
2556 are followed by a letter in parenthesis, like TODO(t)."
2557 :group 'org-todo
2558 :type '(choice
2559 (const :tag "Never" nil)
2560 (const :tag "By default" t)
2561 (const :tag "Only with C-u C-c C-t" prefix)))
2563 (defcustom org-provide-todo-statistics t
2564 "Non-nil means update todo statistics after insert and toggle.
2565 ALL-HEADLINES means update todo statistics by including headlines
2566 with no TODO keyword as well, counting them as not done.
2567 A list of TODO keywords means the same, but skip keywords that are
2568 not in this list.
2570 When this is set, todo statistics is updated in the parent of the
2571 current entry each time a todo state is changed."
2572 :group 'org-todo
2573 :type '(choice
2574 (const :tag "Yes, only for TODO entries" t)
2575 (const :tag "Yes, including all entries" all-headlines)
2576 (repeat :tag "Yes, for TODOs in this list"
2577 (string :tag "TODO keyword"))
2578 (other :tag "No TODO statistics" nil)))
2580 (defcustom org-hierarchical-todo-statistics t
2581 "Non-nil means TODO statistics covers just direct children.
2582 When nil, all entries in the subtree are considered.
2583 This has only an effect if `org-provide-todo-statistics' is set.
2584 To set this to nil for only a single subtree, use a COOKIE_DATA
2585 property and include the word \"recursive\" into the value."
2586 :group 'org-todo
2587 :type 'boolean)
2589 (defcustom org-after-todo-state-change-hook nil
2590 "Hook which is run after the state of a TODO item was changed.
2591 The new state (a string with a TODO keyword, or nil) is available in the
2592 Lisp variable `org-state'."
2593 :group 'org-todo
2594 :type 'hook)
2596 (defvar org-blocker-hook nil
2597 "Hook for functions that are allowed to block a state change.
2599 Functions in this hook should not modify the buffer.
2600 Each function gets as its single argument a property list,
2601 see `org-trigger-hook' for more information about this list.
2603 If any of the functions in this hook returns nil, the state change
2604 is blocked.")
2606 (defvar org-trigger-hook nil
2607 "Hook for functions that are triggered by a state change.
2609 Each function gets as its single argument a property list with at
2610 least the following elements:
2612 (:type type-of-change :position pos-at-entry-start
2613 :from old-state :to new-state)
2615 Depending on the type, more properties may be present.
2617 This mechanism is currently implemented for:
2619 TODO state changes
2620 ------------------
2621 :type todo-state-change
2622 :from previous state (keyword as a string), or nil, or a symbol
2623 'todo' or 'done', to indicate the general type of state.
2624 :to new state, like in :from")
2626 (defcustom org-enforce-todo-dependencies nil
2627 "Non-nil means undone TODO entries will block switching the parent to DONE.
2628 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2629 be blocked if any prior sibling is not yet done.
2630 Finally, if the parent is blocked because of ordered siblings of its own,
2631 the child will also be blocked."
2632 :set (lambda (var val)
2633 (set var val)
2634 (if val
2635 (add-hook 'org-blocker-hook
2636 'org-block-todo-from-children-or-siblings-or-parent)
2637 (remove-hook 'org-blocker-hook
2638 'org-block-todo-from-children-or-siblings-or-parent)))
2639 :group 'org-todo
2640 :type 'boolean)
2642 (defcustom org-enforce-todo-checkbox-dependencies nil
2643 "Non-nil means unchecked boxes will block switching the parent to DONE.
2644 When this is nil, checkboxes have no influence on switching TODO states.
2645 When non-nil, you first need to check off all check boxes before the TODO
2646 entry can be switched to DONE.
2647 This variable needs to be set before org.el is loaded, and you need to
2648 restart Emacs after a change to make the change effective. The only way
2649 to change is while Emacs is running is through the customize interface."
2650 :set (lambda (var val)
2651 (set var val)
2652 (if val
2653 (add-hook 'org-blocker-hook
2654 'org-block-todo-from-checkboxes)
2655 (remove-hook 'org-blocker-hook
2656 'org-block-todo-from-checkboxes)))
2657 :group 'org-todo
2658 :type 'boolean)
2660 (defcustom org-treat-insert-todo-heading-as-state-change nil
2661 "Non-nil means inserting a TODO heading is treated as state change.
2662 So when the command \\[org-insert-todo-heading] is used, state change
2663 logging will apply if appropriate. When nil, the new TODO item will
2664 be inserted directly, and no logging will take place."
2665 :group 'org-todo
2666 :type 'boolean)
2668 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2669 "Non-nil means switching TODO states with S-cursor counts as state change.
2670 This is the default behavior. However, setting this to nil allows a
2671 convenient way to select a TODO state and bypass any logging associated
2672 with that."
2673 :group 'org-todo
2674 :type 'boolean)
2676 (defcustom org-todo-state-tags-triggers nil
2677 "Tag changes that should be triggered by TODO state changes.
2678 This is a list. Each entry is
2680 (state-change (tag . flag) .......)
2682 State-change can be a string with a state, and empty string to indicate the
2683 state that has no TODO keyword, or it can be one of the symbols `todo'
2684 or `done', meaning any not-done or done state, respectively."
2685 :group 'org-todo
2686 :group 'org-tags
2687 :type '(repeat
2688 (cons (choice :tag "When changing to"
2689 (const :tag "Not-done state" todo)
2690 (const :tag "Done state" done)
2691 (string :tag "State"))
2692 (repeat
2693 (cons :tag "Tag action"
2694 (string :tag "Tag")
2695 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2697 (defcustom org-log-done nil
2698 "Information to record when a task moves to the DONE state.
2700 Possible values are:
2702 nil Don't add anything, just change the keyword
2703 time Add a time stamp to the task
2704 note Prompt for a note and add it with template `org-log-note-headings'
2706 This option can also be set with on a per-file-basis with
2708 #+STARTUP: nologdone
2709 #+STARTUP: logdone
2710 #+STARTUP: lognotedone
2712 You can have local logging settings for a subtree by setting the LOGGING
2713 property to one or more of these keywords."
2714 :group 'org-todo
2715 :group 'org-progress
2716 :type '(choice
2717 (const :tag "No logging" nil)
2718 (const :tag "Record CLOSED timestamp" time)
2719 (const :tag "Record CLOSED timestamp with note." note)))
2721 ;; Normalize old uses of org-log-done.
2722 (cond
2723 ((eq org-log-done t) (setq org-log-done 'time))
2724 ((and (listp org-log-done) (memq 'done org-log-done))
2725 (setq org-log-done 'note)))
2727 (defcustom org-log-reschedule nil
2728 "Information to record when the scheduling date of a tasks is modified.
2730 Possible values are:
2732 nil Don't add anything, just change the date
2733 time Add a time stamp to the task
2734 note Prompt for a note and add it with template `org-log-note-headings'
2736 This option can also be set with on a per-file-basis with
2738 #+STARTUP: nologreschedule
2739 #+STARTUP: logreschedule
2740 #+STARTUP: lognotereschedule"
2741 :group 'org-todo
2742 :group 'org-progress
2743 :type '(choice
2744 (const :tag "No logging" nil)
2745 (const :tag "Record timestamp" time)
2746 (const :tag "Record timestamp with note." note)))
2748 (defcustom org-log-redeadline nil
2749 "Information to record when the deadline date of a tasks is modified.
2751 Possible values are:
2753 nil Don't add anything, just change the date
2754 time Add a time stamp to the task
2755 note Prompt for a note and add it with template `org-log-note-headings'
2757 This option can also be set with on a per-file-basis with
2759 #+STARTUP: nologredeadline
2760 #+STARTUP: logredeadline
2761 #+STARTUP: lognoteredeadline
2763 You can have local logging settings for a subtree by setting the LOGGING
2764 property to one or more of these keywords."
2765 :group 'org-todo
2766 :group 'org-progress
2767 :type '(choice
2768 (const :tag "No logging" nil)
2769 (const :tag "Record timestamp" time)
2770 (const :tag "Record timestamp with note." note)))
2772 (defcustom org-log-note-clock-out nil
2773 "Non-nil means record a note when clocking out of an item.
2774 This can also be configured on a per-file basis by adding one of
2775 the following lines anywhere in the buffer:
2777 #+STARTUP: lognoteclock-out
2778 #+STARTUP: nolognoteclock-out"
2779 :group 'org-todo
2780 :group 'org-progress
2781 :type 'boolean)
2783 (defcustom org-log-done-with-time t
2784 "Non-nil means the CLOSED time stamp will contain date and time.
2785 When nil, only the date will be recorded."
2786 :group 'org-progress
2787 :type 'boolean)
2789 (defcustom org-log-note-headings
2790 '((done . "CLOSING NOTE %t")
2791 (state . "State %-12s from %-12S %t")
2792 (note . "Note taken on %t")
2793 (reschedule . "Rescheduled from %S on %t")
2794 (delschedule . "Not scheduled, was %S on %t")
2795 (redeadline . "New deadline from %S on %t")
2796 (deldeadline . "Removed deadline, was %S on %t")
2797 (refile . "Refiled on %t")
2798 (clock-out . ""))
2799 "Headings for notes added to entries.
2800 The value is an alist, with the car being a symbol indicating the note
2801 context, and the cdr is the heading to be used. The heading may also be the
2802 empty string.
2803 %t in the heading will be replaced by a time stamp.
2804 %T will be an active time stamp instead the default inactive one
2805 %d will be replaced by a short-format time stamp.
2806 %D will be replaced by an active short-format time stamp.
2807 %s will be replaced by the new TODO state, in double quotes.
2808 %S will be replaced by the old TODO state, in double quotes.
2809 %u will be replaced by the user name.
2810 %U will be replaced by the full user name.
2812 In fact, it is not a good idea to change the `state' entry, because
2813 agenda log mode depends on the format of these entries."
2814 :group 'org-todo
2815 :group 'org-progress
2816 :type '(list :greedy t
2817 (cons (const :tag "Heading when closing an item" done) string)
2818 (cons (const :tag
2819 "Heading when changing todo state (todo sequence only)"
2820 state) string)
2821 (cons (const :tag "Heading when just taking a note" note) string)
2822 (cons (const :tag "Heading when rescheduling" reschedule) string)
2823 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2824 (cons (const :tag "Heading when changing deadline" redeadline) string)
2825 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2826 (cons (const :tag "Heading when refiling" refile) string)
2827 (cons (const :tag "Heading when clocking out" clock-out) string)))
2829 (unless (assq 'note org-log-note-headings)
2830 (push '(note . "%t") org-log-note-headings))
2832 (defcustom org-log-into-drawer nil
2833 "Non-nil means insert state change notes and time stamps into a drawer.
2834 When nil, state changes notes will be inserted after the headline and
2835 any scheduling and clock lines, but not inside a drawer.
2837 The value of this variable should be the name of the drawer to use.
2838 LOGBOOK is proposed as the default drawer for this purpose, you can
2839 also set this to a string to define the drawer of your choice.
2841 A value of t is also allowed, representing \"LOGBOOK\".
2843 A value of t or nil can also be set with on a per-file-basis with
2845 #+STARTUP: logdrawer
2846 #+STARTUP: nologdrawer
2848 If this variable is set, `org-log-state-notes-insert-after-drawers'
2849 will be ignored.
2851 You can set the property LOG_INTO_DRAWER to overrule this setting for
2852 a subtree."
2853 :group 'org-todo
2854 :group 'org-progress
2855 :type '(choice
2856 (const :tag "Not into a drawer" nil)
2857 (const :tag "LOGBOOK" t)
2858 (string :tag "Other")))
2860 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2862 (defun org-log-into-drawer ()
2863 "Return the value of `org-log-into-drawer', but let properties overrule.
2864 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2865 used instead of the default value."
2866 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2867 (cond
2868 ((not p) org-log-into-drawer)
2869 ((equal p "nil") nil)
2870 ((equal p "t") "LOGBOOK")
2871 (t p))))
2873 (defcustom org-log-state-notes-insert-after-drawers nil
2874 "Non-nil means insert state change notes after any drawers in entry.
2875 Only the drawers that *immediately* follow the headline and the
2876 deadline/scheduled line are skipped.
2877 When nil, insert notes right after the heading and perhaps the line
2878 with deadline/scheduling if present.
2880 This variable will have no effect if `org-log-into-drawer' is
2881 set."
2882 :group 'org-todo
2883 :group 'org-progress
2884 :type 'boolean)
2886 (defcustom org-log-states-order-reversed t
2887 "Non-nil means the latest state note will be directly after heading.
2888 When nil, the state change notes will be ordered according to time.
2890 This option can also be set with on a per-file-basis with
2892 #+STARTUP: logstatesreversed
2893 #+STARTUP: nologstatesreversed"
2894 :group 'org-todo
2895 :group 'org-progress
2896 :type 'boolean)
2898 (defcustom org-todo-repeat-to-state nil
2899 "The TODO state to which a repeater should return the repeating task.
2900 By default this is the first task in a TODO sequence, or the previous state
2901 in a TODO_TYP set. But you can specify another task here.
2902 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2903 :group 'org-todo
2904 :version "24.1"
2905 :type '(choice (const :tag "Head of sequence" nil)
2906 (string :tag "Specific state")))
2908 (defcustom org-log-repeat 'time
2909 "Non-nil means record moving through the DONE state when triggering repeat.
2910 An auto-repeating task is immediately switched back to TODO when
2911 marked DONE. If you are not logging state changes (by adding \"@\"
2912 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2913 record a closing note, there will be no record of the task moving
2914 through DONE. This variable forces taking a note anyway.
2916 nil Don't force a record
2917 time Record a time stamp
2918 note Prompt for a note and add it with template `org-log-note-headings'
2920 This option can also be set with on a per-file-basis with
2922 #+STARTUP: nologrepeat
2923 #+STARTUP: logrepeat
2924 #+STARTUP: lognoterepeat
2926 You can have local logging settings for a subtree by setting the LOGGING
2927 property to one or more of these keywords."
2928 :group 'org-todo
2929 :group 'org-progress
2930 :type '(choice
2931 (const :tag "Don't force a record" nil)
2932 (const :tag "Force recording the DONE state" time)
2933 (const :tag "Force recording a note with the DONE state" note)))
2936 (defgroup org-priorities nil
2937 "Priorities in Org-mode."
2938 :tag "Org Priorities"
2939 :group 'org-todo)
2941 (defcustom org-enable-priority-commands t
2942 "Non-nil means priority commands are active.
2943 When nil, these commands will be disabled, so that you never accidentally
2944 set a priority."
2945 :group 'org-priorities
2946 :type 'boolean)
2948 (defcustom org-highest-priority ?A
2949 "The highest priority of TODO items. A character like ?A, ?B etc.
2950 Must have a smaller ASCII number than `org-lowest-priority'."
2951 :group 'org-priorities
2952 :type 'character)
2954 (defcustom org-lowest-priority ?C
2955 "The lowest priority of TODO items. A character like ?A, ?B etc.
2956 Must have a larger ASCII number than `org-highest-priority'."
2957 :group 'org-priorities
2958 :type 'character)
2960 (defcustom org-default-priority ?B
2961 "The default priority of TODO items.
2962 This is the priority an item gets if no explicit priority is given.
2963 When starting to cycle on an empty priority the first step in the cycle
2964 depends on `org-priority-start-cycle-with-default'. The resulting first
2965 step priority must not exceed the range from `org-highest-priority' to
2966 `org-lowest-priority' which means that `org-default-priority' has to be
2967 in this range exclusive or inclusive the range boundaries. Else the
2968 first step refuses to set the default and the second will fall back
2969 to (depending on the command used) the highest or lowest priority."
2970 :group 'org-priorities
2971 :type 'character)
2973 (defcustom org-priority-start-cycle-with-default t
2974 "Non-nil means start with default priority when starting to cycle.
2975 When this is nil, the first step in the cycle will be (depending on the
2976 command used) one higher or lower than the default priority.
2977 See also `org-default-priority'."
2978 :group 'org-priorities
2979 :type 'boolean)
2981 (defcustom org-get-priority-function nil
2982 "Function to extract the priority from a string.
2983 The string is normally the headline. If this is nil Org computes the
2984 priority from the priority cookie like [#A] in the headline. It returns
2985 an integer, increasing by 1000 for each priority level.
2986 The user can set a different function here, which should take a string
2987 as an argument and return the numeric priority."
2988 :group 'org-priorities
2989 :version "24.1"
2990 :type '(choice
2991 (const nil)
2992 (function)))
2994 (defgroup org-time nil
2995 "Options concerning time stamps and deadlines in Org-mode."
2996 :tag "Org Time"
2997 :group 'org)
2999 (defcustom org-insert-labeled-timestamps-at-point nil
3000 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
3001 When nil, these labeled time stamps are forces into the second line of an
3002 entry, just after the headline. When scheduling from the global TODO list,
3003 the time stamp will always be forced into the second line."
3004 :group 'org-time
3005 :type 'boolean)
3007 (defcustom org-time-stamp-rounding-minutes '(0 5)
3008 "Number of minutes to round time stamps to.
3009 These are two values, the first applies when first creating a time stamp.
3010 The second applies when changing it with the commands `S-up' and `S-down'.
3011 When changing the time stamp, this means that it will change in steps
3012 of N minutes, as given by the second value.
3014 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3015 numbers should be factors of 60, so for example 5, 10, 15.
3017 When this is larger than 1, you can still force an exact time stamp by using
3018 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
3019 and by using a prefix arg to `S-up/down' to specify the exact number
3020 of minutes to shift."
3021 :group 'org-time
3022 :get #'(lambda (var) ; Make sure both elements are there
3023 (if (integerp (default-value var))
3024 (list (default-value var) 5)
3025 (default-value var)))
3026 :type '(list
3027 (integer :tag "when inserting times")
3028 (integer :tag "when modifying times")))
3030 ;; Normalize old customizations of this variable.
3031 (when (integerp org-time-stamp-rounding-minutes)
3032 (setq org-time-stamp-rounding-minutes
3033 (list org-time-stamp-rounding-minutes
3034 org-time-stamp-rounding-minutes)))
3036 (defcustom org-display-custom-times nil
3037 "Non-nil means overlay custom formats over all time stamps.
3038 The formats are defined through the variable `org-time-stamp-custom-formats'.
3039 To turn this on on a per-file basis, insert anywhere in the file:
3040 #+STARTUP: customtime"
3041 :group 'org-time
3042 :set 'set-default
3043 :type 'sexp)
3044 (make-variable-buffer-local 'org-display-custom-times)
3046 (defcustom org-time-stamp-custom-formats
3047 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3048 "Custom formats for time stamps. See `format-time-string' for the syntax.
3049 These are overlaid over the default ISO format if the variable
3050 `org-display-custom-times' is set. Time like %H:%M should be at the
3051 end of the second format. The custom formats are also honored by export
3052 commands, if custom time display is turned on at the time of export."
3053 :group 'org-time
3054 :type 'sexp)
3056 (defun org-time-stamp-format (&optional long inactive)
3057 "Get the right format for a time string."
3058 (let ((f (if long (cdr org-time-stamp-formats)
3059 (car org-time-stamp-formats))))
3060 (if inactive
3061 (concat "[" (substring f 1 -1) "]")
3062 f)))
3064 (defcustom org-time-clocksum-format
3065 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
3066 "The format string used when creating CLOCKSUM lines.
3067 This is also used when Org mode generates a time duration.
3069 The value can be a single format string containing two
3070 %-sequences, which will be filled with the number of hours and
3071 minutes in that order.
3073 Alternatively, the value can be a plist associating any of the
3074 keys :years, :months, :weeks, :days, :hours or :minutes with
3075 format strings. The time duration is formatted using only the
3076 time components that are needed and concatenating the results.
3077 If a time unit in absent, it falls back to the next smallest
3078 unit.
3080 The keys :require-years, :require-months, :require-days,
3081 :require-weeks, :require-hours, :require-minutes are also
3082 meaningful. A non-nil value for these keys indicates that the
3083 corresponding time component should always be included, even if
3084 its value is 0.
3087 For example,
3089 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
3090 :require-minutes t)
3092 means durations longer than a day will be expressed in days,
3093 hours and minutes, and durations less than a day will always be
3094 expressed in hours and minutes (even for durations less than an
3095 hour).
3097 The value
3099 \(:days \"%dd\" :minutes \"%dm\")
3101 means durations longer than a day will be expressed in days and
3102 minutes, and durations less than a day will be expressed entirely
3103 in minutes (even for durations longer than an hour)."
3104 :group 'org-time
3105 :group 'org-clock
3106 :version "24.4"
3107 :package-version '(Org . "8.0")
3108 :type '(choice (string :tag "Format string")
3109 (set :tag "Plist"
3110 (group :inline t (const :tag "Years" :years)
3111 (string :tag "Format string"))
3112 (group :inline t
3113 (const :tag "Always show years" :require-years)
3114 (const t))
3115 (group :inline t (const :tag "Months" :months)
3116 (string :tag "Format string"))
3117 (group :inline t
3118 (const :tag "Always show months" :require-months)
3119 (const t))
3120 (group :inline t (const :tag "Weeks" :weeks)
3121 (string :tag "Format string"))
3122 (group :inline t
3123 (const :tag "Always show weeks" :require-weeks)
3124 (const t))
3125 (group :inline t (const :tag "Days" :days)
3126 (string :tag "Format string"))
3127 (group :inline t
3128 (const :tag "Always show days" :require-days)
3129 (const t))
3130 (group :inline t (const :tag "Hours" :hours)
3131 (string :tag "Format string"))
3132 (group :inline t
3133 (const :tag "Always show hours" :require-hours)
3134 (const t))
3135 (group :inline t (const :tag "Minutes" :minutes)
3136 (string :tag "Format string"))
3137 (group :inline t
3138 (const :tag "Always show minutes" :require-minutes)
3139 (const t)))))
3141 (defcustom org-time-clocksum-use-fractional nil
3142 "When non-nil, \\[org-clock-display] uses fractional times.
3143 See `org-time-clocksum-format' for more on time clock formats."
3144 :group 'org-time
3145 :group 'org-clock
3146 :version "24.3"
3147 :type 'boolean)
3149 (defcustom org-time-clocksum-use-effort-durations nil
3150 "When non-nil, \\[org-clock-display] uses effort durations.
3151 E.g. by default, one day is considered to be a 8 hours effort,
3152 so a task that has been clocked for 16 hours will be displayed
3153 as during 2 days in the clock display or in the clocktable.
3155 See `org-effort-durations' on how to set effort durations
3156 and `org-time-clocksum-format' for more on time clock formats."
3157 :group 'org-time
3158 :group 'org-clock
3159 :version "24.4"
3160 :package-version '(Org . "8.0")
3161 :type 'boolean)
3163 (defcustom org-time-clocksum-fractional-format "%.2f"
3164 "The format string used when creating CLOCKSUM lines,
3165 or when Org mode generates a time duration, if
3166 `org-time-clocksum-use-fractional' is enabled.
3168 The value can be a single format string containing one
3169 %-sequence, which will be filled with the number of hours as
3170 a float.
3172 Alternatively, the value can be a plist associating any of the
3173 keys :years, :months, :weeks, :days, :hours or :minutes with
3174 a format string. The time duration is formatted using the
3175 largest time unit which gives a non-zero integer part. If all
3176 specified formats have zero integer part, the smallest time unit
3177 is used."
3178 :group 'org-time
3179 :type '(choice (string :tag "Format string")
3180 (set (group :inline t (const :tag "Years" :years)
3181 (string :tag "Format string"))
3182 (group :inline t (const :tag "Months" :months)
3183 (string :tag "Format string"))
3184 (group :inline t (const :tag "Weeks" :weeks)
3185 (string :tag "Format string"))
3186 (group :inline t (const :tag "Days" :days)
3187 (string :tag "Format string"))
3188 (group :inline t (const :tag "Hours" :hours)
3189 (string :tag "Format string"))
3190 (group :inline t (const :tag "Minutes" :minutes)
3191 (string :tag "Format string")))))
3193 (defcustom org-deadline-warning-days 14
3194 "Number of days before expiration during which a deadline becomes active.
3195 This variable governs the display in sparse trees and in the agenda.
3196 When 0 or negative, it means use this number (the absolute value of it)
3197 even if a deadline has a different individual lead time specified.
3199 Custom commands can set this variable in the options section."
3200 :group 'org-time
3201 :group 'org-agenda-daily/weekly
3202 :type 'integer)
3204 (defcustom org-scheduled-delay-days 0
3205 "Number of days before a scheduled item becomes active.
3206 This variable governs the display in sparse trees and in the agenda.
3207 The default value (i.e. 0) means: don't delay scheduled item.
3208 When negative, it means use this number (the absolute value of it)
3209 even if a scheduled item has a different individual delay time
3210 specified.
3212 Custom commands can set this variable in the options section."
3213 :group 'org-time
3214 :group 'org-agenda-daily/weekly
3215 :version "24.4"
3216 :package-version '(Org . "8.0")
3217 :type 'integer)
3219 (defcustom org-read-date-prefer-future t
3220 "Non-nil means assume future for incomplete date input from user.
3221 This affects the following situations:
3222 1. The user gives a month but not a year.
3223 For example, if it is April and you enter \"feb 2\", this will be read
3224 as Feb 2, *next* year. \"May 5\", however, will be this year.
3225 2. The user gives a day, but no month.
3226 For example, if today is the 15th, and you enter \"3\", Org-mode will
3227 read this as the third of *next* month. However, if you enter \"17\",
3228 it will be considered as *this* month.
3230 If you set this variable to the symbol `time', then also the following
3231 will work:
3233 3. If the user gives a time.
3234 If the time is before now, it will be interpreted as tomorrow.
3236 Currently none of this works for ISO week specifications.
3238 When this option is nil, the current day, month and year will always be
3239 used as defaults.
3241 See also `org-agenda-jump-prefer-future'."
3242 :group 'org-time
3243 :type '(choice
3244 (const :tag "Never" nil)
3245 (const :tag "Check month and day" t)
3246 (const :tag "Check month, day, and time" time)))
3248 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3249 "Should the agenda jump command prefer the future for incomplete dates?
3250 The default is to do the same as configured in `org-read-date-prefer-future'.
3251 But you can also set a deviating value here.
3252 This may t or nil, or the symbol `org-read-date-prefer-future'."
3253 :group 'org-agenda
3254 :group 'org-time
3255 :version "24.1"
3256 :type '(choice
3257 (const :tag "Use org-read-date-prefer-future"
3258 org-read-date-prefer-future)
3259 (const :tag "Never" nil)
3260 (const :tag "Always" t)))
3262 (defcustom org-read-date-force-compatible-dates t
3263 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3265 Depending on the system Emacs is running on, certain dates cannot
3266 be represented with the type used internally to represent time.
3267 Dates between 1970-1-1 and 2038-1-1 can always be represented
3268 correctly. Some systems allow for earlier dates, some for later,
3269 some for both. One way to find out it to insert any date into an
3270 Org buffer, putting the cursor on the year and hitting S-up and
3271 S-down to test the range.
3273 When this variable is set to t, the date/time prompt will not let
3274 you specify dates outside the 1970-2037 range, so it is certain that
3275 these dates will work in whatever version of Emacs you are
3276 running, and also that you can move a file from one Emacs implementation
3277 to another. WHenever Org is forcing the year for you, it will display
3278 a message and beep.
3280 When this variable is nil, Org will check if the date is
3281 representable in the specific Emacs implementation you are using.
3282 If not, it will force a year, usually the current year, and beep
3283 to remind you. Currently this setting is not recommended because
3284 the likelihood that you will open your Org files in an Emacs that
3285 has limited date range is not negligible.
3287 A workaround for this problem is to use diary sexp dates for time
3288 stamps outside of this range."
3289 :group 'org-time
3290 :version "24.1"
3291 :type 'boolean)
3293 (defcustom org-read-date-display-live t
3294 "Non-nil means display current interpretation of date prompt live.
3295 This display will be in an overlay, in the minibuffer."
3296 :group 'org-time
3297 :type 'boolean)
3299 (defcustom org-read-date-popup-calendar t
3300 "Non-nil means pop up a calendar when prompting for a date.
3301 In the calendar, the date can be selected with mouse-1. However, the
3302 minibuffer will also be active, and you can simply enter the date as well.
3303 When nil, only the minibuffer will be available."
3304 :group 'org-time
3305 :type 'boolean)
3306 (org-defvaralias 'org-popup-calendar-for-date-prompt
3307 'org-read-date-popup-calendar)
3309 (make-obsolete-variable
3310 'org-read-date-minibuffer-setup-hook
3311 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3312 (defcustom org-read-date-minibuffer-setup-hook nil
3313 "Hook to be used to set up keys for the date/time interface.
3314 Add key definitions to `minibuffer-local-map', which will be a
3315 temporary copy.
3317 WARNING: This option is obsolete, you should use
3318 `org-read-date-minibuffer-local-map' to set up keys."
3319 :group 'org-time
3320 :type 'hook)
3322 (defcustom org-extend-today-until 0
3323 "The hour when your day really ends. Must be an integer.
3324 This has influence for the following applications:
3325 - When switching the agenda to \"today\". It it is still earlier than
3326 the time given here, the day recognized as TODAY is actually yesterday.
3327 - When a date is read from the user and it is still before the time given
3328 here, the current date and time will be assumed to be yesterday, 23:59.
3329 Also, timestamps inserted in capture templates follow this rule.
3331 IMPORTANT: This is a feature whose implementation is and likely will
3332 remain incomplete. Really, it is only here because past midnight seems to
3333 be the favorite working time of John Wiegley :-)"
3334 :group 'org-time
3335 :type 'integer)
3337 (defcustom org-use-effective-time nil
3338 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3339 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3340 \"effective time\" of any timestamps between midnight and 8am will be
3341 23:59 of the previous day."
3342 :group 'org-time
3343 :version "24.1"
3344 :type 'boolean)
3346 (defcustom org-use-last-clock-out-time-as-effective-time nil
3347 "When non-nil, use the last clock out time for `org-todo'.
3348 Note that this option has precedence over the combined use of
3349 `org-use-effective-time' and `org-extend-today-until'."
3350 :group 'org-time
3351 :version "24.4"
3352 :package-version '(Org . "8.0")
3353 :type 'boolean)
3355 (defcustom org-edit-timestamp-down-means-later nil
3356 "Non-nil means S-down will increase the time in a time stamp.
3357 When nil, S-up will increase."
3358 :group 'org-time
3359 :type 'boolean)
3361 (defcustom org-calendar-follow-timestamp-change t
3362 "Non-nil means make the calendar window follow timestamp changes.
3363 When a timestamp is modified and the calendar window is visible, it will be
3364 moved to the new date."
3365 :group 'org-time
3366 :type 'boolean)
3368 (defgroup org-tags nil
3369 "Options concerning tags in Org-mode."
3370 :tag "Org Tags"
3371 :group 'org)
3373 (defcustom org-tag-alist nil
3374 "List of tags allowed in Org-mode files.
3375 When this list is nil, Org-mode will base TAG input on what is already in the
3376 buffer.
3377 The value of this variable is an alist, the car of each entry must be a
3378 keyword as a string, the cdr may be a character that is used to select
3379 that tag through the fast-tag-selection interface.
3380 See the manual for details."
3381 :group 'org-tags
3382 :type '(repeat
3383 (choice
3384 (cons (string :tag "Tag name")
3385 (character :tag "Access char"))
3386 (list :tag "Start radio group"
3387 (const :startgroup)
3388 (option (string :tag "Group description")))
3389 (list :tag "Group tags delimiter"
3390 (const :grouptags))
3391 (list :tag "End radio group"
3392 (const :endgroup)
3393 (option (string :tag "Group description")))
3394 (const :tag "New line" (:newline)))))
3396 (defcustom org-tag-persistent-alist nil
3397 "List of tags that will always appear in all Org-mode files.
3398 This is in addition to any in buffer settings or customizations
3399 of `org-tag-alist'.
3400 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3401 The value of this variable is an alist, the car of each entry must be a
3402 keyword as a string, the cdr may be a character that is used to select
3403 that tag through the fast-tag-selection interface.
3404 See the manual for details.
3405 To disable these tags on a per-file basis, insert anywhere in the file:
3406 #+STARTUP: noptag"
3407 :group 'org-tags
3408 :type '(repeat
3409 (choice
3410 (cons (string :tag "Tag name")
3411 (character :tag "Access char"))
3412 (const :tag "Start radio group" (:startgroup))
3413 (const :tag "Group tags delimiter" (:grouptags))
3414 (const :tag "End radio group" (:endgroup))
3415 (const :tag "New line" (:newline)))))
3417 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3418 "If non-nil, always offer completion for all tags of all agenda files.
3419 Instead of customizing this variable directly, you might want to
3420 set it locally for capture buffers, because there no list of
3421 tags in that file can be created dynamically (there are none).
3423 (add-hook 'org-capture-mode-hook
3424 (lambda ()
3425 (set (make-local-variable
3426 'org-complete-tags-always-offer-all-agenda-tags)
3427 t)))"
3428 :group 'org-tags
3429 :version "24.1"
3430 :type 'boolean)
3432 (defvar org-file-tags nil
3433 "List of tags that can be inherited by all entries in the file.
3434 The tags will be inherited if the variable `org-use-tag-inheritance'
3435 says they should be.
3436 This variable is populated from #+FILETAGS lines.")
3438 (defcustom org-use-fast-tag-selection 'auto
3439 "Non-nil means use fast tag selection scheme.
3440 This is a special interface to select and deselect tags with single keys.
3441 When nil, fast selection is never used.
3442 When the symbol `auto', fast selection is used if and only if selection
3443 characters for tags have been configured, either through the variable
3444 `org-tag-alist' or through a #+TAGS line in the buffer.
3445 When t, fast selection is always used and selection keys are assigned
3446 automatically if necessary."
3447 :group 'org-tags
3448 :type '(choice
3449 (const :tag "Always" t)
3450 (const :tag "Never" nil)
3451 (const :tag "When selection characters are configured" auto)))
3453 (defcustom org-fast-tag-selection-single-key nil
3454 "Non-nil means fast tag selection exits after first change.
3455 When nil, you have to press RET to exit it.
3456 During fast tag selection, you can toggle this flag with `C-c'.
3457 This variable can also have the value `expert'. In this case, the window
3458 displaying the tags menu is not even shown, until you press C-c again."
3459 :group 'org-tags
3460 :type '(choice
3461 (const :tag "No" nil)
3462 (const :tag "Yes" t)
3463 (const :tag "Expert" expert)))
3465 (defvar org-fast-tag-selection-include-todo nil
3466 "Non-nil means fast tags selection interface will also offer TODO states.
3467 This is an undocumented feature, you should not rely on it.")
3469 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3470 "The column to which tags should be indented in a headline.
3471 If this number is positive, it specifies the column. If it is negative,
3472 it means that the tags should be flushright to that column. For example,
3473 -80 works well for a normal 80 character screen.
3474 When 0, place tags directly after headline text, with only one space in
3475 between."
3476 :group 'org-tags
3477 :type 'integer)
3479 (defcustom org-auto-align-tags t
3480 "Non-nil keeps tags aligned when modifying headlines.
3481 Some operations (i.e. demoting) change the length of a headline and
3482 therefore shift the tags around. With this option turned on, after
3483 each such operation the tags are again aligned to `org-tags-column'."
3484 :group 'org-tags
3485 :type 'boolean)
3487 (defcustom org-use-tag-inheritance t
3488 "Non-nil means tags in levels apply also for sublevels.
3489 When nil, only the tags directly given in a specific line apply there.
3490 This may also be a list of tags that should be inherited, or a regexp that
3491 matches tags that should be inherited. Additional control is possible
3492 with the variable `org-tags-exclude-from-inheritance' which gives an
3493 explicit list of tags to be excluded from inheritance, even if the value of
3494 `org-use-tag-inheritance' would select it for inheritance.
3496 If this option is t, a match early-on in a tree can lead to a large
3497 number of matches in the subtree when constructing the agenda or creating
3498 a sparse tree. If you only want to see the first match in a tree during
3499 a search, check out the variable `org-tags-match-list-sublevels'."
3500 :group 'org-tags
3501 :type '(choice
3502 (const :tag "Not" nil)
3503 (const :tag "Always" t)
3504 (repeat :tag "Specific tags" (string :tag "Tag"))
3505 (regexp :tag "Tags matched by regexp")))
3507 (defcustom org-tags-exclude-from-inheritance nil
3508 "List of tags that should never be inherited.
3509 This is a way to exclude a few tags from inheritance. For way to do
3510 the opposite, to actively allow inheritance for selected tags,
3511 see the variable `org-use-tag-inheritance'."
3512 :group 'org-tags
3513 :type '(repeat (string :tag "Tag")))
3515 (defun org-tag-inherit-p (tag)
3516 "Check if TAG is one that should be inherited."
3517 (cond
3518 ((member tag org-tags-exclude-from-inheritance) nil)
3519 ((eq org-use-tag-inheritance t) t)
3520 ((not org-use-tag-inheritance) nil)
3521 ((stringp org-use-tag-inheritance)
3522 (string-match org-use-tag-inheritance tag))
3523 ((listp org-use-tag-inheritance)
3524 (member tag org-use-tag-inheritance))
3525 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3527 (defcustom org-tags-match-list-sublevels t
3528 "Non-nil means list also sublevels of headlines matching a search.
3529 This variable applies to tags/property searches, and also to stuck
3530 projects because this search is based on a tags match as well.
3532 When set to the symbol `indented', sublevels are indented with
3533 leading dots.
3535 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3536 the sublevels of a headline matching a tag search often also match
3537 the same search. Listing all of them can create very long lists.
3538 Setting this variable to nil causes subtrees of a match to be skipped.
3540 This variable is semi-obsolete and probably should always be true. It
3541 is better to limit inheritance to certain tags using the variables
3542 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3543 :group 'org-tags
3544 :type '(choice
3545 (const :tag "No, don't list them" nil)
3546 (const :tag "Yes, do list them" t)
3547 (const :tag "List them, indented with leading dots" indented)))
3549 (defcustom org-tags-sort-function nil
3550 "When set, tags are sorted using this function as a comparator."
3551 :group 'org-tags
3552 :type '(choice
3553 (const :tag "No sorting" nil)
3554 (const :tag "Alphabetical" string<)
3555 (const :tag "Reverse alphabetical" string>)
3556 (function :tag "Custom function" nil)))
3558 (defvar org-tags-history nil
3559 "History of minibuffer reads for tags.")
3560 (defvar org-last-tags-completion-table nil
3561 "The last used completion table for tags.")
3562 (defvar org-after-tags-change-hook nil
3563 "Hook that is run after the tags in a line have changed.")
3565 (defgroup org-properties nil
3566 "Options concerning properties in Org-mode."
3567 :tag "Org Properties"
3568 :group 'org)
3570 (defcustom org-property-format "%-10s %s"
3571 "How property key/value pairs should be formatted by `indent-line'.
3572 When `indent-line' hits a property definition, it will format the line
3573 according to this format, mainly to make sure that the values are
3574 lined-up with respect to each other."
3575 :group 'org-properties
3576 :type 'string)
3578 (defcustom org-properties-postprocess-alist nil
3579 "Alist of properties and functions to adjust inserted values.
3580 Elements of this alist must be of the form
3582 ([string] [function])
3584 where [string] must be a property name and [function] must be a
3585 lambda expression: this lambda expression must take one argument,
3586 the value to adjust, and return the new value as a string.
3588 For example, this element will allow the property \"Remaining\"
3589 to be updated wrt the relation between the \"Effort\" property
3590 and the clock summary:
3592 ((\"Remaining\" (lambda(value)
3593 (let ((clocksum (org-clock-sum-current-item))
3594 (effort (org-duration-string-to-minutes
3595 (org-entry-get (point) \"Effort\"))))
3596 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3597 :group 'org-properties
3598 :version "24.1"
3599 :type '(alist :key-type (string :tag "Property")
3600 :value-type (function :tag "Function")))
3602 (defcustom org-use-property-inheritance nil
3603 "Non-nil means properties apply also for sublevels.
3605 This setting is chiefly used during property searches. Turning it on can
3606 cause significant overhead when doing a search, which is why it is not
3607 on by default.
3609 When nil, only the properties directly given in the current entry count.
3610 When t, every property is inherited. The value may also be a list of
3611 properties that should have inheritance, or a regular expression matching
3612 properties that should be inherited.
3614 However, note that some special properties use inheritance under special
3615 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3616 and the properties ending in \"_ALL\" when they are used as descriptor
3617 for valid values of a property.
3619 Note for programmers:
3620 When querying an entry with `org-entry-get', you can control if inheritance
3621 should be used. By default, `org-entry-get' looks only at the local
3622 properties. You can request inheritance by setting the inherit argument
3623 to t (to force inheritance) or to `selective' (to respect the setting
3624 in this variable)."
3625 :group 'org-properties
3626 :type '(choice
3627 (const :tag "Not" nil)
3628 (const :tag "Always" t)
3629 (repeat :tag "Specific properties" (string :tag "Property"))
3630 (regexp :tag "Properties matched by regexp")))
3632 (defun org-property-inherit-p (property)
3633 "Check if PROPERTY is one that should be inherited."
3634 (cond
3635 ((eq org-use-property-inheritance t) t)
3636 ((not org-use-property-inheritance) nil)
3637 ((stringp org-use-property-inheritance)
3638 (string-match org-use-property-inheritance property))
3639 ((listp org-use-property-inheritance)
3640 (member property org-use-property-inheritance))
3641 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3643 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3644 "The default column format, if no other format has been defined.
3645 This variable can be set on the per-file basis by inserting a line
3647 #+COLUMNS: %25ITEM ....."
3648 :group 'org-properties
3649 :type 'string)
3651 (defcustom org-columns-ellipses ".."
3652 "The ellipses to be used when a field in column view is truncated.
3653 When this is the empty string, as many characters as possible are shown,
3654 but then there will be no visual indication that the field has been truncated.
3655 When this is a string of length N, the last N characters of a truncated
3656 field are replaced by this string. If the column is narrower than the
3657 ellipses string, only part of the ellipses string will be shown."
3658 :group 'org-properties
3659 :type 'string)
3661 (defcustom org-columns-modify-value-for-display-function nil
3662 "Function that modifies values for display in column view.
3663 For example, it can be used to cut out a certain part from a time stamp.
3664 The function must take 2 arguments:
3666 column-title The title of the column (*not* the property name)
3667 value The value that should be modified.
3669 The function should return the value that should be displayed,
3670 or nil if the normal value should be used."
3671 :group 'org-properties
3672 :type '(choice (const nil) (function)))
3674 (defconst org-global-properties-fixed
3675 '(("VISIBILITY_ALL" . "folded children content all")
3676 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3677 "List of property/value pairs that can be inherited by any entry.
3679 These are fixed values, for the preset properties. The user variable
3680 that can be used to add to this list is `org-global-properties'.
3682 The entries in this list are cons cells where the car is a property
3683 name and cdr is a string with the value. If the value represents
3684 multiple items like an \"_ALL\" property, separate the items by
3685 spaces.")
3687 (defcustom org-global-properties nil
3688 "List of property/value pairs that can be inherited by any entry.
3690 This list will be combined with the constant `org-global-properties-fixed'.
3692 The entries in this list are cons cells where the car is a property
3693 name and cdr is a string with the value.
3695 You can set buffer-local values for the same purpose in the variable
3696 `org-file-properties' this by adding lines like
3698 #+PROPERTY: NAME VALUE"
3699 :group 'org-properties
3700 :type '(repeat
3701 (cons (string :tag "Property")
3702 (string :tag "Value"))))
3704 (defvar org-file-properties nil
3705 "List of property/value pairs that can be inherited by any entry.
3706 Valid for the current buffer.
3707 This variable is populated from #+PROPERTY lines.")
3708 (make-variable-buffer-local 'org-file-properties)
3710 (defgroup org-agenda nil
3711 "Options concerning agenda views in Org-mode."
3712 :tag "Org Agenda"
3713 :group 'org)
3715 (defvar org-category nil
3716 "Variable used by org files to set a category for agenda display.
3717 Such files should use a file variable to set it, for example
3719 # -*- mode: org; org-category: \"ELisp\"
3721 or contain a special line
3723 #+CATEGORY: ELisp
3725 If the file does not specify a category, then file's base name
3726 is used instead.")
3727 (make-variable-buffer-local 'org-category)
3728 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3730 (defcustom org-agenda-files nil
3731 "The files to be used for agenda display.
3732 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3733 \\[org-remove-file]. You can also use customize to edit the list.
3735 If an entry is a directory, all files in that directory that are matched by
3736 `org-agenda-file-regexp' will be part of the file list.
3738 If the value of the variable is not a list but a single file name, then
3739 the list of agenda files is actually stored and maintained in that file, one
3740 agenda file per line. In this file paths can be given relative to
3741 `org-directory'. Tilde expansion and environment variable substitution
3742 are also made."
3743 :group 'org-agenda
3744 :type '(choice
3745 (repeat :tag "List of files and directories" file)
3746 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3748 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3749 "Regular expression to match files for `org-agenda-files'.
3750 If any element in the list in that variable contains a directory instead
3751 of a normal file, all files in that directory that are matched by this
3752 regular expression will be included."
3753 :group 'org-agenda
3754 :type 'regexp)
3756 (defcustom org-agenda-text-search-extra-files nil
3757 "List of extra files to be searched by text search commands.
3758 These files will be searched in addition to the agenda files by the
3759 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3760 Note that these files will only be searched for text search commands,
3761 not for the other agenda views like todo lists, tag searches or the weekly
3762 agenda. This variable is intended to list notes and possibly archive files
3763 that should also be searched by these two commands.
3764 In fact, if the first element in the list is the symbol `agenda-archives',
3765 then all archive files of all agenda files will be added to the search
3766 scope."
3767 :group 'org-agenda
3768 :type '(set :greedy t
3769 (const :tag "Agenda Archives" agenda-archives)
3770 (repeat :inline t (file))))
3772 (org-defvaralias 'org-agenda-multi-occur-extra-files
3773 'org-agenda-text-search-extra-files)
3775 (defcustom org-agenda-skip-unavailable-files nil
3776 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3777 A nil value means to remove them, after a query, from the list."
3778 :group 'org-agenda
3779 :type 'boolean)
3781 (defcustom org-calendar-to-agenda-key [?c]
3782 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3783 The command `org-calendar-goto-agenda' will be bound to this key. The
3784 default is the character `c' because then `c' can be used to switch back and
3785 forth between agenda and calendar."
3786 :group 'org-agenda
3787 :type 'sexp)
3789 (defcustom org-calendar-insert-diary-entry-key [?i]
3790 "The key to be installed in `calendar-mode-map' for adding diary entries.
3791 This option is irrelevant until `org-agenda-diary-file' has been configured
3792 to point to an Org-mode file. When that is the case, the command
3793 `org-agenda-diary-entry' will be bound to the key given here, by default
3794 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3795 if you want to continue doing this, you need to change this to a different
3796 key."
3797 :group 'org-agenda
3798 :type 'sexp)
3800 (defcustom org-agenda-diary-file 'diary-file
3801 "File to which to add new entries with the `i' key in agenda and calendar.
3802 When this is the symbol `diary-file', the functionality in the Emacs
3803 calendar will be used to add entries to the `diary-file'. But when this
3804 points to a file, `org-agenda-diary-entry' will be used instead."
3805 :group 'org-agenda
3806 :type '(choice
3807 (const :tag "The standard Emacs diary file" diary-file)
3808 (file :tag "Special Org file diary entries")))
3810 (eval-after-load "calendar"
3811 '(progn
3812 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3813 'org-calendar-goto-agenda)
3814 (add-hook 'calendar-mode-hook
3815 (lambda ()
3816 (unless (eq org-agenda-diary-file 'diary-file)
3817 (define-key calendar-mode-map
3818 org-calendar-insert-diary-entry-key
3819 'org-agenda-diary-entry))))))
3821 (defgroup org-latex nil
3822 "Options for embedding LaTeX code into Org-mode."
3823 :tag "Org LaTeX"
3824 :group 'org)
3826 (defcustom org-format-latex-options
3827 '(:foreground default :background default :scale 1.0
3828 :html-foreground "Black" :html-background "Transparent"
3829 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3830 "Options for creating images from LaTeX fragments.
3831 This is a property list with the following properties:
3832 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3833 `default' means use the foreground of the default face.
3834 `auto' means use the foreground from the text face.
3835 :background the background color, or \"Transparent\".
3836 `default' means use the background of the default face.
3837 `auto' means use the background from the text face.
3838 :scale a scaling factor for the size of the images, to get more pixels
3839 :html-foreground, :html-background, :html-scale
3840 the same numbers for HTML export.
3841 :matchers a list indicating which matchers should be used to
3842 find LaTeX fragments. Valid members of this list are:
3843 \"begin\" find environments
3844 \"$1\" find single characters surrounded by $.$
3845 \"$\" find math expressions surrounded by $...$
3846 \"$$\" find math expressions surrounded by $$....$$
3847 \"\\(\" find math expressions surrounded by \\(...\\)
3848 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3849 :group 'org-latex
3850 :type 'plist)
3852 (defcustom org-format-latex-signal-error t
3853 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3854 When nil, just push out a message."
3855 :group 'org-latex
3856 :version "24.1"
3857 :type 'boolean)
3859 (defcustom org-latex-to-mathml-jar-file nil
3860 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3861 Use this to specify additional executable file say a jar file.
3863 When using MathToWeb as the converter, specify the full-path to
3864 your mathtoweb.jar file."
3865 :group 'org-latex
3866 :version "24.1"
3867 :type '(choice
3868 (const :tag "None" nil)
3869 (file :tag "JAR file" :must-match t)))
3871 (defcustom org-latex-to-mathml-convert-command nil
3872 "Command to convert LaTeX fragments to MathML.
3873 Replace format-specifiers in the command as noted below and use
3874 `shell-command' to convert LaTeX to MathML.
3875 %j: Executable file in fully expanded form as specified by
3876 `org-latex-to-mathml-jar-file'.
3877 %I: Input LaTeX file in fully expanded form
3878 %o: Output MathML file
3879 This command is used by `org-create-math-formula'.
3881 When using MathToWeb as the converter, set this to
3882 \"java -jar %j -unicode -force -df %o %I\"."
3883 :group 'org-latex
3884 :version "24.1"
3885 :type '(choice
3886 (const :tag "None" nil)
3887 (string :tag "\nShell command")))
3889 (defcustom org-latex-create-formula-image-program 'dvipng
3890 "Program to convert LaTeX fragments with.
3892 dvipng Process the LaTeX fragments to dvi file, then convert
3893 dvi files to png files using dvipng.
3894 This will also include processing of non-math environments.
3895 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3896 to convert pdf files to png files"
3897 :group 'org-latex
3898 :version "24.1"
3899 :type '(choice
3900 (const :tag "dvipng" dvipng)
3901 (const :tag "imagemagick" imagemagick)))
3903 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3904 "Path to store latex preview images.
3905 A relative path here creates many directories relative to the
3906 processed org files paths. An absolute path puts all preview
3907 images at the same place."
3908 :group 'org-latex
3909 :version "24.3"
3910 :type 'string)
3912 (defun org-format-latex-mathml-available-p ()
3913 "Return t if `org-latex-to-mathml-convert-command' is usable."
3914 (save-match-data
3915 (when (and (boundp 'org-latex-to-mathml-convert-command)
3916 org-latex-to-mathml-convert-command)
3917 (let ((executable (car (split-string
3918 org-latex-to-mathml-convert-command))))
3919 (when (executable-find executable)
3920 (if (string-match
3921 "%j" org-latex-to-mathml-convert-command)
3922 (file-readable-p org-latex-to-mathml-jar-file)
3923 t))))))
3925 (defcustom org-format-latex-header "\\documentclass{article}
3926 \\usepackage[usenames]{color}
3927 \[PACKAGES]
3928 \[DEFAULT-PACKAGES]
3929 \\pagestyle{empty} % do not remove
3930 % The settings below are copied from fullpage.sty
3931 \\setlength{\\textwidth}{\\paperwidth}
3932 \\addtolength{\\textwidth}{-3cm}
3933 \\setlength{\\oddsidemargin}{1.5cm}
3934 \\addtolength{\\oddsidemargin}{-2.54cm}
3935 \\setlength{\\evensidemargin}{\\oddsidemargin}
3936 \\setlength{\\textheight}{\\paperheight}
3937 \\addtolength{\\textheight}{-\\headheight}
3938 \\addtolength{\\textheight}{-\\headsep}
3939 \\addtolength{\\textheight}{-\\footskip}
3940 \\addtolength{\\textheight}{-3cm}
3941 \\setlength{\\topmargin}{1.5cm}
3942 \\addtolength{\\topmargin}{-2.54cm}"
3943 "The document header used for processing LaTeX fragments.
3944 It is imperative that this header make sure that no page number
3945 appears on the page. The package defined in the variables
3946 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3947 will either replace the placeholder \"[PACKAGES]\" in this
3948 header, or they will be appended."
3949 :group 'org-latex
3950 :type 'string)
3952 (defun org-set-packages-alist (var val)
3953 "Set the packages alist and make sure it has 3 elements per entry."
3954 (set var (mapcar (lambda (x)
3955 (if (and (consp x) (= (length x) 2))
3956 (list (car x) (nth 1 x) t)
3958 val)))
3960 (defun org-get-packages-alist (var)
3961 "Get the packages alist and make sure it has 3 elements per entry."
3962 (mapcar (lambda (x)
3963 (if (and (consp x) (= (length x) 2))
3964 (list (car x) (nth 1 x) t)
3966 (default-value var)))
3968 (defcustom org-latex-default-packages-alist
3969 '(("AUTO" "inputenc" t)
3970 ("T1" "fontenc" t)
3971 ("" "fixltx2e" nil)
3972 ("" "graphicx" t)
3973 ("" "longtable" nil)
3974 ("" "float" nil)
3975 ("" "wrapfig" nil)
3976 ("" "rotating" nil)
3977 ("normalem" "ulem" t)
3978 ("" "amsmath" t)
3979 ("" "textcomp" t)
3980 ("" "marvosym" t)
3981 ("" "wasysym" t)
3982 ("" "amssymb" t)
3983 ("" "hyperref" nil)
3984 "\\tolerance=1000")
3985 "Alist of default packages to be inserted in the header.
3987 Change this only if one of the packages here causes an
3988 incompatibility with another package you are using.
3990 The packages in this list are needed by one part or another of
3991 Org mode to function properly:
3993 - inputenc, fontenc: for basic font and character selection
3994 - fixltx2e: Important patches of LaTeX itself
3995 - graphicx: for including images
3996 - longtable: For multipage tables
3997 - float, wrapfig: for figure placement
3998 - rotating: for sideways figures and tables
3999 - ulem: for underline and strike-through
4000 - amsmath: for subscript and superscript and math environments
4001 - textcomp, marvosymb, wasysym, amssymb: for various symbols used
4002 for interpreting the entities in `org-entities'. You can skip
4003 some of these packages if you don't use any of their symbols.
4004 - hyperref: for cross references
4006 Therefore you should not modify this variable unless you know
4007 what you are doing. The one reason to change it anyway is that
4008 you might be loading some other package that conflicts with one
4009 of the default packages. Each cell is of the format
4010 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
4011 the package also needs to be included when compiling LaTeX
4012 snippets into images for inclusion into non-LaTeX output."
4013 :group 'org-latex
4014 :group 'org-export-latex
4015 :set 'org-set-packages-alist
4016 :get 'org-get-packages-alist
4017 :version "24.1"
4018 :type '(repeat
4019 (choice
4020 (list :tag "options/package pair"
4021 (string :tag "options")
4022 (string :tag "package")
4023 (boolean :tag "Snippet"))
4024 (string :tag "A line of LaTeX"))))
4026 (defcustom org-latex-packages-alist nil
4027 "Alist of packages to be inserted in every LaTeX header.
4029 These will be inserted after `org-latex-default-packages-alist'.
4030 Each cell is of the format:
4032 \(\"options\" \"package\" snippet-flag)
4034 SNIPPET-FLAG, when t, indicates that this package is also needed
4035 when turning LaTeX snippets into images for inclusion into
4036 non-LaTeX output.
4038 Make sure that you only list packages here which:
4040 - you want in every file
4041 - do not conflict with the setup in `org-format-latex-header'.
4042 - do not conflict with the default packages in
4043 `org-latex-default-packages-alist'."
4044 :group 'org-latex
4045 :group 'org-export-latex
4046 :set 'org-set-packages-alist
4047 :get 'org-get-packages-alist
4048 :type '(repeat
4049 (choice
4050 (list :tag "options/package pair"
4051 (string :tag "options")
4052 (string :tag "package")
4053 (boolean :tag "Snippet"))
4054 (string :tag "A line of LaTeX"))))
4056 (defgroup org-appearance nil
4057 "Settings for Org-mode appearance."
4058 :tag "Org Appearance"
4059 :group 'org)
4061 (defcustom org-level-color-stars-only nil
4062 "Non-nil means fontify only the stars in each headline.
4063 When nil, the entire headline is fontified.
4064 Changing it requires restart of `font-lock-mode' to become effective
4065 also in regions already fontified."
4066 :group 'org-appearance
4067 :type 'boolean)
4069 (defcustom org-hide-leading-stars nil
4070 "Non-nil means hide the first N-1 stars in a headline.
4071 This works by using the face `org-hide' for these stars. This
4072 face is white for a light background, and black for a dark
4073 background. You may have to customize the face `org-hide' to
4074 make this work.
4075 Changing it requires restart of `font-lock-mode' to become effective
4076 also in regions already fontified.
4077 You may also set this on a per-file basis by adding one of the following
4078 lines to the buffer:
4080 #+STARTUP: hidestars
4081 #+STARTUP: showstars"
4082 :group 'org-appearance
4083 :type 'boolean)
4085 (defcustom org-hidden-keywords nil
4086 "List of symbols corresponding to keywords to be hidden the org buffer.
4087 For example, a value '(title) for this list will make the document's title
4088 appear in the buffer without the initial #+TITLE: keyword."
4089 :group 'org-appearance
4090 :version "24.1"
4091 :type '(set (const :tag "#+AUTHOR" author)
4092 (const :tag "#+DATE" date)
4093 (const :tag "#+EMAIL" email)
4094 (const :tag "#+TITLE" title)))
4096 (defcustom org-custom-properties nil
4097 "List of properties (as strings) with a special meaning.
4098 The default use of these custom properties is to let the user
4099 hide them with `org-toggle-custom-properties-visibility'."
4100 :group 'org-properties
4101 :group 'org-appearance
4102 :version "24.3"
4103 :type '(repeat (string :tag "Property Name")))
4105 (defcustom org-fontify-done-headline nil
4106 "Non-nil means change the face of a headline if it is marked DONE.
4107 Normally, only the TODO/DONE keyword indicates the state of a headline.
4108 When this is non-nil, the headline after the keyword is set to the
4109 `org-headline-done' as an additional indication."
4110 :group 'org-appearance
4111 :type 'boolean)
4113 (defcustom org-fontify-emphasized-text t
4114 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4115 Changing this variable requires a restart of Emacs to take effect."
4116 :group 'org-appearance
4117 :type 'boolean)
4119 (defcustom org-fontify-whole-heading-line nil
4120 "Non-nil means fontify the whole line for headings.
4121 This is useful when setting a background color for the
4122 org-level-* faces."
4123 :group 'org-appearance
4124 :type 'boolean)
4126 (defcustom org-highlight-latex-and-related nil
4127 "Non-nil means highlight LaTeX related syntax in the buffer.
4128 When non nil, the value should be a list containing any of the
4129 following symbols:
4130 `latex' Highlight LaTeX snippets and environments.
4131 `script' Highlight subscript and superscript.
4132 `entities' Highlight entities."
4133 :group 'org-appearance
4134 :version "24.4"
4135 :package-version '(Org . "8.0")
4136 :type '(choice
4137 (const :tag "No highlighting" nil)
4138 (set :greedy t :tag "Highlight"
4139 (const :tag "LaTeX snippets and environments" latex)
4140 (const :tag "Subscript and superscript" script)
4141 (const :tag "Entities" entities))))
4143 (defcustom org-hide-emphasis-markers nil
4144 "Non-nil mean font-lock should hide the emphasis marker characters."
4145 :group 'org-appearance
4146 :type 'boolean)
4148 (defcustom org-pretty-entities nil
4149 "Non-nil means show entities as UTF8 characters.
4150 When nil, the \\name form remains in the buffer."
4151 :group 'org-appearance
4152 :version "24.1"
4153 :type 'boolean)
4155 (defcustom org-pretty-entities-include-sub-superscripts t
4156 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4157 :group 'org-appearance
4158 :version "24.1"
4159 :type 'boolean)
4161 (defvar org-emph-re nil
4162 "Regular expression for matching emphasis.
4163 After a match, the match groups contain these elements:
4164 0 The match of the full regular expression, including the characters
4165 before and after the proper match
4166 1 The character before the proper match, or empty at beginning of line
4167 2 The proper match, including the leading and trailing markers
4168 3 The leading marker like * or /, indicating the type of highlighting
4169 4 The text between the emphasis markers, not including the markers
4170 5 The character after the match, empty at the end of a line")
4171 (defvar org-verbatim-re nil
4172 "Regular expression for matching verbatim text.")
4173 (defvar org-emphasis-regexp-components) ; defined just below
4174 (defvar org-emphasis-alist) ; defined just below
4175 (defun org-set-emph-re (var val)
4176 "Set variable and compute the emphasis regular expression."
4177 (set var val)
4178 (when (and (boundp 'org-emphasis-alist)
4179 (boundp 'org-emphasis-regexp-components)
4180 org-emphasis-alist org-emphasis-regexp-components)
4181 (let* ((e org-emphasis-regexp-components)
4182 (pre (car e))
4183 (post (nth 1 e))
4184 (border (nth 2 e))
4185 (body (nth 3 e))
4186 (nl (nth 4 e))
4187 (body1 (concat body "*?"))
4188 (markers (mapconcat 'car org-emphasis-alist ""))
4189 (vmarkers (mapconcat
4190 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4191 org-emphasis-alist "")))
4192 ;; make sure special characters appear at the right position in the class
4193 (if (string-match "\\^" markers)
4194 (setq markers (concat (replace-match "" t t markers) "^")))
4195 (if (string-match "-" markers)
4196 (setq markers (concat (replace-match "" t t markers) "-")))
4197 (if (string-match "\\^" vmarkers)
4198 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4199 (if (string-match "-" vmarkers)
4200 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4201 (if (> nl 0)
4202 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4203 (int-to-string nl) "\\}")))
4204 ;; Make the regexp
4205 (setq org-emph-re
4206 (concat "\\([" pre "]\\|^\\)"
4207 "\\("
4208 "\\([" markers "]\\)"
4209 "\\("
4210 "[^" border "]\\|"
4211 "[^" border "]"
4212 body1
4213 "[^" border "]"
4214 "\\)"
4215 "\\3\\)"
4216 "\\([" post "]\\|$\\)"))
4217 (setq org-verbatim-re
4218 (concat "\\([" pre "]\\|^\\)"
4219 "\\("
4220 "\\([" vmarkers "]\\)"
4221 "\\("
4222 "[^" border "]\\|"
4223 "[^" border "]"
4224 body1
4225 "[^" border "]"
4226 "\\)"
4227 "\\3\\)"
4228 "\\([" post "]\\|$\\)")))))
4230 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4231 ;; set this option proved cumbersome. See this message/thread:
4232 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4233 (defvar org-emphasis-regexp-components
4234 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4235 "Components used to build the regular expression for emphasis.
4236 This is a list with five entries. Terminology: In an emphasis string
4237 like \" *strong word* \", we call the initial space PREMATCH, the final
4238 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4239 and \"trong wor\" is the body. The different components in this variable
4240 specify what is allowed/forbidden in each part:
4242 pre Chars allowed as prematch. Beginning of line will be allowed too.
4243 post Chars allowed as postmatch. End of line will be allowed too.
4244 border The chars *forbidden* as border characters.
4245 body-regexp A regexp like \".\" to match a body character. Don't use
4246 non-shy groups here, and don't allow newline here.
4247 newline The maximum number of newlines allowed in an emphasis exp.
4249 You need to reload Org or to restart Emacs after customizing this.")
4251 (defcustom org-emphasis-alist
4252 `(("*" bold)
4253 ("/" italic)
4254 ("_" underline)
4255 ("=" org-code verbatim)
4256 ("~" org-verbatim verbatim)
4257 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4258 "Alist of characters and faces to emphasize text.
4259 Text starting and ending with a special character will be emphasized,
4260 for example *bold*, _underlined_ and /italic/. This variable sets the
4261 marker characters and the face to be used by font-lock for highlighting
4262 in Org-mode Emacs buffers.
4264 You need to reload Org or to restart Emacs after customizing this."
4265 :group 'org-appearance
4266 :set 'org-set-emph-re
4267 :version "24.4"
4268 :package-version '(Org . "8.0")
4269 :type '(repeat
4270 (list
4271 (string :tag "Marker character")
4272 (choice
4273 (face :tag "Font-lock-face")
4274 (plist :tag "Face property list"))
4275 (option (const verbatim)))))
4277 (defvar org-protecting-blocks
4278 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4279 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4280 This is needed for font-lock setup.")
4282 ;;; Miscellaneous options
4284 (defgroup org-completion nil
4285 "Completion in Org-mode."
4286 :tag "Org Completion"
4287 :group 'org)
4289 (defcustom org-completion-use-ido nil
4290 "Non-nil means use ido completion wherever possible.
4291 Note that `ido-mode' must be active for this variable to be relevant.
4292 If you decide to turn this variable on, you might well want to turn off
4293 `org-outline-path-complete-in-steps'.
4294 See also `org-completion-use-iswitchb'."
4295 :group 'org-completion
4296 :type 'boolean)
4298 (defcustom org-completion-use-iswitchb nil
4299 "Non-nil means use iswitchb completion wherever possible.
4300 Note that `iswitchb-mode' must be active for this variable to be relevant.
4301 If you decide to turn this variable on, you might well want to turn off
4302 `org-outline-path-complete-in-steps'.
4303 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4304 :group 'org-completion
4305 :type 'boolean)
4307 (defcustom org-completion-fallback-command 'hippie-expand
4308 "The expansion command called by \\[pcomplete] in normal context.
4309 Normal means, no org-mode-specific context."
4310 :group 'org-completion
4311 :type 'function)
4313 ;;; Functions and variables from their packages
4314 ;; Declared here to avoid compiler warnings
4316 ;; XEmacs only
4317 (defvar outline-mode-menu-heading)
4318 (defvar outline-mode-menu-show)
4319 (defvar outline-mode-menu-hide)
4320 (defvar zmacs-regions) ; XEmacs regions
4322 ;; Emacs only
4323 (defvar mark-active)
4325 ;; Various packages
4326 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4327 (declare-function calendar-forward-day "cal-move" (arg))
4328 (declare-function calendar-goto-date "cal-move" (date))
4329 (declare-function calendar-goto-today "cal-move" ())
4330 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4331 (defvar calc-embedded-close-formula)
4332 (defvar calc-embedded-open-formula)
4333 (declare-function cdlatex-tab "ext:cdlatex" ())
4334 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4335 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4336 (defvar font-lock-unfontify-region-function)
4337 (declare-function iswitchb-read-buffer "iswitchb"
4338 (prompt &optional default require-match start matches-set))
4339 (defvar iswitchb-temp-buflist)
4340 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4341 (defvar org-agenda-tags-todo-honor-ignore-options)
4342 (declare-function org-agenda-skip "org-agenda" ())
4343 (declare-function
4344 org-agenda-format-item "org-agenda"
4345 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4346 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4347 (declare-function org-agenda-change-all-lines "org-agenda"
4348 (newhead hdmarker &optional fixface just-this))
4349 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4350 (declare-function org-agenda-maybe-redo "org-agenda" ())
4351 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4352 (beg end))
4353 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4354 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4355 "org-agenda" (&optional end))
4356 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4357 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4358 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4359 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4360 (declare-function org-indent-mode "org-indent" (&optional arg))
4361 (declare-function parse-time-string "parse-time" (string))
4362 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4363 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4364 (defvar remember-data-file)
4365 (defvar texmathp-why)
4366 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4367 (declare-function table--at-cell-p "table" (position &optional object at-column))
4369 ;;;###autoload
4370 (defun turn-on-orgtbl ()
4371 "Unconditionally turn on `orgtbl-mode'."
4372 (require 'org-table)
4373 (orgtbl-mode 1))
4375 (defun org-at-table-p (&optional table-type)
4376 "Return t if the cursor is inside an org-type table.
4377 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4378 (if org-enable-table-editor
4379 (save-excursion
4380 (beginning-of-line 1)
4381 (looking-at (if table-type org-table-any-line-regexp
4382 org-table-line-regexp)))
4383 nil))
4384 (defsubst org-table-p () (org-at-table-p))
4386 (defun org-at-table.el-p ()
4387 "Return t if and only if we are at a table.el table."
4388 (and (org-at-table-p 'any)
4389 (save-excursion
4390 (goto-char (org-table-begin 'any))
4391 (looking-at org-table1-hline-regexp))))
4393 (defun org-table-recognize-table.el ()
4394 "If there is a table.el table nearby, recognize it and move into it."
4395 (if org-table-tab-recognizes-table.el
4396 (if (org-at-table.el-p)
4397 (progn
4398 (beginning-of-line 1)
4399 (if (looking-at org-table-dataline-regexp)
4401 (if (looking-at org-table1-hline-regexp)
4402 (progn
4403 (beginning-of-line 2)
4404 (if (looking-at org-table-any-border-regexp)
4405 (beginning-of-line -1)))))
4406 (if (re-search-forward "|" (org-table-end t) t)
4407 (progn
4408 (require 'table)
4409 (if (table--at-cell-p (point))
4411 (message "recognizing table.el table...")
4412 (table-recognize-table)
4413 (message "recognizing table.el table...done")))
4414 (error "This should not happen"))
4416 nil)
4417 nil))
4419 (defun org-at-table-hline-p ()
4420 "Return t if the cursor is inside a hline in a table."
4421 (if org-enable-table-editor
4422 (save-excursion
4423 (beginning-of-line 1)
4424 (looking-at org-table-hline-regexp))
4425 nil))
4427 (defun org-table-map-tables (function &optional quietly)
4428 "Apply FUNCTION to the start of all tables in the buffer."
4429 (save-excursion
4430 (save-restriction
4431 (widen)
4432 (goto-char (point-min))
4433 (while (re-search-forward org-table-any-line-regexp nil t)
4434 (unless quietly
4435 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4436 (beginning-of-line 1)
4437 (when (and (looking-at org-table-line-regexp)
4438 ;; Exclude tables in src/example/verbatim/clocktable blocks
4439 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4440 (save-excursion (funcall function))
4441 (or (looking-at org-table-line-regexp)
4442 (forward-char 1)))
4443 (re-search-forward org-table-any-border-regexp nil 1))))
4444 (unless quietly (message "Mapping tables: done")))
4446 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4447 (declare-function org-clock-update-mode-line "org-clock" ())
4448 (declare-function org-resolve-clocks "org-clock"
4449 (&optional also-non-dangling-p prompt last-valid))
4451 (defun org-at-TBLFM-p (&optional pos)
4452 "Return t when point (or POS) is in #+TBLFM line."
4453 (save-excursion
4454 (let ((pos pos)))
4455 (goto-char (or pos (point)))
4456 (beginning-of-line 1)
4457 (looking-at org-TBLFM-regexp)))
4459 (defvar org-clock-start-time)
4460 (defvar org-clock-marker (make-marker)
4461 "Marker recording the last clock-in.")
4462 (defvar org-clock-hd-marker (make-marker)
4463 "Marker recording the last clock-in, but the headline position.")
4464 (defvar org-clock-heading ""
4465 "The heading of the current clock entry.")
4466 (defun org-clock-is-active ()
4467 "Return the buffer where the clock is currently running.
4468 Return nil if no clock is running."
4469 (marker-buffer org-clock-marker))
4471 (defun org-check-running-clock ()
4472 "Check if the current buffer contains the running clock.
4473 If yes, offer to stop it and to save the buffer with the changes."
4474 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4475 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4476 (buffer-name))))
4477 (org-clock-out)
4478 (when (y-or-n-p "Save changed buffer?")
4479 (save-buffer))))
4481 (defun org-clocktable-try-shift (dir n)
4482 "Check if this line starts a clock table, if yes, shift the time block."
4483 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4484 (org-clocktable-shift dir n)))
4486 ;;;###autoload
4487 (defun org-clock-persistence-insinuate ()
4488 "Set up hooks for clock persistence."
4489 (require 'org-clock)
4490 (add-hook 'org-mode-hook 'org-clock-load)
4491 (add-hook 'kill-emacs-hook 'org-clock-save))
4493 ;; Define the variable already here, to make sure we have it.
4494 (defvar org-indent-mode nil
4495 "Non-nil if Org-Indent mode is enabled.
4496 Use the command `org-indent-mode' to change this variable.")
4498 ;; Autoload archiving code
4499 ;; The stuff that is needed for cycling and tags has to be defined here.
4501 (defgroup org-archive nil
4502 "Options concerning archiving in Org-mode."
4503 :tag "Org Archive"
4504 :group 'org-structure)
4506 (defcustom org-archive-location "%s_archive::"
4507 "The location where subtrees should be archived.
4509 The value of this variable is a string, consisting of two parts,
4510 separated by a double-colon. The first part is a filename and
4511 the second part is a headline.
4513 When the filename is omitted, archiving happens in the same file.
4514 %s in the filename will be replaced by the current file
4515 name (without the directory part). Archiving to a different file
4516 is useful to keep archived entries from contributing to the
4517 Org-mode Agenda.
4519 The archived entries will be filed as subtrees of the specified
4520 headline. When the headline is omitted, the subtrees are simply
4521 filed away at the end of the file, as top-level entries. Also in
4522 the heading you can use %s to represent the file name, this can be
4523 useful when using the same archive for a number of different files.
4525 Here are a few examples:
4526 \"%s_archive::\"
4527 If the current file is Projects.org, archive in file
4528 Projects.org_archive, as top-level trees. This is the default.
4530 \"::* Archived Tasks\"
4531 Archive in the current file, under the top-level headline
4532 \"* Archived Tasks\".
4534 \"~/org/archive.org::\"
4535 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4537 \"~/org/archive.org::* From %s\"
4538 Archive in file ~/org/archive.org (absolute path), under headlines
4539 \"From FILENAME\" where file name is the current file name.
4541 \"~/org/datetree.org::datetree/* Finished Tasks\"
4542 The \"datetree/\" string is special, signifying to archive
4543 items to the datetree. Items are placed in either the CLOSED
4544 date of the item, or the current date if there is no CLOSED date.
4545 The heading will be a subentry to the current date. There doesn't
4546 need to be a heading, but there always needs to be a slash after
4547 datetree. For example, to store archived items directly in the
4548 datetree, use \"~/org/datetree.org::datetree/\".
4550 \"basement::** Finished Tasks\"
4551 Archive in file ./basement (relative path), as level 3 trees
4552 below the level 2 heading \"** Finished Tasks\".
4554 You may set this option on a per-file basis by adding to the buffer a
4555 line like
4557 #+ARCHIVE: basement::** Finished Tasks
4559 You may also define it locally for a subtree by setting an ARCHIVE property
4560 in the entry. If such a property is found in an entry, or anywhere up
4561 the hierarchy, it will be used."
4562 :group 'org-archive
4563 :type 'string)
4565 (defcustom org-agenda-skip-archived-trees t
4566 "Non-nil means the agenda will skip any items located in archived trees.
4567 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4568 variable is no longer recommended, you should leave it at the value t.
4569 Instead, use the key `v' to cycle the archives-mode in the agenda."
4570 :group 'org-archive
4571 :group 'org-agenda-skip
4572 :type 'boolean)
4574 (defcustom org-columns-skip-archived-trees t
4575 "Non-nil means ignore archived trees when creating column view."
4576 :group 'org-archive
4577 :group 'org-properties
4578 :type 'boolean)
4580 (defcustom org-cycle-open-archived-trees nil
4581 "Non-nil means `org-cycle' will open archived trees.
4582 An archived tree is a tree marked with the tag ARCHIVE.
4583 When nil, archived trees will stay folded. You can still open them with
4584 normal outline commands like `show-all', but not with the cycling commands."
4585 :group 'org-archive
4586 :group 'org-cycle
4587 :type 'boolean)
4589 (defcustom org-sparse-tree-open-archived-trees nil
4590 "Non-nil means sparse tree construction shows matches in archived trees.
4591 When nil, matches in these trees are highlighted, but the trees are kept in
4592 collapsed state."
4593 :group 'org-archive
4594 :group 'org-sparse-trees
4595 :type 'boolean)
4597 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4598 "The default date type when building a sparse tree.
4599 When this is nil, a date is a scheduled or a deadline timestamp.
4600 Otherwise, these types are allowed:
4602 all: all timestamps
4603 active: only active timestamps (<...>)
4604 inactive: only inactive timestamps (<...)
4605 scheduled: only scheduled timestamps
4606 deadline: only deadline timestamps"
4607 :type '(choice (const :tag "Scheduled or deadline" scheduled-or-deadline)
4608 (const :tag "All timestamps" all)
4609 (const :tag "Only active timestamps" active)
4610 (const :tag "Only inactive timestamps" inactive)
4611 (const :tag "Only scheduled timestamps" scheduled)
4612 (const :tag "Only deadline timestamps" deadline)
4613 (const :tag "Only closed timestamps" closed))
4614 :version "24.3"
4615 :group 'org-sparse-trees)
4617 (defun org-cycle-hide-archived-subtrees (state)
4618 "Re-hide all archived subtrees after a visibility state change."
4619 (when (and (not org-cycle-open-archived-trees)
4620 (not (memq state '(overview folded))))
4621 (save-excursion
4622 (let* ((globalp (memq state '(contents all)))
4623 (beg (if globalp (point-min) (point)))
4624 (end (if globalp (point-max) (org-end-of-subtree t))))
4625 (org-hide-archived-subtrees beg end)
4626 (goto-char beg)
4627 (if (looking-at (concat ".*:" org-archive-tag ":"))
4628 (message "%s" (substitute-command-keys
4629 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4631 (defun org-force-cycle-archived ()
4632 "Cycle subtree even if it is archived."
4633 (interactive)
4634 (setq this-command 'org-cycle)
4635 (let ((org-cycle-open-archived-trees t))
4636 (call-interactively 'org-cycle)))
4638 (defun org-hide-archived-subtrees (beg end)
4639 "Re-hide all archived subtrees after a visibility state change."
4640 (save-excursion
4641 (let* ((re (concat ":" org-archive-tag ":")))
4642 (goto-char beg)
4643 (while (re-search-forward re end t)
4644 (when (org-at-heading-p)
4645 (org-flag-subtree t)
4646 (org-end-of-subtree t))))))
4648 (declare-function outline-end-of-heading "outline" ())
4649 (declare-function outline-flag-region "outline" (from to flag))
4650 (defun org-flag-subtree (flag)
4651 (save-excursion
4652 (org-back-to-heading t)
4653 (outline-end-of-heading)
4654 (outline-flag-region (point)
4655 (progn (org-end-of-subtree t) (point))
4656 flag)))
4658 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4660 ;; Declare Column View Code
4662 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4663 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4664 (declare-function org-columns-compute "org-colview" (property))
4666 ;; Declare ID code
4668 (declare-function org-id-store-link "org-id")
4669 (declare-function org-id-locations-load "org-id")
4670 (declare-function org-id-locations-save "org-id")
4671 (defvar org-id-track-globally)
4673 ;;; Variables for pre-computed regular expressions, all buffer local
4675 (defvar org-todo-regexp nil
4676 "Matches any of the TODO state keywords.")
4677 (make-variable-buffer-local 'org-todo-regexp)
4678 (defvar org-not-done-regexp nil
4679 "Matches any of the TODO state keywords except the last one.")
4680 (make-variable-buffer-local 'org-not-done-regexp)
4681 (defvar org-not-done-heading-regexp nil
4682 "Matches a TODO headline that is not done.")
4683 (make-variable-buffer-local 'org-not-done-regexp)
4684 (defvar org-todo-line-regexp nil
4685 "Matches a headline and puts TODO state into group 2 if present.")
4686 (make-variable-buffer-local 'org-todo-line-regexp)
4687 (defvar org-complex-heading-regexp nil
4688 "Matches a headline and puts everything into groups:
4689 group 1: the stars
4690 group 2: The todo keyword, maybe
4691 group 3: Priority cookie
4692 group 4: True headline
4693 group 5: Tags")
4694 (make-variable-buffer-local 'org-complex-heading-regexp)
4695 (defvar org-complex-heading-regexp-format nil
4696 "Printf format to make regexp to match an exact headline.
4697 This regexp will match the headline of any node which has the
4698 exact headline text that is put into the format, but may have any
4699 TODO state, priority and tags.")
4700 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4701 (defvar org-todo-line-tags-regexp nil
4702 "Matches a headline and puts TODO state into group 2 if present.
4703 Also put tags into group 4 if tags are present.")
4704 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4705 (defvar org-ds-keyword-length 12
4706 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4707 (make-variable-buffer-local 'org-ds-keyword-length)
4708 (defvar org-deadline-regexp nil
4709 "Matches the DEADLINE keyword.")
4710 (make-variable-buffer-local 'org-deadline-regexp)
4711 (defvar org-deadline-time-regexp nil
4712 "Matches the DEADLINE keyword together with a time stamp.")
4713 (make-variable-buffer-local 'org-deadline-time-regexp)
4714 (defvar org-deadline-time-hour-regexp nil
4715 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4716 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4717 (defvar org-deadline-line-regexp nil
4718 "Matches the DEADLINE keyword and the rest of the line.")
4719 (make-variable-buffer-local 'org-deadline-line-regexp)
4720 (defvar org-scheduled-regexp nil
4721 "Matches the SCHEDULED keyword.")
4722 (make-variable-buffer-local 'org-scheduled-regexp)
4723 (defvar org-scheduled-time-regexp nil
4724 "Matches the SCHEDULED keyword together with a time stamp.")
4725 (make-variable-buffer-local 'org-scheduled-time-regexp)
4726 (defvar org-scheduled-time-hour-regexp nil
4727 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4728 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4729 (defvar org-closed-time-regexp nil
4730 "Matches the CLOSED keyword together with a time stamp.")
4731 (make-variable-buffer-local 'org-closed-time-regexp)
4733 (defvar org-keyword-time-regexp nil
4734 "Matches any of the 4 keywords, together with the time stamp.")
4735 (make-variable-buffer-local 'org-keyword-time-regexp)
4736 (defvar org-keyword-time-not-clock-regexp nil
4737 "Matches any of the 3 keywords, together with the time stamp.")
4738 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4739 (defvar org-maybe-keyword-time-regexp nil
4740 "Matches a timestamp, possibly preceded by a keyword.")
4741 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4742 (defvar org-all-time-keywords nil
4743 "List of time keywords.")
4744 (make-variable-buffer-local 'org-all-time-keywords)
4746 (defconst org-plain-time-of-day-regexp
4747 (concat
4748 "\\(\\<[012]?[0-9]"
4749 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4750 "\\(--?"
4751 "\\(\\<[012]?[0-9]"
4752 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4753 "\\)?")
4754 "Regular expression to match a plain time or time range.
4755 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4756 groups carry important information:
4757 0 the full match
4758 1 the first time, range or not
4759 8 the second time, if it is a range.")
4761 (defconst org-plain-time-extension-regexp
4762 (concat
4763 "\\(\\<[012]?[0-9]"
4764 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4765 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4766 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4767 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4768 groups carry important information:
4769 0 the full match
4770 7 hours of duration
4771 9 minutes of duration")
4773 (defconst org-stamp-time-of-day-regexp
4774 (concat
4775 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4776 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4777 "\\(--?"
4778 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4779 "Regular expression to match a timestamp time or time range.
4780 After a match, the following groups carry important information:
4781 0 the full match
4782 1 date plus weekday, for back referencing to make sure both times are on the same day
4783 2 the first time, range or not
4784 4 the second time, if it is a range.")
4786 (defconst org-startup-options
4787 '(("fold" org-startup-folded t)
4788 ("overview" org-startup-folded t)
4789 ("nofold" org-startup-folded nil)
4790 ("showall" org-startup-folded nil)
4791 ("showeverything" org-startup-folded showeverything)
4792 ("content" org-startup-folded content)
4793 ("indent" org-startup-indented t)
4794 ("noindent" org-startup-indented nil)
4795 ("hidestars" org-hide-leading-stars t)
4796 ("showstars" org-hide-leading-stars nil)
4797 ("odd" org-odd-levels-only t)
4798 ("oddeven" org-odd-levels-only nil)
4799 ("align" org-startup-align-all-tables t)
4800 ("noalign" org-startup-align-all-tables nil)
4801 ("inlineimages" org-startup-with-inline-images t)
4802 ("noinlineimages" org-startup-with-inline-images nil)
4803 ("latexpreview" org-startup-with-latex-preview t)
4804 ("nolatexpreview" org-startup-with-latex-preview nil)
4805 ("customtime" org-display-custom-times t)
4806 ("logdone" org-log-done time)
4807 ("lognotedone" org-log-done note)
4808 ("nologdone" org-log-done nil)
4809 ("lognoteclock-out" org-log-note-clock-out t)
4810 ("nolognoteclock-out" org-log-note-clock-out nil)
4811 ("logrepeat" org-log-repeat state)
4812 ("lognoterepeat" org-log-repeat note)
4813 ("logdrawer" org-log-into-drawer t)
4814 ("nologdrawer" org-log-into-drawer nil)
4815 ("logstatesreversed" org-log-states-order-reversed t)
4816 ("nologstatesreversed" org-log-states-order-reversed nil)
4817 ("nologrepeat" org-log-repeat nil)
4818 ("logreschedule" org-log-reschedule time)
4819 ("lognotereschedule" org-log-reschedule note)
4820 ("nologreschedule" org-log-reschedule nil)
4821 ("logredeadline" org-log-redeadline time)
4822 ("lognoteredeadline" org-log-redeadline note)
4823 ("nologredeadline" org-log-redeadline nil)
4824 ("logrefile" org-log-refile time)
4825 ("lognoterefile" org-log-refile note)
4826 ("nologrefile" org-log-refile nil)
4827 ("fninline" org-footnote-define-inline t)
4828 ("nofninline" org-footnote-define-inline nil)
4829 ("fnlocal" org-footnote-section nil)
4830 ("fnauto" org-footnote-auto-label t)
4831 ("fnprompt" org-footnote-auto-label nil)
4832 ("fnconfirm" org-footnote-auto-label confirm)
4833 ("fnplain" org-footnote-auto-label plain)
4834 ("fnadjust" org-footnote-auto-adjust t)
4835 ("nofnadjust" org-footnote-auto-adjust nil)
4836 ("constcgs" constants-unit-system cgs)
4837 ("constSI" constants-unit-system SI)
4838 ("noptag" org-tag-persistent-alist nil)
4839 ("hideblocks" org-hide-block-startup t)
4840 ("nohideblocks" org-hide-block-startup nil)
4841 ("beamer" org-startup-with-beamer-mode t)
4842 ("entitiespretty" org-pretty-entities t)
4843 ("entitiesplain" org-pretty-entities nil))
4844 "Variable associated with STARTUP options for org-mode.
4845 Each element is a list of three items: the startup options (as written
4846 in the #+STARTUP line), the corresponding variable, and the value to set
4847 this variable to if the option is found. An optional forth element PUSH
4848 means to push this value onto the list in the variable.")
4850 (defun org-update-property-plist (key val props)
4851 "Update PROPS with KEY and VAL."
4852 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4853 (key (if appending (substring key 0 (- (length key) 1)) key))
4854 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4855 (previous (cdr (assoc key props))))
4856 (if appending
4857 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4858 (cons (cons key val) remainder))))
4860 (defcustom org-group-tags t
4861 "When non-nil (the default), use group tags.
4862 This can be turned on/off through `org-toggle-tags-groups'."
4863 :group 'org-tags
4864 :group 'org-startup
4865 :type 'boolean)
4867 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4869 (defun org-toggle-tags-groups ()
4870 "Toggle support for group tags.
4871 Support for group tags is controlled by the option
4872 `org-group-tags', which is non-nil by default."
4873 (interactive)
4874 (setq org-group-tags (not org-group-tags))
4875 (cond ((and (derived-mode-p 'org-agenda-mode)
4876 org-group-tags)
4877 (org-agenda-redo))
4878 ((derived-mode-p 'org-mode)
4879 (let ((org-inhibit-startup t)) (org-mode))))
4880 (message "Groups tags support has been turned %s"
4881 (if org-group-tags "on" "off")))
4883 (defun org-set-regexps-and-options-for-tags ()
4884 "Precompute variables used for tags."
4885 (when (derived-mode-p 'org-mode)
4886 (org-set-local 'org-file-tags nil)
4887 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4888 (splitre "[ \t]+")
4889 (start 0)
4890 tags ftags key value)
4891 (save-excursion
4892 (save-restriction
4893 (widen)
4894 (goto-char (point-min))
4895 (while (re-search-forward re nil t)
4896 (setq key (upcase (org-match-string-no-properties 1))
4897 value (org-match-string-no-properties 2))
4898 (if (stringp value) (setq value (org-trim value)))
4899 (cond
4900 ((equal key "TAGS")
4901 (setq tags (append tags (if tags '("\\n") nil)
4902 (org-split-string value splitre))))
4903 ((equal key "FILETAGS")
4904 (when (string-match "\\S-" value)
4905 (setq ftags
4906 (append
4907 ftags
4908 (apply 'append
4909 (mapcar (lambda (x) (org-split-string x ":"))
4910 (org-split-string value)))))))))))
4911 ;; Process the file tags.
4912 (and ftags (org-set-local 'org-file-tags
4913 (mapcar 'org-add-prop-inherited ftags)))
4914 (org-set-local 'org-tag-groups-alist nil)
4915 ;; Process the tags.
4916 (when (and (not tags) org-tag-alist)
4917 (setq tags
4918 (mapcar
4919 (lambda (tg) (cond ((eq (car tg) :startgroup) "{")
4920 ((eq (car tg) :endgroup) "}")
4921 ((eq (car tg) :grouptags) ":")
4922 ((eq (car tg) :newline) "\n")
4923 (t (concat (car tg)
4924 (if (characterp (cdr tg))
4925 (format "(%s)" (char-to-string (cdr tg))) "")))))
4926 org-tag-alist)))
4927 (let (e tgs g)
4928 (while (setq e (pop tags))
4929 (cond
4930 ((equal e "{")
4931 (progn (push '(:startgroup) tgs)
4932 (when (equal (nth 1 tags) ":")
4933 (push (list (replace-regexp-in-string
4934 "(.+)$" "" (nth 0 tags)))
4935 org-tag-groups-alist)
4936 (setq g 0))))
4937 ((equal e ":") (push '(:grouptags) tgs))
4938 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4939 ((equal e "\\n") (push '(:newline) tgs))
4940 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4941 (push (cons (match-string 1 e)
4942 (string-to-char (match-string 2 e))) tgs)
4943 (if (and g (> g 0))
4944 (setcar org-tag-groups-alist
4945 (append (car org-tag-groups-alist)
4946 (list (match-string 1 e)))))
4947 (if g (setq g (1+ g))))
4948 (t (push (list e) tgs)
4949 (if (and g (> g 0))
4950 (setcar org-tag-groups-alist
4951 (append (car org-tag-groups-alist) (list e))))
4952 (if g (setq g (1+ g))))))
4953 (org-set-local 'org-tag-alist nil)
4954 (while (setq e (pop tgs))
4955 (or (and (stringp (car e))
4956 (assoc (car e) org-tag-alist))
4957 (push e org-tag-alist)))
4958 ;; Return a list with tag variables
4959 (list org-file-tags org-tag-alist org-tag-groups-alist)))))
4961 (defvar org-ota nil)
4962 (defun org-set-regexps-and-options ()
4963 "Precompute regular expressions used in the current buffer."
4964 (when (derived-mode-p 'org-mode)
4965 (org-set-local 'org-todo-kwd-alist nil)
4966 (org-set-local 'org-todo-key-alist nil)
4967 (org-set-local 'org-todo-key-trigger nil)
4968 (org-set-local 'org-todo-keywords-1 nil)
4969 (org-set-local 'org-done-keywords nil)
4970 (org-set-local 'org-todo-heads nil)
4971 (org-set-local 'org-todo-sets nil)
4972 (org-set-local 'org-todo-log-states nil)
4973 (org-set-local 'org-file-properties nil)
4974 (let ((re (org-make-options-regexp
4975 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
4976 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4977 "SETUPFILE" "OPTIONS")
4978 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4979 (splitre "[ \t]+")
4980 (scripts org-use-sub-superscripts)
4981 kwds kws0 kwsa key log value cat arch const links hw dws
4982 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
4983 (start 0))
4984 (save-excursion
4985 (save-restriction
4986 (widen)
4987 (goto-char (point-min))
4988 (while
4989 (or (and
4990 ext-setup-or-nil
4991 (not org-ota)
4992 (let (ret)
4993 (with-temp-buffer
4994 (insert ext-setup-or-nil)
4995 (let ((major-mode 'org-mode) org-ota)
4996 (setq ret (save-match-data
4997 (org-set-regexps-and-options-for-tags)))))
4998 ;; Append setupfile tags to existing tags
4999 (setq org-ota t)
5000 (setq org-file-tags
5001 (delq nil (append org-file-tags (nth 0 ret)))
5002 org-tag-alist
5003 (delq nil (append org-tag-alist (nth 1 ret)))
5004 org-tag-groups-alist
5005 (delq nil (append org-tag-groups-alist (nth 2 ret))))))
5006 (and ext-setup-or-nil
5007 (string-match re ext-setup-or-nil start)
5008 (setq start (match-end 0)))
5009 (and (setq ext-setup-or-nil nil start 0)
5010 (re-search-forward re nil t)))
5011 (setq key (upcase (match-string 1 ext-setup-or-nil))
5012 value (org-match-string-no-properties 2 ext-setup-or-nil))
5013 (if (stringp value) (setq value (org-trim value)))
5014 (cond
5015 ((equal key "CATEGORY")
5016 (setq cat value))
5017 ((member key '("SEQ_TODO" "TODO"))
5018 (push (cons 'sequence (org-split-string value splitre)) kwds))
5019 ((equal key "TYP_TODO")
5020 (push (cons 'type (org-split-string value splitre)) kwds))
5021 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
5022 ;; general TODO-like setup
5023 (push (cons (intern (downcase (match-string 1 key)))
5024 (org-split-string value splitre)) kwds))
5025 ((equal key "COLUMNS")
5026 (org-set-local 'org-columns-default-format value))
5027 ((equal key "LINK")
5028 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5029 (push (cons (match-string 1 value)
5030 (org-trim (match-string 2 value)))
5031 links)))
5032 ((equal key "PRIORITIES")
5033 (setq prio (org-split-string value " +")))
5034 ((equal key "PROPERTY")
5035 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
5036 (setq props (org-update-property-plist (match-string 1 value)
5037 (match-string 2 value)
5038 props))))
5039 ((equal key "CONSTANTS")
5040 (org-table-set-constants))
5041 ((equal key "STARTUP")
5042 (let ((opts (org-split-string value splitre))
5043 l var val)
5044 (while (setq l (pop opts))
5045 (when (setq l (assoc l org-startup-options))
5046 (setq var (nth 1 l) val (nth 2 l))
5047 (if (not (nth 3 l))
5048 (set (make-local-variable var) val)
5049 (if (not (listp (symbol-value var)))
5050 (set (make-local-variable var) nil))
5051 (set (make-local-variable var) (symbol-value var))
5052 (add-to-list var val))))))
5053 ((equal key "ARCHIVE")
5054 (setq arch value)
5055 (remove-text-properties 0 (length arch)
5056 '(face t fontified t) arch))
5057 ((equal key "OPTIONS")
5058 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
5059 (setq scripts (read (match-string 2 value)))))
5060 ((and (equal key "SETUPFILE")
5061 ;; Prevent checking in Gnus messages
5062 (not buffer-read-only))
5063 (setq setup-contents (org-file-contents
5064 (expand-file-name
5065 (org-remove-double-quotes value))
5066 'noerror))
5067 (if (not ext-setup-or-nil)
5068 (setq ext-setup-or-nil setup-contents start 0)
5069 (setq ext-setup-or-nil
5070 (concat (substring ext-setup-or-nil 0 start)
5071 "\n" setup-contents "\n"
5072 (substring ext-setup-or-nil start)))))))
5073 ;; search for property blocks
5074 (goto-char (point-min))
5075 (while (re-search-forward org-block-regexp nil t)
5076 (when (equal "PROPERTY" (upcase (match-string 1)))
5077 (setq value (replace-regexp-in-string
5078 "[\n\r]" " " (match-string 4)))
5079 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
5080 (setq props (org-update-property-plist (match-string 1 value)
5081 (match-string 2 value)
5082 props)))))))
5083 (org-set-local 'org-use-sub-superscripts scripts)
5084 (when cat
5085 (org-set-local 'org-category (intern cat))
5086 (push (cons "CATEGORY" cat) props))
5087 (when prio
5088 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
5089 (setq prio (mapcar 'string-to-char prio))
5090 (org-set-local 'org-highest-priority (nth 0 prio))
5091 (org-set-local 'org-lowest-priority (nth 1 prio))
5092 (org-set-local 'org-default-priority (nth 2 prio)))
5093 (and props (org-set-local 'org-file-properties (nreverse props)))
5094 (and arch (org-set-local 'org-archive-location arch))
5095 (and links (setq org-link-abbrev-alist-local (nreverse links)))
5096 ;; Process the TODO keywords
5097 (unless kwds
5098 ;; Use the global values as if they had been given locally.
5099 (setq kwds (default-value 'org-todo-keywords))
5100 (if (stringp (car kwds))
5101 (setq kwds (list (cons org-todo-interpretation
5102 (default-value 'org-todo-keywords)))))
5103 (setq kwds (reverse kwds)))
5104 (setq kwds (nreverse kwds))
5105 (let (inter kws kw)
5106 (while (setq kws (pop kwds))
5107 (let ((kws (or
5108 (run-hook-with-args-until-success
5109 'org-todo-setup-filter-hook kws)
5110 kws)))
5111 (setq inter (pop kws) sep (member "|" kws)
5112 kws0 (delete "|" (copy-sequence kws))
5113 kwsa nil
5114 kws1 (mapcar
5115 (lambda (x)
5116 ;; 1 2
5117 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
5118 (progn
5119 (setq kw (match-string 1 x)
5120 key (and (match-end 2) (match-string 2 x))
5121 log (org-extract-log-state-settings x))
5122 (push (cons kw (and key (string-to-char key))) kwsa)
5123 (and log (push log org-todo-log-states))
5125 (error "Invalid TODO keyword %s" x)))
5126 kws0)
5127 kwsa (if kwsa (append '((:startgroup))
5128 (nreverse kwsa)
5129 '((:endgroup))))
5130 hw (car kws1)
5131 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
5132 tail (list inter hw (car dws) (org-last dws))))
5133 (add-to-list 'org-todo-heads hw 'append)
5134 (push kws1 org-todo-sets)
5135 (setq org-done-keywords (append org-done-keywords dws nil))
5136 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
5137 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
5138 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
5139 (setq org-todo-sets (nreverse org-todo-sets)
5140 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5141 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
5142 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
5143 ;; Compute the regular expressions and other local variables.
5144 ;; Using `org-outline-regexp-bol' would complicate them much,
5145 ;; because of the fixed white space at the end of that string.
5146 (if (not org-done-keywords)
5147 (setq org-done-keywords (and org-todo-keywords-1
5148 (list (org-last org-todo-keywords-1)))))
5149 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5150 (length org-scheduled-string)
5151 (length org-clock-string)
5152 (length org-closed-string)))
5153 org-not-done-keywords
5154 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5155 org-todo-regexp
5156 (concat "\\("
5157 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5158 "\\)")
5159 org-not-done-regexp
5160 (concat "\\("
5161 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5162 "\\)")
5163 org-not-done-heading-regexp
5164 (format org-heading-keyword-regexp-format org-not-done-regexp)
5165 org-todo-line-regexp
5166 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5167 org-complex-heading-regexp
5168 (concat "^\\(\\*+\\)"
5169 "\\(?: +" org-todo-regexp "\\)?"
5170 "\\(?: +\\(\\[#.\\]\\)\\)?"
5171 "\\(?: +\\(.*?\\)\\)??"
5172 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5173 "[ \t]*$")
5174 org-complex-heading-regexp-format
5175 (concat "^\\(\\*+\\)"
5176 "\\(?: +" org-todo-regexp "\\)?"
5177 "\\(?: +\\(\\[#.\\]\\)\\)?"
5178 "\\(?: +"
5179 ;; Stats cookies can be stuck to body.
5180 "\\(?:\\[[0-9%%/]+\\] *\\)?"
5181 "\\(%s\\)"
5182 "\\(?: *\\[[0-9%%/]+\\]\\)?"
5183 "\\)"
5184 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5185 "[ \t]*$")
5186 org-todo-line-tags-regexp
5187 (concat "^\\(\\*+\\)"
5188 "\\(?: +" org-todo-regexp "\\)?"
5189 "\\(?: +\\(.*?\\)\\)??"
5190 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5191 "[ \t]*$")
5192 org-deadline-regexp (concat "\\<" org-deadline-string)
5193 org-deadline-time-regexp
5194 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5195 org-deadline-time-hour-regexp
5196 (concat "\\<" org-deadline-string
5197 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5198 org-deadline-line-regexp
5199 (concat "\\<\\(" org-deadline-string "\\).*")
5200 org-scheduled-regexp
5201 (concat "\\<" org-scheduled-string)
5202 org-scheduled-time-regexp
5203 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5204 org-scheduled-time-hour-regexp
5205 (concat "\\<" org-scheduled-string
5206 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5207 org-closed-time-regexp
5208 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5209 org-keyword-time-regexp
5210 (concat "\\<\\(" org-scheduled-string
5211 "\\|" org-deadline-string
5212 "\\|" org-closed-string
5213 "\\|" org-clock-string "\\)"
5214 " *[[<]\\([^]>]+\\)[]>]")
5215 org-keyword-time-not-clock-regexp
5216 (concat "\\<\\(" org-scheduled-string
5217 "\\|" org-deadline-string
5218 "\\|" org-closed-string
5219 "\\)"
5220 " *[[<]\\([^]>]+\\)[]>]")
5221 org-maybe-keyword-time-regexp
5222 (concat "\\(\\<\\(" org-scheduled-string
5223 "\\|" org-deadline-string
5224 "\\|" org-closed-string
5225 "\\|" org-clock-string "\\)\\)?"
5226 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5227 org-all-time-keywords
5228 (mapcar (lambda (w) (substring w 0 -1))
5229 (list org-scheduled-string org-deadline-string
5230 org-clock-string org-closed-string)))
5231 (setq org-ota nil)
5232 (org-compute-latex-and-related-regexp))))
5234 (defun org-file-contents (file &optional noerror)
5235 "Return the contents of FILE, as a string."
5236 (if (or (not file)
5237 (not (file-readable-p file)))
5238 (if noerror
5239 (message "Cannot read file \"%s\"" file)
5240 (error "Cannot read file \"%s\"" file))
5241 (with-temp-buffer
5242 (insert-file-contents file)
5243 (buffer-string))))
5245 (defun org-extract-log-state-settings (x)
5246 "Extract the log state setting from a TODO keyword string.
5247 This will extract info from a string like \"WAIT(w@/!)\"."
5248 (let (kw key log1 log2)
5249 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5250 (setq kw (match-string 1 x)
5251 key (and (match-end 2) (match-string 2 x))
5252 log1 (and (match-end 3) (match-string 3 x))
5253 log2 (and (match-end 4) (match-string 4 x)))
5254 (and (or log1 log2)
5255 (list kw
5256 (and log1 (if (equal log1 "!") 'time 'note))
5257 (and log2 (if (equal log2 "!") 'time 'note)))))))
5259 (defun org-remove-keyword-keys (list)
5260 "Remove a pair of parenthesis at the end of each string in LIST."
5261 (mapcar (lambda (x)
5262 (if (string-match "(.*)$" x)
5263 (substring x 0 (match-beginning 0))
5265 list))
5267 (defun org-assign-fast-keys (alist)
5268 "Assign fast keys to a keyword-key alist.
5269 Respect keys that are already there."
5270 (let (new e (alt ?0))
5271 (while (setq e (pop alist))
5272 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5273 (cdr e)) ;; Key already assigned.
5274 (push e new)
5275 (let ((clist (string-to-list (downcase (car e))))
5276 (used (append new alist)))
5277 (when (= (car clist) ?@)
5278 (pop clist))
5279 (while (and clist (rassoc (car clist) used))
5280 (pop clist))
5281 (unless clist
5282 (while (rassoc alt used)
5283 (incf alt)))
5284 (push (cons (car e) (or (car clist) alt)) new))))
5285 (nreverse new)))
5287 ;;; Some variables used in various places
5289 (defvar org-window-configuration nil
5290 "Used in various places to store a window configuration.")
5291 (defvar org-selected-window nil
5292 "Used in various places to store a window configuration.")
5293 (defvar org-finish-function nil
5294 "Function to be called when `C-c C-c' is used.
5295 This is for getting out of special buffers like capture.")
5298 ;; FIXME: Occasionally check by commenting these, to make sure
5299 ;; no other functions uses these, forgetting to let-bind them.
5300 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5301 (defvar org-last-state)
5302 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5304 ;; Defined somewhere in this file, but used before definition.
5305 (defvar org-entities) ;; defined in org-entities.el
5306 (defvar org-struct-menu)
5307 (defvar org-org-menu)
5308 (defvar org-tbl-menu)
5310 ;;;; Define the Org-mode
5312 ;; We use a before-change function to check if a table might need
5313 ;; an update.
5314 (defvar org-table-may-need-update t
5315 "Indicates that a table might need an update.
5316 This variable is set by `org-before-change-function'.
5317 `org-table-align' sets it back to nil.")
5318 (defun org-before-change-function (beg end)
5319 "Every change indicates that a table might need an update."
5320 (setq org-table-may-need-update t))
5321 (defvar org-mode-map)
5322 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5323 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5324 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5325 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5326 (defvar org-table-buffer-is-an nil)
5328 (defvar bidi-paragraph-direction)
5329 (defvar buffer-face-mode-face)
5331 (require 'outline)
5332 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5333 (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"))
5334 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5336 ;; Other stuff we need.
5337 (require 'time-date)
5338 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5339 (require 'easymenu)
5340 (require 'overlay)
5342 ;; (require 'org-macs) moved higher up in the file before it is first used
5343 (require 'org-entities)
5344 ;; (require 'org-compat) moved higher up in the file before it is first used
5345 (require 'org-faces)
5346 (require 'org-list)
5347 (require 'org-pcomplete)
5348 (require 'org-src)
5349 (require 'org-footnote)
5350 (require 'org-macro)
5352 ;; babel
5353 (require 'ob)
5355 ;;;###autoload
5356 (define-derived-mode org-mode outline-mode "Org"
5357 "Outline-based notes management and organizer, alias
5358 \"Carsten's outline-mode for keeping track of everything.\"
5360 Org-mode develops organizational tasks around a NOTES file which
5361 contains information about projects as plain text. Org-mode is
5362 implemented on top of outline-mode, which is ideal to keep the content
5363 of large files well structured. It supports ToDo items, deadlines and
5364 time stamps, which magically appear in the diary listing of the Emacs
5365 calendar. Tables are easily created with a built-in table editor.
5366 Plain text URL-like links connect to websites, emails (VM), Usenet
5367 messages (Gnus), BBDB entries, and any files related to the project.
5368 For printing and sharing of notes, an Org-mode file (or a part of it)
5369 can be exported as a structured ASCII or HTML file.
5371 The following commands are available:
5373 \\{org-mode-map}"
5375 ;; Get rid of Outline menus, they are not needed
5376 ;; Need to do this here because define-derived-mode sets up
5377 ;; the keymap so late. Still, it is a waste to call this each time
5378 ;; we switch another buffer into org-mode.
5379 (if (featurep 'xemacs)
5380 (when (boundp 'outline-mode-menu-heading)
5381 ;; Assume this is Greg's port, it uses easymenu
5382 (easy-menu-remove outline-mode-menu-heading)
5383 (easy-menu-remove outline-mode-menu-show)
5384 (easy-menu-remove outline-mode-menu-hide))
5385 (define-key org-mode-map [menu-bar headings] 'undefined)
5386 (define-key org-mode-map [menu-bar hide] 'undefined)
5387 (define-key org-mode-map [menu-bar show] 'undefined))
5389 (org-load-modules-maybe)
5390 (easy-menu-add org-org-menu)
5391 (easy-menu-add org-tbl-menu)
5392 (org-install-agenda-files-menu)
5393 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5394 (add-to-invisibility-spec '(org-cwidth))
5395 (add-to-invisibility-spec '(org-hide-block . t))
5396 (when (featurep 'xemacs)
5397 (org-set-local 'line-move-ignore-invisible t))
5398 (org-set-local 'outline-regexp org-outline-regexp)
5399 (org-set-local 'outline-level 'org-outline-level)
5400 (setq bidi-paragraph-direction 'left-to-right)
5401 (when (and org-ellipsis
5402 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5403 (fboundp 'make-glyph-code))
5404 (unless org-display-table
5405 (setq org-display-table (make-display-table)))
5406 (set-display-table-slot
5407 org-display-table 4
5408 (vconcat (mapcar
5409 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5410 org-ellipsis)))
5411 (if (stringp org-ellipsis) org-ellipsis "..."))))
5412 (setq buffer-display-table org-display-table))
5413 (org-set-regexps-and-options-for-tags)
5414 (org-set-regexps-and-options)
5415 (org-set-font-lock-defaults)
5416 (when (and org-tag-faces (not org-tags-special-faces-re))
5417 ;; tag faces set outside customize.... force initialization.
5418 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5419 ;; Calc embedded
5420 (org-set-local 'calc-embedded-open-mode "# ")
5421 ;; Modify a few syntax entries
5422 (modify-syntax-entry ?@ "w")
5423 (modify-syntax-entry ?\" "\"")
5424 (if org-startup-truncated (setq truncate-lines t))
5425 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5426 (org-set-local 'font-lock-unfontify-region-function
5427 'org-unfontify-region)
5428 ;; Activate before-change-function
5429 (org-set-local 'org-table-may-need-update t)
5430 (org-add-hook 'before-change-functions 'org-before-change-function nil
5431 'local)
5432 ;; Check for running clock before killing a buffer
5433 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5434 ;; Initialize macros templates.
5435 (org-macro-initialize-templates)
5436 ;; Initialize radio targets.
5437 (org-update-radio-target-regexp)
5438 ;; Indentation.
5439 (org-set-local 'indent-line-function 'org-indent-line)
5440 (org-set-local 'indent-region-function 'org-indent-region)
5441 ;; Filling and auto-filling.
5442 (org-setup-filling)
5443 ;; Comments.
5444 (org-setup-comments-handling)
5445 ;; Initialize cache.
5446 (org-element-cache-reset)
5447 ;; Beginning/end of defun
5448 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5449 (org-set-local 'end-of-defun-function 'org-forward-element)
5450 ;; Next error for sparse trees
5451 (org-set-local 'next-error-function 'org-occur-next-match)
5452 ;; Make sure dependence stuff works reliably, even for users who set it
5453 ;; too late :-(
5454 (if org-enforce-todo-dependencies
5455 (add-hook 'org-blocker-hook
5456 'org-block-todo-from-children-or-siblings-or-parent)
5457 (remove-hook 'org-blocker-hook
5458 'org-block-todo-from-children-or-siblings-or-parent))
5459 (if org-enforce-todo-checkbox-dependencies
5460 (add-hook 'org-blocker-hook
5461 'org-block-todo-from-checkboxes)
5462 (remove-hook 'org-blocker-hook
5463 'org-block-todo-from-checkboxes))
5465 ;; Align options lines
5466 (org-set-local
5467 'align-mode-rules-list
5468 '((org-in-buffer-settings
5469 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5470 (modes . '(org-mode)))))
5472 ;; Imenu
5473 (org-set-local 'imenu-create-index-function
5474 'org-imenu-get-tree)
5476 ;; Make isearch reveal context
5477 (if (or (featurep 'xemacs)
5478 (not (boundp 'outline-isearch-open-invisible-function)))
5479 ;; Emacs 21 and XEmacs make use of the hook
5480 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5481 ;; Emacs 22 deals with this through a special variable
5482 (org-set-local 'outline-isearch-open-invisible-function
5483 (lambda (&rest ignore) (org-show-context 'isearch)))
5484 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5486 ;; Setup the pcomplete hooks
5487 (set (make-local-variable 'pcomplete-command-completion-function)
5488 'org-pcomplete-initial)
5489 (set (make-local-variable 'pcomplete-command-name-function)
5490 'org-command-at-point)
5491 (set (make-local-variable 'pcomplete-default-completion-function)
5492 'ignore)
5493 (set (make-local-variable 'pcomplete-parse-arguments-function)
5494 'org-parse-arguments)
5495 (set (make-local-variable 'pcomplete-termination-string) "")
5496 (when (>= emacs-major-version 23)
5497 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5499 ;; If empty file that did not turn on org-mode automatically, make it to.
5500 (if (and org-insert-mode-line-in-empty-file
5501 (org-called-interactively-p 'any)
5502 (= (point-min) (point-max)))
5503 (insert "# -*- mode: org -*-\n\n"))
5504 (unless org-inhibit-startup
5505 (org-unmodified
5506 (and org-startup-with-beamer-mode (org-beamer-mode))
5507 (when org-startup-align-all-tables
5508 (org-table-map-tables 'org-table-align 'quietly))
5509 (when org-startup-with-inline-images
5510 (org-display-inline-images))
5511 (when org-startup-with-latex-preview
5512 (org-preview-latex-fragment))
5513 (unless org-inhibit-startup-visibility-stuff
5514 (org-set-startup-visibility))))
5515 ;; Try to set org-hide correctly
5516 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5518 ;; Update `customize-package-emacs-version-alist'
5519 (add-to-list 'customize-package-emacs-version-alist
5520 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5521 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5522 ("8.0" . "24.4")))
5524 (defvar org-mode-transpose-word-syntax-table
5525 (let ((st (make-syntax-table)))
5526 (mapc (lambda(c) (modify-syntax-entry
5527 (string-to-char (car c)) "w p" st))
5528 org-emphasis-alist)
5529 st))
5531 (when (fboundp 'abbrev-table-put)
5532 (abbrev-table-put org-mode-abbrev-table
5533 :parents (list text-mode-abbrev-table)))
5535 (defsubst org-fix-ellipsis-at-bol ()
5536 (save-excursion (goto-char (window-start)) (recenter 0)))
5538 (defun org-find-invisible-foreground ()
5539 (let ((candidates (remove
5540 "unspecified-bg"
5541 (nconc
5542 (list (face-background 'default)
5543 (face-background 'org-default))
5544 (mapcar
5545 (lambda (alist)
5546 (when (boundp alist)
5547 (cdr (assoc 'background-color (symbol-value alist)))))
5548 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5549 (list (face-foreground 'org-hide))))))
5550 (car (remove nil candidates))))
5552 (defun org-current-time (&optional rounding-minutes past)
5553 "Current time, possibly rounded to ROUNDING-MINUTES.
5554 When ROUNDING-MINUTES is not an integer, fall back on the car of
5555 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5556 the rounding returns a past time."
5557 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5558 (car org-time-stamp-rounding-minutes)))
5559 (time (decode-time)) res)
5560 (if (< r 1)
5561 (current-time)
5562 (setq res
5563 (apply 'encode-time
5564 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5565 (nthcdr 2 time))))
5566 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5567 (seconds-to-time (- (org-float-time res) (* r 60)))
5568 res))))
5570 (defun org-today ()
5571 "Return today date, considering `org-extend-today-until'."
5572 (time-to-days
5573 (time-subtract (current-time)
5574 (list 0 (* 3600 org-extend-today-until) 0))))
5576 ;;;; Font-Lock stuff, including the activators
5578 (defvar org-mouse-map (make-sparse-keymap))
5579 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5580 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5581 (when org-mouse-1-follows-link
5582 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5583 (when org-tab-follows-link
5584 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5585 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5587 (require 'font-lock)
5589 (defconst org-non-link-chars "]\t\n\r<>")
5590 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5591 "shell" "elisp" "doi" "message"))
5592 (defvar org-link-types-re nil
5593 "Matches a link that has a url-like prefix like \"http:\"")
5594 (defvar org-link-re-with-space nil
5595 "Matches a link with spaces, optional angular brackets around it.")
5596 (defvar org-link-re-with-space2 nil
5597 "Matches a link with spaces, optional angular brackets around it.")
5598 (defvar org-link-re-with-space3 nil
5599 "Matches a link with spaces, only for internal part in bracket links.")
5600 (defvar org-angle-link-re nil
5601 "Matches link with angular brackets, spaces are allowed.")
5602 (defvar org-plain-link-re nil
5603 "Matches plain link, without spaces.")
5604 (defvar org-bracket-link-regexp nil
5605 "Matches a link in double brackets.")
5606 (defvar org-bracket-link-analytic-regexp nil
5607 "Regular expression used to analyze links.
5608 Here is what the match groups contain after a match:
5609 1: http:
5610 2: http
5611 3: path
5612 4: [desc]
5613 5: desc")
5614 (defvar org-bracket-link-analytic-regexp++ nil
5615 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5616 (defvar org-any-link-re nil
5617 "Regular expression matching any link.")
5619 (defconst org-match-sexp-depth 3
5620 "Number of stacked braces for sub/superscript matching.")
5622 (defun org-create-multibrace-regexp (left right n)
5623 "Create a regular expression which will match a balanced sexp.
5624 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5625 as single character strings.
5626 The regexp returned will match the entire expression including the
5627 delimiters. It will also define a single group which contains the
5628 match except for the outermost delimiters. The maximum depth of
5629 stacked delimiters is N. Escaping delimiters is not possible."
5630 (let* ((nothing (concat "[^" left right "]*?"))
5631 (or "\\|")
5632 (re nothing)
5633 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5634 (while (> n 1)
5635 (setq n (1- n)
5636 re (concat re or next)
5637 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5638 (concat left "\\(" re "\\)" right)))
5640 (defvar org-match-substring-regexp
5641 (concat
5642 "\\(\\S-\\)\\([_^]\\)\\("
5643 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5644 "\\|"
5645 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5646 "\\|"
5647 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5648 "The regular expression matching a sub- or superscript.")
5650 (defvar org-match-substring-with-braces-regexp
5651 (concat
5652 "\\(\\S-\\)\\([_^]\\)\\("
5653 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5654 "\\)")
5655 "The regular expression matching a sub- or superscript, forcing braces.")
5657 (defun org-make-link-regexps ()
5658 "Update the link regular expressions.
5659 This should be called after the variable `org-link-types' has changed."
5660 (setq org-link-types-re
5661 (concat
5662 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5663 org-link-re-with-space
5664 (concat
5665 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5666 "\\([^" org-non-link-chars " ]"
5667 "[^" org-non-link-chars "]*"
5668 "[^" org-non-link-chars " ]\\)>?")
5669 org-link-re-with-space2
5670 (concat
5671 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5672 "\\([^" org-non-link-chars " ]"
5673 "[^\t\n\r]*"
5674 "[^" org-non-link-chars " ]\\)>?")
5675 org-link-re-with-space3
5676 (concat
5677 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5678 "\\([^" org-non-link-chars " ]"
5679 "[^\t\n\r]*\\)")
5680 org-angle-link-re
5681 (concat
5682 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5683 "\\([^" org-non-link-chars " ]"
5684 "[^" org-non-link-chars "]*"
5685 "\\)>")
5686 org-plain-link-re
5687 (concat
5688 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5689 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5690 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5691 org-bracket-link-regexp
5692 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5693 org-bracket-link-analytic-regexp
5694 (concat
5695 "\\[\\["
5696 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5697 "\\([^]]+\\)"
5698 "\\]"
5699 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5700 "\\]")
5701 org-bracket-link-analytic-regexp++
5702 (concat
5703 "\\[\\["
5704 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5705 "\\([^]]+\\)"
5706 "\\]"
5707 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5708 "\\]")
5709 org-any-link-re
5710 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5711 org-angle-link-re "\\)\\|\\("
5712 org-plain-link-re "\\)")))
5714 (org-make-link-regexps)
5716 (defvar org-emph-face nil)
5718 (defun org-do-emphasis-faces (limit)
5719 "Run through the buffer and add overlays to emphasized strings."
5720 (let (rtn a)
5721 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5722 (if (not (= (char-after (match-beginning 3))
5723 (char-after (match-beginning 4))))
5724 (progn
5725 (setq rtn t)
5726 (setq a (assoc (match-string 3) org-emphasis-alist))
5727 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5728 'face
5729 (nth 1 a))
5730 (and (nth 2 a)
5731 (org-remove-flyspell-overlays-in
5732 (match-beginning 0) (match-end 0)))
5733 (add-text-properties (match-beginning 2) (match-end 2)
5734 '(font-lock-multiline t org-emphasis t))
5735 (when org-hide-emphasis-markers
5736 (add-text-properties (match-end 4) (match-beginning 5)
5737 '(invisible org-link))
5738 (add-text-properties (match-beginning 3) (match-end 3)
5739 '(invisible org-link)))))
5740 (goto-char (1+ (match-beginning 0))))
5741 rtn))
5743 (defun org-emphasize (&optional char)
5744 "Insert or change an emphasis, i.e. a font like bold or italic.
5745 If there is an active region, change that region to a new emphasis.
5746 If there is no region, just insert the marker characters and position
5747 the cursor between them.
5748 CHAR should be the marker character. If it is a space, it means to
5749 remove the emphasis of the selected region.
5750 If CHAR is not given (for example in an interactive call) it will be
5751 prompted for."
5752 (interactive)
5753 (let ((erc org-emphasis-regexp-components)
5754 (prompt "")
5755 (string "") beg end move c s)
5756 (if (org-region-active-p)
5757 (setq beg (region-beginning) end (region-end)
5758 string (buffer-substring beg end))
5759 (setq move t))
5761 (unless char
5762 (message "Emphasis marker or tag: [%s]"
5763 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5764 (setq char (read-char-exclusive)))
5765 (if (equal char ?\ )
5766 (setq s "" move nil)
5767 (unless (assoc (char-to-string char) org-emphasis-alist)
5768 (user-error "No such emphasis marker: \"%c\"" char))
5769 (setq s (char-to-string char)))
5770 (while (and (> (length string) 1)
5771 (equal (substring string 0 1) (substring string -1))
5772 (assoc (substring string 0 1) org-emphasis-alist))
5773 (setq string (substring string 1 -1)))
5774 (setq string (concat s string s))
5775 (if beg (delete-region beg end))
5776 (unless (or (bolp)
5777 (string-match (concat "[" (nth 0 erc) "\n]")
5778 (char-to-string (char-before (point)))))
5779 (insert " "))
5780 (unless (or (eobp)
5781 (string-match (concat "[" (nth 1 erc) "\n]")
5782 (char-to-string (char-after (point)))))
5783 (insert " ") (backward-char 1))
5784 (insert string)
5785 (and move (backward-char 1))))
5787 (defconst org-nonsticky-props
5788 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5790 (defsubst org-rear-nonsticky-at (pos)
5791 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5793 (defun org-activate-plain-links (limit)
5794 "Run through the buffer and add overlays to links."
5795 (let (f hl)
5796 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5797 (not (org-in-src-block-p)))
5798 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5799 (setq f (get-text-property (match-beginning 0) 'face))
5800 (setq hl (org-match-string-no-properties 0))
5801 (if (or (eq f 'org-tag)
5802 (and (listp f) (memq 'org-tag f)))
5804 (add-text-properties (match-beginning 0) (match-end 0)
5805 (list 'mouse-face 'highlight
5806 'face 'org-link
5807 'htmlize-link `(:uri ,hl)
5808 'keymap org-mouse-map))
5809 (org-rear-nonsticky-at (match-end 0)))
5810 t)))
5812 (defun org-activate-code (limit)
5813 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5814 (progn
5815 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5816 (remove-text-properties (match-beginning 0) (match-end 0)
5817 '(display t invisible t intangible t))
5818 t)))
5820 (defcustom org-src-fontify-natively nil
5821 "When non-nil, fontify code in code blocks."
5822 :type 'boolean
5823 :version "24.1"
5824 :group 'org-appearance
5825 :group 'org-babel)
5827 (defcustom org-allow-promoting-top-level-subtree nil
5828 "When non-nil, allow promoting a top level subtree.
5829 The leading star of the top level headline will be replaced
5830 by a #."
5831 :type 'boolean
5832 :version "24.1"
5833 :group 'org-appearance)
5835 (defun org-fontify-meta-lines-and-blocks (limit)
5836 (condition-case nil
5837 (org-fontify-meta-lines-and-blocks-1 limit)
5838 (error (message "org-mode fontification error"))))
5840 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5841 "Fontify #+ lines and blocks."
5842 (let ((case-fold-search t))
5843 (if (re-search-forward
5844 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5845 limit t)
5846 (let ((beg (match-beginning 0))
5847 (block-start (match-end 0))
5848 (block-end nil)
5849 (lang (match-string 7))
5850 (beg1 (line-beginning-position 2))
5851 (dc1 (downcase (match-string 2)))
5852 (dc3 (downcase (match-string 3)))
5853 end end1 quoting block-type ovl)
5854 (cond
5855 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5856 ;; a single line of backend-specific content
5857 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5858 (remove-text-properties (match-beginning 0) (match-end 0)
5859 '(display t invisible t intangible t))
5860 (add-text-properties (match-beginning 1) (match-end 3)
5861 '(font-lock-fontified t face org-meta-line))
5862 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5863 '(font-lock-fontified t face org-block))
5864 ; for backend-specific code
5866 ((and (match-end 4) (equal dc3 "+begin"))
5867 ;; Truly a block
5868 (setq block-type (downcase (match-string 5))
5869 quoting (member block-type org-protecting-blocks))
5870 (when (re-search-forward
5871 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5872 nil t) ;; on purpose, we look further than LIMIT
5873 (setq end (min (point-max) (match-end 0))
5874 end1 (min (point-max) (1- (match-beginning 0))))
5875 (setq block-end (match-beginning 0))
5876 (when quoting
5877 (org-remove-flyspell-overlays-in beg1 end1)
5878 (remove-text-properties beg end
5879 '(display t invisible t intangible t)))
5880 (add-text-properties
5881 beg end '(font-lock-fontified t font-lock-multiline t))
5882 (add-text-properties beg beg1 '(face org-meta-line))
5883 (org-remove-flyspell-overlays-in beg beg1)
5884 (add-text-properties ; For end_src
5885 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5886 (org-remove-flyspell-overlays-in end1 end)
5887 (cond
5888 ((and lang (not (string= lang "")) org-src-fontify-natively)
5889 (org-src-font-lock-fontify-block lang block-start block-end)
5890 ;; remove old background overlays
5891 (mapc (lambda (ov)
5892 (if (eq (overlay-get ov 'face) 'org-block-background)
5893 (delete-overlay ov)))
5894 (overlays-at (/ (+ beg1 block-end) 2)))
5895 ;; add a background overlay
5896 (setq ovl (make-overlay beg1 block-end))
5897 (overlay-put ovl 'face 'org-block-background)
5898 (overlay-put ovl 'evaporate t)) ; make it go away when empty
5899 (quoting
5900 (add-text-properties beg1 (min (point-max) (1+ end1))
5901 '(face org-block))) ; end of source block
5902 ((not org-fontify-quote-and-verse-blocks))
5903 ((string= block-type "quote")
5904 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5905 ((string= block-type "verse")
5906 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5907 (add-text-properties beg beg1 '(face org-block-begin-line))
5908 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5909 '(face org-block-end-line))
5911 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5912 (org-remove-flyspell-overlays-in
5913 (match-beginning 0)
5914 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5915 (add-text-properties
5916 beg (match-end 3)
5917 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5918 '(font-lock-fontified t invisible t)
5919 '(font-lock-fontified t face org-document-info-keyword)))
5920 (add-text-properties
5921 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5922 (if (string-equal dc1 "+title:")
5923 '(font-lock-fontified t face org-document-title)
5924 '(font-lock-fontified t face org-document-info))))
5925 ((or (equal dc1 "+results")
5926 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5927 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5928 "+call:" "+header:" "+headers:" "+name:"))
5929 (and (match-end 4) (equal dc3 "+attr")))
5930 (org-remove-flyspell-overlays-in
5931 (match-beginning 0)
5932 (if (equal "+caption:" dc1) (match-end 2) (match-end 0)))
5933 (add-text-properties
5934 beg (match-end 0)
5935 '(font-lock-fontified t face org-meta-line))
5937 ((member dc3 '(" " ""))
5938 (org-remove-flyspell-overlays-in beg (match-end 0))
5939 (add-text-properties
5940 beg (match-end 0)
5941 '(font-lock-fontified t face font-lock-comment-face)))
5942 ((not (member (char-after beg) '(?\ ?\t)))
5943 ;; just any other in-buffer setting, but not indented
5944 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5945 (add-text-properties
5946 beg (match-end 0)
5947 '(font-lock-fontified t face org-meta-line))
5949 (t nil))))))
5951 (defun org-fontify-drawers (limit)
5952 "Fontify drawers."
5953 (when (re-search-forward org-drawer-regexp limit t)
5954 (add-text-properties
5955 (match-beginning 0) (match-end 0)
5956 '(font-lock-fontified t face org-special-keyword))
5957 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5960 (defun org-activate-angle-links (limit)
5961 "Run through the buffer and add overlays to links."
5962 (if (and (re-search-forward org-angle-link-re limit t)
5963 (not (org-in-src-block-p)))
5964 (progn
5965 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5966 (add-text-properties (match-beginning 0) (match-end 0)
5967 (list 'mouse-face 'highlight
5968 'keymap org-mouse-map))
5969 (org-rear-nonsticky-at (match-end 0))
5970 t)))
5972 (defun org-activate-footnote-links (limit)
5973 "Run through the buffer and add overlays to footnotes."
5974 (let ((fn (org-footnote-next-reference-or-definition limit)))
5975 (when fn
5976 (let* ((beg (nth 1 fn))
5977 (end (nth 2 fn))
5978 (label (car fn))
5979 (referencep (/= (line-beginning-position) beg)))
5980 (when (and referencep (nth 3 fn))
5981 (save-excursion
5982 (goto-char beg)
5983 (search-forward (or label "fn:"))
5984 (org-remove-flyspell-overlays-in beg (match-end 0))))
5985 (add-text-properties beg end
5986 (list 'mouse-face 'highlight
5987 'keymap org-mouse-map
5988 'help-echo
5989 (if referencep "Footnote reference"
5990 "Footnote definition")
5991 'font-lock-fontified t
5992 'font-lock-multiline t
5993 'face 'org-footnote))))))
5995 (defun org-activate-bracket-links (limit)
5996 "Run through the buffer and add overlays to bracketed links."
5997 (if (and (re-search-forward org-bracket-link-regexp limit t)
5998 (not (org-in-src-block-p)))
5999 (let* ((hl (org-match-string-no-properties 1))
6000 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
6001 (ip (org-maybe-intangible
6002 (list 'invisible 'org-link
6003 'keymap org-mouse-map 'mouse-face 'highlight
6004 'font-lock-multiline t 'help-echo help
6005 'htmlize-link `(:uri ,hl))))
6006 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
6007 'font-lock-multiline t 'help-echo help
6008 'htmlize-link `(:uri ,hl))))
6009 ;; We need to remove the invisible property here. Table narrowing
6010 ;; may have made some of this invisible.
6011 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6012 (remove-text-properties (match-beginning 0) (match-end 0)
6013 '(invisible nil))
6014 (if (match-end 3)
6015 (progn
6016 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
6017 (org-rear-nonsticky-at (match-beginning 3))
6018 (add-text-properties (match-beginning 3) (match-end 3) vp)
6019 (org-rear-nonsticky-at (match-end 3))
6020 (add-text-properties (match-end 3) (match-end 0) ip)
6021 (org-rear-nonsticky-at (match-end 0)))
6022 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
6023 (org-rear-nonsticky-at (match-beginning 1))
6024 (add-text-properties (match-beginning 1) (match-end 1) vp)
6025 (org-rear-nonsticky-at (match-end 1))
6026 (add-text-properties (match-end 1) (match-end 0) ip)
6027 (org-rear-nonsticky-at (match-end 0)))
6028 t)))
6030 (defun org-activate-dates (limit)
6031 "Run through the buffer and add overlays to dates."
6032 (if (and (re-search-forward org-tsr-regexp-both limit t)
6033 (not (equal (char-before (match-beginning 0)) 91)))
6034 (progn
6035 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6036 (add-text-properties (match-beginning 0) (match-end 0)
6037 (list 'mouse-face 'highlight
6038 'keymap org-mouse-map))
6039 (org-rear-nonsticky-at (match-end 0))
6040 (when org-display-custom-times
6041 (if (match-end 3)
6042 (org-display-custom-time (match-beginning 3) (match-end 3)))
6043 (org-display-custom-time (match-beginning 1) (match-end 1)))
6044 t)))
6046 (defvar org-target-link-regexp nil
6047 "Regular expression matching radio targets in plain text.")
6048 (make-variable-buffer-local 'org-target-link-regexp)
6049 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
6050 "Regular expression matching a link target.")
6051 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
6052 "Regular expression matching a radio target.")
6053 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
6054 "Regular expression matching any target.")
6056 (defun org-activate-target-links (limit)
6057 "Run through the buffer and add overlays to target matches."
6058 (when org-target-link-regexp
6059 (let ((case-fold-search t))
6060 (if (re-search-forward org-target-link-regexp limit t)
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 'help-echo "Radio target link"
6067 'org-linked-text t))
6068 (org-rear-nonsticky-at (match-end 0))
6069 t)))))
6071 (defun org-update-radio-target-regexp ()
6072 "Find all radio targets in this file and update the regular expression."
6073 (interactive)
6074 (when (memq 'radio org-activate-links)
6075 (setq org-target-link-regexp
6076 (org-make-target-link-regexp (org-all-targets 'radio)))
6077 (org-restart-font-lock)))
6079 (defun org-hide-wide-columns (limit)
6080 (let (s e)
6081 (setq s (text-property-any (point) (or limit (point-max))
6082 'org-cwidth t))
6083 (when s
6084 (setq e (next-single-property-change s 'org-cwidth))
6085 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6086 (goto-char e)
6087 t)))
6089 (defvar org-latex-and-related-regexp nil
6090 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6091 (defvar org-match-substring-regexp)
6092 (defvar org-match-substring-with-braces-regexp)
6094 (defun org-compute-latex-and-related-regexp ()
6095 "Compute regular expression for LaTeX, entities and sub/superscript.
6096 Result depends on variable `org-highlight-latex-and-related'."
6097 (org-set-local
6098 'org-latex-and-related-regexp
6099 (let* ((re-sub
6100 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6101 ((eq org-use-sub-superscripts '{})
6102 (list org-match-substring-with-braces-regexp))
6103 (org-use-sub-superscripts (list org-match-substring-regexp))))
6104 (re-latex
6105 (when (memq 'latex org-highlight-latex-and-related)
6106 (let ((matchers (plist-get org-format-latex-options :matchers)))
6107 (delq nil
6108 (mapcar (lambda (x)
6109 (and (member (car x) matchers) (nth 1 x)))
6110 org-latex-regexps)))))
6111 (re-entities
6112 (when (memq 'entities org-highlight-latex-and-related)
6113 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6114 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6116 (defun org-do-latex-and-related (limit)
6117 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6118 LIMIT bounds the search for syntax to highlight. Stop at first
6119 highlighted object, if any. Return t if some highlighting was
6120 done, nil otherwise."
6121 (when (org-string-nw-p org-latex-and-related-regexp)
6122 (catch 'found
6123 (while (re-search-forward org-latex-and-related-regexp limit t)
6124 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6125 'face))
6126 '(org-code org-verbatim underline))
6127 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6128 '(?_ ?^))
6130 0)))
6131 (font-lock-prepend-text-property
6132 (+ offset (match-beginning 0)) (match-end 0)
6133 'face 'org-latex-and-related)
6134 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6135 '(font-lock-multiline t)))
6136 (throw 'found t)))
6137 nil)))
6139 (defun org-restart-font-lock ()
6140 "Restart `font-lock-mode', to force refontification."
6141 (when (and (boundp 'font-lock-mode) font-lock-mode)
6142 (font-lock-mode -1)
6143 (font-lock-mode 1)))
6145 (defun org-all-targets (&optional radio)
6146 "Return a list of all targets in this file.
6147 When optional argument RADIO is non-nil, only find radio
6148 targets."
6149 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
6150 (save-excursion
6151 (goto-char (point-min))
6152 (while (re-search-forward re nil t)
6153 ;; Make sure point is really within the object.
6154 (backward-char)
6155 (let ((obj (org-element-context)))
6156 (when (memq (org-element-type obj) '(radio-target target))
6157 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
6158 rtn)))
6160 (defun org-make-target-link-regexp (targets)
6161 "Make regular expression matching all strings in TARGETS.
6162 The regular expression finds the targets also if there is a line break
6163 between words."
6164 (and targets
6165 (concat
6166 "\\<\\("
6167 (mapconcat
6168 (lambda (x)
6169 (setq x (regexp-quote x))
6170 (while (string-match " +" x)
6171 (setq x (replace-match "\\s-+" t t x)))
6173 targets
6174 "\\|")
6175 "\\)\\>")))
6177 (defun org-activate-tags (limit)
6178 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6179 (progn
6180 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6181 (add-text-properties (match-beginning 1) (match-end 1)
6182 (list 'mouse-face 'highlight
6183 'keymap org-mouse-map))
6184 (org-rear-nonsticky-at (match-end 1))
6185 t)))
6187 (defun org-outline-level ()
6188 "Compute the outline level of the heading at point.
6189 If this is called at a normal headline, the level is the number of stars.
6190 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6191 (save-excursion
6192 (if (not (condition-case nil
6193 (org-back-to-heading t)
6194 (error nil)))
6196 (looking-at org-outline-regexp)
6197 (1- (- (match-end 0) (match-beginning 0))))))
6199 (defvar org-font-lock-keywords nil)
6201 (defsubst org-re-property (property &optional literal)
6202 "Return a regexp matching a PROPERTY line.
6203 Match group 3 will be set to the value if it exists."
6204 (concat "^\\(?4:[ \t]*\\)\\(?1::\\(?2:"
6205 (if literal property (regexp-quote property))
6206 "\\):\\)[ \t]+\\(?3:[^ \t\r\n].*?\\)\\(?5:[ \t]*\\)$"))
6208 (defconst org-property-re
6209 (org-re-property ".*?" 'literal)
6210 "Regular expression matching a property line.
6211 There are four matching groups:
6212 1: :PROPKEY: including the leading and trailing colon,
6213 2: PROPKEY without the leading and trailing colon,
6214 3: PROPVAL without leading or trailing spaces,
6215 4: the indentation of the current line,
6216 5: trailing whitespace.")
6218 (defvar org-font-lock-hook nil
6219 "Functions to be called for special font lock stuff.")
6221 (defvar org-font-lock-set-keywords-hook nil
6222 "Functions that can manipulate `org-font-lock-extra-keywords'.
6223 This is called after `org-font-lock-extra-keywords' is defined, but before
6224 it is installed to be used by font lock. This can be useful if something
6225 needs to be inserted at a specific position in the font-lock sequence.")
6227 (defun org-font-lock-hook (limit)
6228 "Run `org-font-lock-hook' within LIMIT."
6229 (run-hook-with-args 'org-font-lock-hook limit))
6231 (defun org-set-font-lock-defaults ()
6232 "Set font lock defaults for the current buffer."
6233 (let* ((em org-fontify-emphasized-text)
6234 (lk org-activate-links)
6235 (org-font-lock-extra-keywords
6236 (list
6237 ;; Call the hook
6238 '(org-font-lock-hook)
6239 ;; Headlines
6240 `(,(if org-fontify-whole-heading-line
6241 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6242 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6243 (1 (org-get-level-face 1))
6244 (2 (org-get-level-face 2))
6245 (3 (org-get-level-face 3)))
6246 ;; Table lines
6247 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6248 (1 'org-table t))
6249 ;; Table internals
6250 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6251 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6252 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6253 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6254 ;; Drawers
6255 '(org-fontify-drawers)
6256 ;; Properties
6257 (list org-property-re
6258 '(1 'org-special-keyword t)
6259 '(3 'org-property-value t))
6260 ;; Links
6261 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6262 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6263 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6264 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6265 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6266 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6267 (if (memq 'footnote lk) '(org-activate-footnote-links))
6268 ;; Targets.
6269 (list org-any-target-regexp '(0 'org-target t))
6270 ;; Diary sexps.
6271 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6272 ;; Macro
6273 '("{{{.+?}}}" (0 'org-macro t))
6274 '(org-hide-wide-columns (0 nil append))
6275 ;; TODO keyword
6276 (list (format org-heading-keyword-regexp-format
6277 org-todo-regexp)
6278 '(2 (org-get-todo-face 2) t))
6279 ;; DONE
6280 (if org-fontify-done-headline
6281 (list (format org-heading-keyword-regexp-format
6282 (concat
6283 "\\(?:"
6284 (mapconcat 'regexp-quote org-done-keywords "\\|")
6285 "\\)"))
6286 '(2 'org-headline-done t))
6287 nil)
6288 ;; Priorities
6289 '(org-font-lock-add-priority-faces)
6290 ;; Tags
6291 '(org-font-lock-add-tag-faces)
6292 ;; Tags groups
6293 (if (and org-group-tags org-tag-groups-alist)
6294 (list (concat org-outline-regexp-bol ".+\\(:"
6295 (regexp-opt (mapcar 'car org-tag-groups-alist))
6296 ":\\).*$")
6297 '(1 'org-tag-group prepend)))
6298 ;; Special keywords
6299 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6300 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6301 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6302 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6303 ;; Emphasis
6304 (if em
6305 (if (featurep 'xemacs)
6306 '(org-do-emphasis-faces (0 nil append))
6307 '(org-do-emphasis-faces)))
6308 ;; Checkboxes
6309 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6310 1 'org-checkbox prepend)
6311 (if (cdr (assq 'checkbox org-list-automatic-rules))
6312 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6313 (0 (org-get-checkbox-statistics-face) t)))
6314 ;; Description list items
6315 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6316 1 'org-list-dt prepend)
6317 ;; ARCHIVEd headings
6318 (list (concat
6319 org-outline-regexp-bol
6320 "\\(.*:" org-archive-tag ":.*\\)")
6321 '(1 'org-archived prepend))
6322 ;; Specials
6323 '(org-do-latex-and-related)
6324 '(org-fontify-entities)
6325 '(org-raise-scripts)
6326 ;; Code
6327 '(org-activate-code (1 'org-code t))
6328 ;; COMMENT
6329 (list (format org-heading-keyword-regexp-format
6330 (concat "\\("
6331 org-comment-string "\\|" org-quote-string
6332 "\\)"))
6333 '(2 'org-special-keyword t))
6334 ;; Blocks and meta lines
6335 '(org-fontify-meta-lines-and-blocks))))
6336 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6337 (run-hooks 'org-font-lock-set-keywords-hook)
6338 ;; Now set the full font-lock-keywords
6339 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6340 (org-set-local 'font-lock-defaults
6341 '(org-font-lock-keywords t nil nil backward-paragraph))
6342 (kill-local-variable 'font-lock-keywords) nil))
6344 (defun org-toggle-pretty-entities ()
6345 "Toggle the composition display of entities as UTF8 characters."
6346 (interactive)
6347 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6348 (org-restart-font-lock)
6349 (if org-pretty-entities
6350 (message "Entities are now displayed as UTF8 characters")
6351 (save-restriction
6352 (widen)
6353 (org-decompose-region (point-min) (point-max))
6354 (message "Entities are now displayed as plain text"))))
6356 (defvar org-custom-properties-overlays nil
6357 "List of overlays used for custom properties.")
6358 (make-variable-buffer-local 'org-custom-properties-overlays)
6360 (defun org-toggle-custom-properties-visibility ()
6361 "Display or hide properties in `org-custom-properties'."
6362 (interactive)
6363 (if org-custom-properties-overlays
6364 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6365 (setq org-custom-properties-overlays nil))
6366 (unless (not org-custom-properties)
6367 (save-excursion
6368 (save-restriction
6369 (widen)
6370 (goto-char (point-min))
6371 (while (re-search-forward org-property-re nil t)
6372 (mapc (lambda(p)
6373 (when (equal p (substring (match-string 1) 1 -1))
6374 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6375 (overlay-put o 'invisible t)
6376 (overlay-put o 'org-custom-property t)
6377 (push o org-custom-properties-overlays))))
6378 org-custom-properties)))))))
6380 (defun org-fontify-entities (limit)
6381 "Find an entity to fontify."
6382 (let (ee)
6383 (when org-pretty-entities
6384 (catch 'match
6385 (while (re-search-forward
6386 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6387 limit t)
6388 (if (and (not (org-in-indented-comment-line))
6389 (setq ee (org-entity-get (match-string 1)))
6390 (= (length (nth 6 ee)) 1))
6391 (let*
6392 ((end (if (equal (match-string 2) "{}")
6393 (match-end 2)
6394 (match-end 1))))
6395 (add-text-properties
6396 (match-beginning 0) end
6397 (list 'font-lock-fontified t))
6398 (compose-region (match-beginning 0) end
6399 (nth 6 ee) nil)
6400 (backward-char 1)
6401 (throw 'match t))))
6402 nil))))
6404 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6405 "Fontify string S like in Org-mode."
6406 (with-temp-buffer
6407 (insert s)
6408 (let ((org-odd-levels-only odd-levels))
6409 (org-mode)
6410 (font-lock-fontify-buffer)
6411 (buffer-string))))
6413 (defvar org-m nil)
6414 (defvar org-l nil)
6415 (defvar org-f nil)
6416 (defun org-get-level-face (n)
6417 "Get the right face for match N in font-lock matching of headlines."
6418 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6419 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6420 (if org-cycle-level-faces
6421 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6422 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6423 (cond
6424 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6425 ((eq n 2) org-f)
6426 (t (if org-level-color-stars-only nil org-f))))
6429 (defun org-get-todo-face (kwd)
6430 "Get the right face for a TODO keyword KWD.
6431 If KWD is a number, get the corresponding match group."
6432 (if (numberp kwd) (setq kwd (match-string kwd)))
6433 (or (org-face-from-face-or-color
6434 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6435 (and (member kwd org-done-keywords) 'org-done)
6436 'org-todo))
6438 (defun org-face-from-face-or-color (context inherit face-or-color)
6439 "Create a face list that inherits INHERIT, but sets the foreground color.
6440 When FACE-OR-COLOR is not a string, just return it."
6441 (if (stringp face-or-color)
6442 (list :inherit inherit
6443 (cdr (assoc context org-faces-easy-properties))
6444 face-or-color)
6445 face-or-color))
6447 (defun org-font-lock-add-tag-faces (limit)
6448 "Add the special tag faces."
6449 (when (and org-tag-faces org-tags-special-faces-re)
6450 (while (re-search-forward org-tags-special-faces-re limit t)
6451 (add-text-properties (match-beginning 1) (match-end 1)
6452 (list 'face (org-get-tag-face 1)
6453 'font-lock-fontified t))
6454 (backward-char 1))))
6456 (defun org-font-lock-add-priority-faces (limit)
6457 "Add the special priority faces."
6458 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6459 (when (save-match-data (org-at-heading-p))
6460 (add-text-properties
6461 (match-beginning 0) (match-end 0)
6462 (list 'face (or (org-face-from-face-or-color
6463 'priority 'org-priority
6464 (cdr (assoc (char-after (match-beginning 1))
6465 org-priority-faces)))
6466 'org-priority)
6467 'font-lock-fontified t)))))
6469 (defun org-get-tag-face (kwd)
6470 "Get the right face for a TODO keyword KWD.
6471 If KWD is a number, get the corresponding match group."
6472 (if (numberp kwd) (setq kwd (match-string kwd)))
6473 (or (org-face-from-face-or-color
6474 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6475 'org-tag))
6477 (defun org-unfontify-region (beg end &optional maybe_loudly)
6478 "Remove fontification and activation overlays from links."
6479 (font-lock-default-unfontify-region beg end)
6480 (let* ((buffer-undo-list t)
6481 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6482 (inhibit-modification-hooks t)
6483 deactivate-mark buffer-file-name buffer-file-truename)
6484 (org-decompose-region beg end)
6485 (remove-text-properties beg end
6486 '(mouse-face t keymap t org-linked-text t
6487 invisible t intangible t
6488 org-emphasis t))
6489 (org-remove-font-lock-display-properties beg end)))
6491 (defconst org-script-display '(((raise -0.3) (height 0.7))
6492 ((raise 0.3) (height 0.7))
6493 ((raise -0.5))
6494 ((raise 0.5)))
6495 "Display properties for showing superscripts and subscripts.")
6497 (defun org-remove-font-lock-display-properties (beg end)
6498 "Remove specific display properties that have been added by font lock.
6499 The will remove the raise properties that are used to show superscripts
6500 and subscripts."
6501 (let (next prop)
6502 (while (< beg end)
6503 (setq next (next-single-property-change beg 'display nil end)
6504 prop (get-text-property beg 'display))
6505 (if (member prop org-script-display)
6506 (put-text-property beg next 'display nil))
6507 (setq beg next))))
6509 (defun org-raise-scripts (limit)
6510 "Add raise properties to sub/superscripts."
6511 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6512 (if (re-search-forward
6513 (if (eq org-use-sub-superscripts t)
6514 org-match-substring-regexp
6515 org-match-substring-with-braces-regexp)
6516 limit t)
6517 (let* ((pos (point)) table-p comment-p
6518 (mpos (match-beginning 3))
6519 (emph-p (get-text-property mpos 'org-emphasis))
6520 (link-p (get-text-property mpos 'mouse-face))
6521 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6522 (goto-char (point-at-bol))
6523 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6524 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6525 (goto-char pos)
6526 ;; Handle a_b^c
6527 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6528 (if (or comment-p emph-p link-p keyw-p)
6530 (put-text-property (match-beginning 3) (match-end 0)
6531 'display
6532 (if (equal (char-after (match-beginning 2)) ?^)
6533 (nth (if table-p 3 1) org-script-display)
6534 (nth (if table-p 2 0) org-script-display)))
6535 (add-text-properties (match-beginning 2) (match-end 2)
6536 (list 'invisible t
6537 'org-dwidth t 'org-dwidth-n 1))
6538 (if (and (eq (char-after (match-beginning 3)) ?{)
6539 (eq (char-before (match-end 3)) ?}))
6540 (progn
6541 (add-text-properties
6542 (match-beginning 3) (1+ (match-beginning 3))
6543 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6544 (add-text-properties
6545 (1- (match-end 3)) (match-end 3)
6546 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6547 t)))))
6549 ;;;; Visibility cycling, including org-goto and indirect buffer
6551 ;;; Cycling
6553 (defvar org-cycle-global-status nil)
6554 (make-variable-buffer-local 'org-cycle-global-status)
6555 (put 'org-cycle-global-status 'org-state t)
6556 (defvar org-cycle-subtree-status nil)
6557 (make-variable-buffer-local 'org-cycle-subtree-status)
6558 (put 'org-cycle-subtree-status 'org-state t)
6560 (defvar org-inlinetask-min-level)
6562 (defun org-unlogged-message (&rest args)
6563 "Display a message, but avoid logging it in the *Messages* buffer."
6564 (let ((message-log-max nil))
6565 (apply 'message args)))
6567 ;;;###autoload
6568 (defun org-cycle (&optional arg)
6569 "TAB-action and visibility cycling for Org-mode.
6571 This is the command invoked in Org-mode by the TAB key. Its main purpose
6572 is outline visibility cycling, but it also invokes other actions
6573 in special contexts.
6575 - When this function is called with a prefix argument, rotate the entire
6576 buffer through 3 states (global cycling)
6577 1. OVERVIEW: Show only top-level headlines.
6578 2. CONTENTS: Show all headlines of all levels, but no body text.
6579 3. SHOW ALL: Show everything.
6580 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6581 determined by the variable `org-startup-folded', and by any VISIBILITY
6582 properties in the buffer.
6583 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6584 including any drawers.
6586 - When inside a table, re-align the table and move to the next field.
6588 - When point is at the beginning of a headline, rotate the subtree started
6589 by this line through 3 different states (local cycling)
6590 1. FOLDED: Only the main headline is shown.
6591 2. CHILDREN: The main headline and the direct children are shown.
6592 From this state, you can move to one of the children
6593 and zoom in further.
6594 3. SUBTREE: Show the entire subtree, including body text.
6595 If there is no subtree, switch directly from CHILDREN to FOLDED.
6597 - When point is at the beginning of an empty headline and the variable
6598 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6599 of the headline by demoting and promoting it to likely levels. This
6600 speeds up creation document structure by pressing TAB once or several
6601 times right after creating a new headline.
6603 - When there is a numeric prefix, go up to a heading with level ARG, do
6604 a `show-subtree' and return to the previous cursor position. If ARG
6605 is negative, go up that many levels.
6607 - When point is not at the beginning of a headline, execute the global
6608 binding for TAB, which is re-indenting the line. See the option
6609 `org-cycle-emulate-tab' for details.
6611 - Special case: if point is at the beginning of the buffer and there is
6612 no headline in line 1, this function will act as if called with prefix arg
6613 (C-u TAB, same as S-TAB) also when called without prefix arg.
6614 But only if also the variable `org-cycle-global-at-bob' is t."
6615 (interactive "P")
6616 (org-load-modules-maybe)
6617 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6618 (and org-cycle-level-after-item/entry-creation
6619 (or (org-cycle-level)
6620 (org-cycle-item-indentation))))
6621 (let* ((limit-level
6622 (or org-cycle-max-level
6623 (and (boundp 'org-inlinetask-min-level)
6624 org-inlinetask-min-level
6625 (1- org-inlinetask-min-level))))
6626 (nstars (and limit-level
6627 (if org-odd-levels-only
6628 (and limit-level (1- (* limit-level 2)))
6629 limit-level)))
6630 (org-outline-regexp
6631 (if (not (derived-mode-p 'org-mode))
6632 outline-regexp
6633 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6634 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6635 (not (looking-at org-outline-regexp))))
6636 (org-cycle-hook
6637 (if bob-special
6638 (delq 'org-optimize-window-after-visibility-change
6639 (copy-sequence org-cycle-hook))
6640 org-cycle-hook))
6641 (pos (point)))
6643 (if (or bob-special (equal arg '(4)))
6644 ;; special case: use global cycling
6645 (setq arg t))
6647 (cond
6649 ((equal arg '(16))
6650 (setq last-command 'dummy)
6651 (org-set-startup-visibility)
6652 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6654 ((equal arg '(64))
6655 (show-all)
6656 (org-unlogged-message "Entire buffer visible, including drawers"))
6658 ;; Table: enter it or move to the next field.
6659 ((org-at-table-p 'any)
6660 (if (org-at-table.el-p)
6661 (message "Use C-c ' to edit table.el tables")
6662 (if arg (org-table-edit-field t)
6663 (org-table-justify-field-maybe)
6664 (call-interactively 'org-table-next-field))))
6666 ((run-hook-with-args-until-success
6667 'org-tab-after-check-for-table-hook))
6669 ;; Global cycling: delegate to `org-cycle-internal-global'.
6670 ((eq arg t) (org-cycle-internal-global))
6672 ;; Drawers: delegate to `org-flag-drawer'.
6673 ((save-excursion
6674 (beginning-of-line 1)
6675 (looking-at org-drawer-regexp))
6676 (org-flag-drawer ; toggle block visibility
6677 (not (get-char-property (match-end 0) 'invisible))))
6679 ;; Show-subtree, ARG levels up from here.
6680 ((integerp arg)
6681 (save-excursion
6682 (org-back-to-heading)
6683 (outline-up-heading (if (< arg 0) (- arg)
6684 (- (funcall outline-level) arg)))
6685 (org-show-subtree)))
6687 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6688 ((and (featurep 'org-inlinetask)
6689 (org-inlinetask-at-task-p)
6690 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6691 (org-inlinetask-toggle-visibility))
6693 ((org-try-cdlatex-tab))
6695 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6696 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6697 (save-excursion (beginning-of-line 1)
6698 (looking-at org-outline-regexp)))
6699 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6700 (org-cycle-internal-local))
6702 ;; From there: TAB emulation and template completion.
6703 (buffer-read-only (org-back-to-heading))
6705 ((run-hook-with-args-until-success
6706 'org-tab-after-check-for-cycling-hook))
6708 ((org-try-structure-completion))
6710 ((run-hook-with-args-until-success
6711 'org-tab-before-tab-emulation-hook))
6713 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6714 (or (not (bolp))
6715 (not (looking-at org-outline-regexp))))
6716 (call-interactively (global-key-binding "\t")))
6718 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6719 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6720 (or (and (eq org-cycle-emulate-tab 'white)
6721 (= (match-end 0) (point-at-eol)))
6722 (and (eq org-cycle-emulate-tab 'whitestart)
6723 (>= (match-end 0) pos))))
6725 (eq org-cycle-emulate-tab t))
6726 (call-interactively (global-key-binding "\t")))
6728 (t (save-excursion
6729 (org-back-to-heading)
6730 (org-cycle)))))))
6732 (defun org-cycle-internal-global ()
6733 "Do the global cycling action."
6734 ;; Hack to avoid display of messages for .org attachments in Gnus
6735 (let ((ga (string-match "\\*fontification" (buffer-name))))
6736 (cond
6737 ((and (eq last-command this-command)
6738 (eq org-cycle-global-status 'overview))
6739 ;; We just created the overview - now do table of contents
6740 ;; This can be slow in very large buffers, so indicate action
6741 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6742 (unless ga (org-unlogged-message "CONTENTS..."))
6743 (org-content)
6744 (unless ga (org-unlogged-message "CONTENTS...done"))
6745 (setq org-cycle-global-status 'contents)
6746 (run-hook-with-args 'org-cycle-hook 'contents))
6748 ((and (eq last-command this-command)
6749 (eq org-cycle-global-status 'contents))
6750 ;; We just showed the table of contents - now show everything
6751 (run-hook-with-args 'org-pre-cycle-hook 'all)
6752 (show-all)
6753 (unless ga (org-unlogged-message "SHOW ALL"))
6754 (setq org-cycle-global-status 'all)
6755 (run-hook-with-args 'org-cycle-hook 'all))
6758 ;; Default action: go to overview
6759 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6760 (org-overview)
6761 (unless ga (org-unlogged-message "OVERVIEW"))
6762 (setq org-cycle-global-status 'overview)
6763 (run-hook-with-args 'org-cycle-hook 'overview)))))
6765 (defvar org-called-with-limited-levels);Dyn-bound in ̀org-with-limited-levels'.
6767 (defun org-cycle-internal-local ()
6768 "Do the local cycling action."
6769 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6770 ;; First, determine end of headline (EOH), end of subtree or item
6771 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6772 (save-excursion
6773 (if (org-at-item-p)
6774 (progn
6775 (beginning-of-line)
6776 (setq struct (org-list-struct))
6777 (setq eoh (point-at-eol))
6778 (setq eos (org-list-get-item-end-before-blank (point) struct))
6779 (setq has-children (org-list-has-child-p (point) struct)))
6780 (org-back-to-heading)
6781 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6782 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6783 (setq has-children
6784 (or (save-excursion
6785 (let ((level (funcall outline-level)))
6786 (outline-next-heading)
6787 (and (org-at-heading-p t)
6788 (> (funcall outline-level) level))))
6789 (save-excursion
6790 (org-list-search-forward (org-item-beginning-re) eos t)))))
6791 ;; Determine end invisible part of buffer (EOL)
6792 (beginning-of-line 2)
6793 ;; XEmacs doesn't have `next-single-char-property-change'
6794 (if (featurep 'xemacs)
6795 (while (and (not (eobp)) ;; this is like `next-line'
6796 (get-char-property (1- (point)) 'invisible))
6797 (beginning-of-line 2))
6798 (while (and (not (eobp)) ;; this is like `next-line'
6799 (get-char-property (1- (point)) 'invisible))
6800 (goto-char (next-single-char-property-change (point) 'invisible))
6801 (and (eolp) (beginning-of-line 2))))
6802 (setq eol (point)))
6803 ;; Find out what to do next and set `this-command'
6804 (cond
6805 ((= eos eoh)
6806 ;; Nothing is hidden behind this heading
6807 (unless (org-before-first-heading-p)
6808 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6809 (org-unlogged-message "EMPTY ENTRY")
6810 (setq org-cycle-subtree-status nil)
6811 (save-excursion
6812 (goto-char eos)
6813 (outline-next-heading)
6814 (if (outline-invisible-p) (org-flag-heading nil))))
6815 ((and (or (>= eol eos)
6816 (not (string-match "\\S-" (buffer-substring eol eos))))
6817 (or has-children
6818 (not (setq children-skipped
6819 org-cycle-skip-children-state-if-no-children))))
6820 ;; Entire subtree is hidden in one line: children view
6821 (unless (org-before-first-heading-p)
6822 (run-hook-with-args 'org-pre-cycle-hook 'children))
6823 (if (org-at-item-p)
6824 (org-list-set-item-visibility (point-at-bol) struct 'children)
6825 (org-show-entry)
6826 (org-with-limited-levels (show-children))
6827 ;; FIXME: This slows down the func way too much.
6828 ;; How keep drawers hidden in subtree anyway?
6829 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6830 ;; (org-cycle-hide-drawers 'subtree))
6832 ;; Fold every list in subtree to top-level items.
6833 (when (eq org-cycle-include-plain-lists 'integrate)
6834 (save-excursion
6835 (org-back-to-heading)
6836 (while (org-list-search-forward (org-item-beginning-re) eos t)
6837 (beginning-of-line 1)
6838 (let* ((struct (org-list-struct))
6839 (prevs (org-list-prevs-alist struct))
6840 (end (org-list-get-bottom-point struct)))
6841 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6842 (org-list-get-all-items (point) struct prevs))
6843 (goto-char (if (< end eos) end eos)))))))
6844 (org-unlogged-message "CHILDREN")
6845 (save-excursion
6846 (goto-char eos)
6847 (outline-next-heading)
6848 (if (outline-invisible-p) (org-flag-heading nil)))
6849 (setq org-cycle-subtree-status 'children)
6850 (unless (org-before-first-heading-p)
6851 (run-hook-with-args 'org-cycle-hook 'children)))
6852 ((or children-skipped
6853 (and (eq last-command this-command)
6854 (eq org-cycle-subtree-status 'children)))
6855 ;; We just showed the children, or no children are there,
6856 ;; now show everything.
6857 (unless (org-before-first-heading-p)
6858 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6859 (outline-flag-region eoh eos nil)
6860 (org-unlogged-message
6861 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6862 (setq org-cycle-subtree-status 'subtree)
6863 (unless (org-before-first-heading-p)
6864 (run-hook-with-args 'org-cycle-hook 'subtree)))
6866 ;; Default action: hide the subtree.
6867 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6868 (outline-flag-region eoh eos t)
6869 (org-unlogged-message "FOLDED")
6870 (setq org-cycle-subtree-status 'folded)
6871 (unless (org-before-first-heading-p)
6872 (run-hook-with-args 'org-cycle-hook 'folded))))))
6874 ;;;###autoload
6875 (defun org-global-cycle (&optional arg)
6876 "Cycle the global visibility. For details see `org-cycle'.
6877 With \\[universal-argument] prefix arg, switch to startup visibility.
6878 With a numeric prefix, show all headlines up to that level."
6879 (interactive "P")
6880 (let ((org-cycle-include-plain-lists
6881 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6882 (cond
6883 ((integerp arg)
6884 (show-all)
6885 (hide-sublevels arg)
6886 (setq org-cycle-global-status 'contents))
6887 ((equal arg '(4))
6888 (org-set-startup-visibility)
6889 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6891 (org-cycle '(4))))))
6893 (defun org-set-startup-visibility ()
6894 "Set the visibility required by startup options and properties."
6895 (cond
6896 ((eq org-startup-folded t)
6897 (org-overview))
6898 ((eq org-startup-folded 'content)
6899 (org-content))
6900 ((or (eq org-startup-folded 'showeverything)
6901 (eq org-startup-folded nil))
6902 (show-all)))
6903 (unless (eq org-startup-folded 'showeverything)
6904 (if org-hide-block-startup (org-hide-block-all))
6905 (org-set-visibility-according-to-property 'no-cleanup)
6906 (org-cycle-hide-archived-subtrees 'all)
6907 (org-cycle-hide-drawers 'all)
6908 (org-cycle-show-empty-lines t)))
6910 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6911 "Switch subtree visibilities according to :VISIBILITY: property."
6912 (interactive)
6913 (let (org-show-entry-below state)
6914 (save-excursion
6915 (goto-char (point-min))
6916 (while (re-search-forward
6917 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6918 nil t)
6919 (setq state (match-string 1))
6920 (save-excursion
6921 (org-back-to-heading t)
6922 (hide-subtree)
6923 (org-reveal)
6924 (cond
6925 ((equal state '("fold" "folded"))
6926 (hide-subtree))
6927 ((equal state "children")
6928 (org-show-hidden-entry)
6929 (show-children))
6930 ((equal state "content")
6931 (save-excursion
6932 (save-restriction
6933 (org-narrow-to-subtree)
6934 (org-content))))
6935 ((member state '("all" "showall"))
6936 (show-subtree)))))
6937 (unless no-cleanup
6938 (org-cycle-hide-archived-subtrees 'all)
6939 (org-cycle-hide-drawers 'all)
6940 (org-cycle-show-empty-lines 'all)))))
6942 ;; This function uses outline-regexp instead of the more fundamental
6943 ;; org-outline-regexp so that org-cycle-global works outside of Org
6944 ;; buffers, where outline-regexp is needed.
6945 (defun org-overview ()
6946 "Switch to overview mode, showing only top-level headlines.
6947 Really, this shows all headlines with level equal or greater than the level
6948 of the first headline in the buffer. This is important, because if the
6949 first headline is not level one, then (hide-sublevels 1) gives confusing
6950 results."
6951 (interactive)
6952 (let ((pos (point))
6953 (level (save-excursion
6954 (goto-char (point-min))
6955 (if (re-search-forward (concat "^" outline-regexp) nil t)
6956 (progn
6957 (goto-char (match-beginning 0))
6958 (funcall outline-level))))))
6959 (and level (hide-sublevels level))
6960 (recenter '(4))
6961 (goto-char pos)))
6963 (defun org-content (&optional arg)
6964 "Show all headlines in the buffer, like a table of contents.
6965 With numerical argument N, show content up to level N."
6966 (interactive "P")
6967 (save-excursion
6968 ;; Visit all headings and show their offspring
6969 (and (integerp arg) (org-overview))
6970 (goto-char (point-max))
6971 (catch 'exit
6972 (while (and (progn (condition-case nil
6973 (outline-previous-visible-heading 1)
6974 (error (goto-char (point-min))))
6976 (looking-at org-outline-regexp))
6977 (if (integerp arg)
6978 (show-children (1- arg))
6979 (show-branches))
6980 (if (bobp) (throw 'exit nil))))))
6982 (defun org-optimize-window-after-visibility-change (state)
6983 "Adjust the window after a change in outline visibility.
6984 This function is the default value of the hook `org-cycle-hook'."
6985 (when (get-buffer-window (current-buffer))
6986 (cond
6987 ((eq state 'content) nil)
6988 ((eq state 'all) nil)
6989 ((eq state 'folded) nil)
6990 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6991 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6993 (defun org-remove-empty-overlays-at (pos)
6994 "Remove outline overlays that do not contain non-white stuff."
6995 (mapc
6996 (lambda (o)
6997 (and (eq 'outline (overlay-get o 'invisible))
6998 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6999 (overlay-end o))))
7000 (delete-overlay o)))
7001 (overlays-at pos)))
7003 (defun org-clean-visibility-after-subtree-move ()
7004 "Fix visibility issues after moving a subtree."
7005 ;; First, find a reasonable region to look at:
7006 ;; Start two siblings above, end three below
7007 (let* ((beg (save-excursion
7008 (and (org-get-last-sibling)
7009 (org-get-last-sibling))
7010 (point)))
7011 (end (save-excursion
7012 (and (org-get-next-sibling)
7013 (org-get-next-sibling)
7014 (org-get-next-sibling))
7015 (if (org-at-heading-p)
7016 (point-at-eol)
7017 (point))))
7018 (level (looking-at "\\*+"))
7019 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
7020 (save-excursion
7021 (save-restriction
7022 (narrow-to-region beg end)
7023 (when re
7024 ;; Properly fold already folded siblings
7025 (goto-char (point-min))
7026 (while (re-search-forward re nil t)
7027 (if (and (not (outline-invisible-p))
7028 (save-excursion
7029 (goto-char (point-at-eol)) (outline-invisible-p)))
7030 (hide-entry))))
7031 (org-cycle-show-empty-lines 'overview)
7032 (org-cycle-hide-drawers 'overview)))))
7034 (defun org-cycle-show-empty-lines (state)
7035 "Show empty lines above all visible headlines.
7036 The region to be covered depends on STATE when called through
7037 `org-cycle-hook'. Lisp program can use t for STATE to get the
7038 entire buffer covered. Note that an empty line is only shown if there
7039 are at least `org-cycle-separator-lines' empty lines before the headline."
7040 (when (not (= org-cycle-separator-lines 0))
7041 (save-excursion
7042 (let* ((n (abs org-cycle-separator-lines))
7043 (re (cond
7044 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7045 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7046 (t (let ((ns (number-to-string (- n 2))))
7047 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7048 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7049 beg end b e)
7050 (cond
7051 ((memq state '(overview contents t))
7052 (setq beg (point-min) end (point-max)))
7053 ((memq state '(children folded))
7054 (setq beg (point) end (progn (org-end-of-subtree t t)
7055 (beginning-of-line 2)
7056 (point)))))
7057 (when beg
7058 (goto-char beg)
7059 (while (re-search-forward re end t)
7060 (unless (get-char-property (match-end 1) 'invisible)
7061 (setq e (match-end 1))
7062 (if (< org-cycle-separator-lines 0)
7063 (setq b (save-excursion
7064 (goto-char (match-beginning 0))
7065 (org-back-over-empty-lines)
7066 (if (save-excursion
7067 (goto-char (max (point-min) (1- (point))))
7068 (org-at-heading-p))
7069 (1- (point))
7070 (point))))
7071 (setq b (match-beginning 1)))
7072 (outline-flag-region b e nil)))))))
7073 ;; Never hide empty lines at the end of the file.
7074 (save-excursion
7075 (goto-char (point-max))
7076 (outline-previous-heading)
7077 (outline-end-of-heading)
7078 (if (and (looking-at "[ \t\n]+")
7079 (= (match-end 0) (point-max)))
7080 (outline-flag-region (point) (match-end 0) nil))))
7082 (defun org-show-empty-lines-in-parent ()
7083 "Move to the parent and re-show empty lines before visible headlines."
7084 (save-excursion
7085 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7086 (org-cycle-show-empty-lines context))))
7088 (defun org-files-list ()
7089 "Return `org-agenda-files' list, plus all open org-mode files.
7090 This is useful for operations that need to scan all of a user's
7091 open and agenda-wise Org files."
7092 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7093 (dolist (buf (buffer-list))
7094 (with-current-buffer buf
7095 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7096 (let ((file (expand-file-name (buffer-file-name))))
7097 (unless (member file files)
7098 (push file files))))))
7099 files))
7101 (defsubst org-entry-beginning-position ()
7102 "Return the beginning position of the current entry."
7103 (save-excursion (outline-back-to-heading t) (point)))
7105 (defsubst org-entry-end-position ()
7106 "Return the end position of the current entry."
7107 (save-excursion (outline-next-heading) (point)))
7109 (defun org-cycle-hide-drawers (state &optional exceptions)
7110 "Re-hide all drawers after a visibility state change.
7111 When non-nil, optional argument EXCEPTIONS is a list of strings
7112 specifying which drawers should not be hidden."
7113 (when (and (derived-mode-p 'org-mode)
7114 (not (memq state '(overview folded contents))))
7115 (save-excursion
7116 (let* ((globalp (memq state '(contents all)))
7117 (beg (if globalp (point-min) (point)))
7118 (end (if globalp (point-max)
7119 (if (eq state 'children)
7120 (save-excursion (outline-next-heading) (point))
7121 (org-end-of-subtree t)))))
7122 (goto-char beg)
7123 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7124 (unless (member-ignore-case (match-string 1) exceptions)
7125 (let ((drawer (org-element-at-point)))
7126 (when (memq (org-element-type drawer) '(drawer property-drawer))
7127 (org-flag-drawer t drawer)
7128 ;; Make sure to skip drawer entirely or we might flag
7129 ;; it another time when matching its ending line with
7130 ;; `org-drawer-regexp'.
7131 (goto-char (org-element-property :end drawer))))))))))
7133 (defun org-cycle-hide-inline-tasks (state)
7134 "Re-hide inline tasks when switching to 'contents or 'children
7135 visibility state."
7136 (case state
7137 (contents
7138 (when (org-bound-and-true-p org-inlinetask-min-level)
7139 (hide-sublevels (1- org-inlinetask-min-level))))
7140 (children
7141 (when (featurep 'org-inlinetask)
7142 (save-excursion
7143 (while (and (outline-next-heading)
7144 (org-inlinetask-at-task-p))
7145 (org-inlinetask-toggle-visibility)
7146 (org-inlinetask-goto-end)))))))
7148 (defun org-flag-drawer (flag &optional element)
7149 "When FLAG is non-nil, hide the drawer we are at.
7150 Otherwise make it visible. When optional argument ELEMENT is
7151 a parsed drawer, as returned by `org-element-at-point', hide or
7152 show that drawer instead."
7153 (let ((drawer (or element (org-element-at-point))))
7154 (when (memq (org-element-type drawer) '(drawer property-drawer))
7155 (save-excursion
7156 (goto-char (org-element-property :post-affiliated drawer))
7157 (outline-flag-region
7158 (line-end-position)
7159 (progn (goto-char (org-element-property :end drawer))
7160 (skip-chars-backward " \r\t\n")
7161 (line-end-position))
7162 flag)))))
7164 (defun org-subtree-end-visible-p ()
7165 "Is the end of the current subtree visible?"
7166 (pos-visible-in-window-p
7167 (save-excursion (org-end-of-subtree t) (point))))
7169 (defun org-first-headline-recenter (&optional N)
7170 "Move cursor to the first headline and recenter the headline.
7171 Optional argument N means put the headline into the Nth line of the window."
7172 (goto-char (point-min))
7173 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7174 (beginning-of-line)
7175 (recenter (prefix-numeric-value N))))
7177 ;;; Saving and restoring visibility
7179 (defun org-outline-overlay-data (&optional use-markers)
7180 "Return a list of the locations of all outline overlays.
7181 These are overlays with the `invisible' property value `outline'.
7182 The return value is a list of cons cells, with start and stop
7183 positions for each overlay.
7184 If USE-MARKERS is set, return the positions as markers."
7185 (let (beg end)
7186 (save-excursion
7187 (save-restriction
7188 (widen)
7189 (delq nil
7190 (mapcar (lambda (o)
7191 (when (eq (overlay-get o 'invisible) 'outline)
7192 (setq beg (overlay-start o)
7193 end (overlay-end o))
7194 (and beg end (> end beg)
7195 (if use-markers
7196 (cons (move-marker (make-marker) beg)
7197 (move-marker (make-marker) end))
7198 (cons beg end)))))
7199 (overlays-in (point-min) (point-max))))))))
7201 (defun org-set-outline-overlay-data (data)
7202 "Create visibility overlays for all positions in DATA.
7203 DATA should have been made by `org-outline-overlay-data'."
7204 (let (o)
7205 (save-excursion
7206 (save-restriction
7207 (widen)
7208 (show-all)
7209 (mapc (lambda (c)
7210 (outline-flag-region (car c) (cdr c) t))
7211 data)))))
7213 ;;; Folding of blocks
7215 (defvar org-hide-block-overlays nil
7216 "Overlays hiding blocks.")
7217 (make-variable-buffer-local 'org-hide-block-overlays)
7219 (defun org-block-map (function &optional start end)
7220 "Call FUNCTION at the head of all source blocks in the current buffer.
7221 Optional arguments START and END can be used to limit the range."
7222 (let ((start (or start (point-min)))
7223 (end (or end (point-max))))
7224 (save-excursion
7225 (goto-char start)
7226 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7227 (save-excursion
7228 (save-match-data
7229 (goto-char (match-beginning 0))
7230 (funcall function)))))))
7232 (defun org-hide-block-toggle-all ()
7233 "Toggle the visibility of all blocks in the current buffer."
7234 (org-block-map #'org-hide-block-toggle))
7236 (defun org-hide-block-all ()
7237 "Fold all blocks in the current buffer."
7238 (interactive)
7239 (org-show-block-all)
7240 (org-block-map #'org-hide-block-toggle-maybe))
7242 (defun org-show-block-all ()
7243 "Unfold all blocks in the current buffer."
7244 (interactive)
7245 (mapc 'delete-overlay org-hide-block-overlays)
7246 (setq org-hide-block-overlays nil))
7248 (defun org-hide-block-toggle-maybe ()
7249 "Toggle visibility of block at point."
7250 (interactive)
7251 (let ((case-fold-search t))
7252 (if (save-excursion
7253 (beginning-of-line 1)
7254 (looking-at org-block-regexp))
7255 (progn (org-hide-block-toggle)
7256 t) ;; to signal that we took action
7257 nil))) ;; to signal that we did not
7259 (defun org-hide-block-toggle (&optional force)
7260 "Toggle the visibility of the current block."
7261 (interactive)
7262 (save-excursion
7263 (beginning-of-line)
7264 (if (re-search-forward org-block-regexp nil t)
7265 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7266 (end (match-end 0)) ;; end of entire body
7268 (if (memq t (mapcar (lambda (overlay)
7269 (eq (overlay-get overlay 'invisible)
7270 'org-hide-block))
7271 (overlays-at start)))
7272 (if (or (not force) (eq force 'off))
7273 (mapc (lambda (ov)
7274 (when (member ov org-hide-block-overlays)
7275 (setq org-hide-block-overlays
7276 (delq ov org-hide-block-overlays)))
7277 (when (eq (overlay-get ov 'invisible)
7278 'org-hide-block)
7279 (delete-overlay ov)))
7280 (overlays-at start)))
7281 (setq ov (make-overlay start end))
7282 (overlay-put ov 'invisible 'org-hide-block)
7283 ;; make the block accessible to isearch
7284 (overlay-put
7285 ov 'isearch-open-invisible
7286 (lambda (ov)
7287 (when (member ov org-hide-block-overlays)
7288 (setq org-hide-block-overlays
7289 (delq ov org-hide-block-overlays)))
7290 (when (eq (overlay-get ov 'invisible)
7291 'org-hide-block)
7292 (delete-overlay ov))))
7293 (push ov org-hide-block-overlays)))
7294 (user-error "Not looking at a source block"))))
7296 ;; org-tab-after-check-for-cycling-hook
7297 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7298 ;; Remove overlays when changing major mode
7299 (add-hook 'org-mode-hook
7300 (lambda () (org-add-hook 'change-major-mode-hook
7301 'org-show-block-all 'append 'local)))
7303 ;;; Org-goto
7305 (defvar org-goto-window-configuration nil)
7306 (defvar org-goto-marker nil)
7307 (defvar org-goto-map)
7308 (defun org-goto-map ()
7309 "Set the keymap `org-goto'."
7310 (setq org-goto-map
7311 (let ((map (make-sparse-keymap)))
7312 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7313 mouse-drag-region universal-argument org-occur))
7314 cmd)
7315 (while (setq cmd (pop cmds))
7316 (substitute-key-definition cmd cmd map global-map)))
7317 (suppress-keymap map)
7318 (org-defkey map "\C-m" 'org-goto-ret)
7319 (org-defkey map [(return)] 'org-goto-ret)
7320 (org-defkey map [(left)] 'org-goto-left)
7321 (org-defkey map [(right)] 'org-goto-right)
7322 (org-defkey map [(control ?g)] 'org-goto-quit)
7323 (org-defkey map "\C-i" 'org-cycle)
7324 (org-defkey map [(tab)] 'org-cycle)
7325 (org-defkey map [(down)] 'outline-next-visible-heading)
7326 (org-defkey map [(up)] 'outline-previous-visible-heading)
7327 (if org-goto-auto-isearch
7328 (if (fboundp 'define-key-after)
7329 (define-key-after map [t] 'org-goto-local-auto-isearch)
7330 nil)
7331 (org-defkey map "q" 'org-goto-quit)
7332 (org-defkey map "n" 'outline-next-visible-heading)
7333 (org-defkey map "p" 'outline-previous-visible-heading)
7334 (org-defkey map "f" 'outline-forward-same-level)
7335 (org-defkey map "b" 'outline-backward-same-level)
7336 (org-defkey map "u" 'outline-up-heading))
7337 (org-defkey map "/" 'org-occur)
7338 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7339 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7340 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7341 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7342 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7343 map)))
7345 (defconst org-goto-help
7346 "Browse buffer copy, to find location or copy text.%s
7347 RET=jump to location C-g=quit and return to previous location
7348 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7350 (defvar org-goto-start-pos) ; dynamically scoped parameter
7352 (defun org-goto (&optional alternative-interface)
7353 "Look up a different location in the current file, keeping current visibility.
7355 When you want look-up or go to a different location in a
7356 document, the fastest way is often to fold the entire buffer and
7357 then dive into the tree. This method has the disadvantage, that
7358 the previous location will be folded, which may not be what you
7359 want.
7361 This command works around this by showing a copy of the current
7362 buffer in an indirect buffer, in overview mode. You can dive
7363 into the tree in that copy, use org-occur and incremental search
7364 to find a location. When pressing RET or `Q', the command
7365 returns to the original buffer in which the visibility is still
7366 unchanged. After RET it will also jump to the location selected
7367 in the indirect buffer and expose the headline hierarchy above.
7369 With a prefix argument, use the alternative interface: e.g. if
7370 `org-goto-interface' is 'outline use 'outline-path-completion."
7371 (interactive "P")
7372 (org-goto-map)
7373 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7374 (org-refile-use-outline-path t)
7375 (org-refile-target-verify-function nil)
7376 (interface
7377 (if (not alternative-interface)
7378 org-goto-interface
7379 (if (eq org-goto-interface 'outline)
7380 'outline-path-completion
7381 'outline)))
7382 (org-goto-start-pos (point))
7383 (selected-point
7384 (if (eq interface 'outline)
7385 (car (org-get-location (current-buffer) org-goto-help))
7386 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7387 (org-refile-check-position pa)
7388 (nth 3 pa)))))
7389 (if selected-point
7390 (progn
7391 (org-mark-ring-push org-goto-start-pos)
7392 (goto-char selected-point)
7393 (if (or (outline-invisible-p) (org-invisible-p2))
7394 (org-show-context 'org-goto)))
7395 (message "Quit"))))
7397 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7398 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7399 (defvar org-goto-local-auto-isearch-map) ; defined below
7401 (defun org-get-location (buf help)
7402 "Let the user select a location in the Org-mode buffer BUF.
7403 This function uses a recursive edit. It returns the selected position
7404 or nil."
7405 (org-no-popups
7406 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7407 (isearch-hide-immediately nil)
7408 (isearch-search-fun-function
7409 (lambda () 'org-goto-local-search-headings))
7410 (org-goto-selected-point org-goto-exit-command))
7411 (save-excursion
7412 (save-window-excursion
7413 (delete-other-windows)
7414 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7415 (org-pop-to-buffer-same-window
7416 (condition-case nil
7417 (make-indirect-buffer (current-buffer) "*org-goto*")
7418 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7419 (with-output-to-temp-buffer "*Org Help*"
7420 (princ (format help (if org-goto-auto-isearch
7421 " Just type for auto-isearch."
7422 " n/p/f/b/u to navigate, q to quit."))))
7423 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7424 (setq buffer-read-only nil)
7425 (let ((org-startup-truncated t)
7426 (org-startup-folded nil)
7427 (org-startup-align-all-tables nil))
7428 (org-mode)
7429 (org-overview))
7430 (setq buffer-read-only t)
7431 (if (and (boundp 'org-goto-start-pos)
7432 (integer-or-marker-p org-goto-start-pos))
7433 (let ((org-show-hierarchy-above t)
7434 (org-show-siblings t)
7435 (org-show-following-heading t))
7436 (goto-char org-goto-start-pos)
7437 (and (outline-invisible-p) (org-show-context)))
7438 (goto-char (point-min)))
7439 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7440 (message "Select location and press RET")
7441 (use-local-map org-goto-map)
7442 (recursive-edit)))
7443 (kill-buffer "*org-goto*")
7444 (cons org-goto-selected-point org-goto-exit-command))))
7446 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7447 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7448 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7449 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7451 (defun org-goto-local-search-headings (string bound noerror)
7452 "Search and make sure that any matches are in headlines."
7453 (catch 'return
7454 (while (if isearch-forward
7455 (search-forward string bound noerror)
7456 (search-backward string bound noerror))
7457 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7458 (and (member :headline context)
7459 (not (member :tags context))))
7460 (throw 'return (point))))))
7462 (defun org-goto-local-auto-isearch ()
7463 "Start isearch."
7464 (interactive)
7465 (goto-char (point-min))
7466 (let ((keys (this-command-keys)))
7467 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7468 (isearch-mode t)
7469 (isearch-process-search-char (string-to-char keys)))))
7471 (defun org-goto-ret (&optional arg)
7472 "Finish `org-goto' by going to the new location."
7473 (interactive "P")
7474 (setq org-goto-selected-point (point)
7475 org-goto-exit-command 'return)
7476 (throw 'exit nil))
7478 (defun org-goto-left ()
7479 "Finish `org-goto' by going to the new location."
7480 (interactive)
7481 (if (org-at-heading-p)
7482 (progn
7483 (beginning-of-line 1)
7484 (setq org-goto-selected-point (point)
7485 org-goto-exit-command 'left)
7486 (throw 'exit nil))
7487 (user-error "Not on a heading")))
7489 (defun org-goto-right ()
7490 "Finish `org-goto' by going to the new location."
7491 (interactive)
7492 (if (org-at-heading-p)
7493 (progn
7494 (setq org-goto-selected-point (point)
7495 org-goto-exit-command 'right)
7496 (throw 'exit nil))
7497 (user-error "Not on a heading")))
7499 (defun org-goto-quit ()
7500 "Finish `org-goto' without cursor motion."
7501 (interactive)
7502 (setq org-goto-selected-point nil)
7503 (setq org-goto-exit-command 'quit)
7504 (throw 'exit nil))
7506 ;;; Indirect buffer display of subtrees
7508 (defvar org-indirect-dedicated-frame nil
7509 "This is the frame being used for indirect tree display.")
7510 (defvar org-last-indirect-buffer nil)
7512 (defun org-tree-to-indirect-buffer (&optional arg)
7513 "Create indirect buffer and narrow it to current subtree.
7514 With a numerical prefix ARG, go up to this level and then take that tree.
7515 If ARG is negative, go up that many levels.
7517 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7518 indirect buffer previously made with this command, to avoid proliferation of
7519 indirect buffers. However, when you call the command with a \
7520 \\[universal-argument] prefix, or
7521 when `org-indirect-buffer-display' is `new-frame', the last buffer
7522 is kept so that you can work with several indirect buffers at the same time.
7523 If `org-indirect-buffer-display' is `dedicated-frame', the \
7524 \\[universal-argument] prefix also
7525 requests that a new frame be made for the new buffer, so that the dedicated
7526 frame is not changed."
7527 (interactive "P")
7528 (let ((cbuf (current-buffer))
7529 (cwin (selected-window))
7530 (pos (point))
7531 beg end level heading ibuf)
7532 (save-excursion
7533 (org-back-to-heading t)
7534 (when (numberp arg)
7535 (setq level (org-outline-level))
7536 (if (< arg 0) (setq arg (+ level arg)))
7537 (while (> (setq level (org-outline-level)) arg)
7538 (org-up-heading-safe)))
7539 (setq beg (point)
7540 heading (org-get-heading))
7541 (org-end-of-subtree t t)
7542 (if (org-at-heading-p) (backward-char 1))
7543 (setq end (point)))
7544 (if (and (buffer-live-p org-last-indirect-buffer)
7545 (not (eq org-indirect-buffer-display 'new-frame))
7546 (not arg))
7547 (kill-buffer org-last-indirect-buffer))
7548 (setq ibuf (org-get-indirect-buffer cbuf heading)
7549 org-last-indirect-buffer ibuf)
7550 (cond
7551 ((or (eq org-indirect-buffer-display 'new-frame)
7552 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7553 (select-frame (make-frame))
7554 (delete-other-windows)
7555 (org-pop-to-buffer-same-window ibuf)
7556 (org-set-frame-title heading))
7557 ((eq org-indirect-buffer-display 'dedicated-frame)
7558 (raise-frame
7559 (select-frame (or (and org-indirect-dedicated-frame
7560 (frame-live-p org-indirect-dedicated-frame)
7561 org-indirect-dedicated-frame)
7562 (setq org-indirect-dedicated-frame (make-frame)))))
7563 (delete-other-windows)
7564 (org-pop-to-buffer-same-window ibuf)
7565 (org-set-frame-title (concat "Indirect: " heading)))
7566 ((eq org-indirect-buffer-display 'current-window)
7567 (org-pop-to-buffer-same-window ibuf))
7568 ((eq org-indirect-buffer-display 'other-window)
7569 (pop-to-buffer ibuf))
7570 (t (error "Invalid value")))
7571 (if (featurep 'xemacs)
7572 (save-excursion (org-mode) (turn-on-font-lock)))
7573 (narrow-to-region beg end)
7574 (show-all)
7575 (goto-char pos)
7576 (run-hook-with-args 'org-cycle-hook 'all)
7577 (and (window-live-p cwin) (select-window cwin))))
7579 (defun org-get-indirect-buffer (&optional buffer heading)
7580 (setq buffer (or buffer (current-buffer)))
7581 (let ((n 1) (base (buffer-name buffer)) bname)
7582 (while (buffer-live-p
7583 (get-buffer
7584 (setq bname
7585 (concat base "-"
7586 (if heading (concat heading "-" (number-to-string n))
7587 (number-to-string n))))))
7588 (setq n (1+ n)))
7589 (condition-case nil
7590 (make-indirect-buffer buffer bname 'clone)
7591 (error (make-indirect-buffer buffer bname)))))
7593 (defun org-set-frame-title (title)
7594 "Set the title of the current frame to the string TITLE."
7595 ;; FIXME: how to name a single frame in XEmacs???
7596 (unless (featurep 'xemacs)
7597 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7599 ;;;; Structure editing
7601 ;;; Inserting headlines
7603 (defun org-previous-line-empty-p (&optional next)
7604 "Is the previous line a blank line?
7605 When NEXT is non-nil, check the next line instead."
7606 (save-excursion
7607 (and (not (bobp))
7608 (or (beginning-of-line (if next 2 0)) t)
7609 (save-match-data
7610 (looking-at "[ \t]*$")))))
7612 (defun org-insert-heading (&optional arg invisible-ok)
7613 "Insert a new heading or item with same depth at point.
7614 If point is in a plain list and ARG is nil, create a new list item.
7615 With one universal prefix argument, insert a heading even in lists.
7616 With two universal prefix arguments, insert the heading at the end
7617 of the parent subtree.
7619 If point is at the beginning of a headline, insert a sibling before
7620 the current headline. If point is not at the beginning, split the line
7621 and create a new headline with the text in the current line after point
7622 \(see `org-M-RET-may-split-line' on how to modify this behavior).
7624 If point is at the beginning of a normal line, turn this line into
7625 a heading.
7627 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7628 This is important for non-interactive uses of the command."
7629 (interactive "P")
7630 (if (org-called-interactively-p 'any) (org-reveal))
7631 (let ((itemp (org-in-item-p))
7632 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7633 (respect-content (or org-insert-heading-respect-content
7634 (equal arg '(16))))
7635 (initial-content "")
7636 (adjust-empty-lines t))
7638 (cond
7640 ((or (= (buffer-size) 0)
7641 (and (not (save-excursion
7642 (and (ignore-errors (org-back-to-heading invisible-ok))
7643 (org-at-heading-p))))
7644 (or arg (not itemp))))
7645 ;; At beginning of buffer or so high up that only a heading
7646 ;; makes sense.
7647 (insert
7648 (if (or (bobp) (org-previous-line-empty-p)) "" "\n")
7649 (if (org-in-src-block-p) ",* " "* "))
7650 (run-hooks 'org-insert-heading-hook))
7652 ((and itemp (not (equal arg '(4))))
7653 ;; Insert an item
7654 (org-insert-item))
7657 ;; Insert a heading
7658 (save-restriction
7659 (widen)
7660 (let* ((level nil)
7661 (on-heading (org-at-heading-p))
7662 (empty-line-p (if on-heading
7663 (org-previous-line-empty-p)
7664 ;; We will decide later
7665 nil))
7666 ;; Get a level string to fall back on
7667 (fix-level
7668 (save-excursion
7669 (org-back-to-heading t)
7670 (if (org-previous-line-empty-p) (setq empty-line-p t))
7671 (looking-at org-outline-regexp)
7672 (make-string (1- (length (match-string 0))) ?*)))
7673 (stars
7674 (save-excursion
7675 (condition-case nil
7676 (progn
7677 (org-back-to-heading invisible-ok)
7678 (when (and (not on-heading)
7679 (featurep 'org-inlinetask)
7680 (integerp org-inlinetask-min-level)
7681 (>= (length (match-string 0))
7682 org-inlinetask-min-level))
7683 ;; Find a heading level before the inline task
7684 (while (and (setq level (org-up-heading-safe))
7685 (>= level org-inlinetask-min-level)))
7686 (if (org-at-heading-p)
7687 (org-back-to-heading invisible-ok)
7688 (error "This should not happen")))
7689 (unless (and (save-excursion
7690 (save-match-data
7691 (org-backward-heading-same-level
7692 1 invisible-ok))
7693 (= (point) (match-beginning 0)))
7694 (not (org-previous-line-empty-p t)))
7695 (setq empty-line-p (or empty-line-p
7696 (org-previous-line-empty-p))))
7697 (match-string 0))
7698 (error (or fix-level "* ")))))
7699 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7700 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7701 pos hide-previous previous-pos)
7703 ;; If we insert after content, move there and clean up whitespace
7704 (when respect-content
7705 (org-end-of-subtree nil t)
7706 (skip-chars-backward " \r\n")
7707 (and (looking-at "[ \t]+") (replace-match ""))
7708 (unless (eobp) (forward-char 1))
7709 (when (looking-at "^\\*")
7710 (unless (bobp) (backward-char 1))
7711 (insert "\n")))
7713 ;; If we are splitting, grab the text that should be moved to the new headline
7714 (when may-split
7715 (if (org-on-heading-p)
7716 ;; This is a heading, we split intelligently (keeping tags)
7717 (let ((pos (point)))
7718 (goto-char (point-at-bol))
7719 (unless (looking-at org-complex-heading-regexp)
7720 (error "This should not happen"))
7721 (when (and (match-beginning 4)
7722 (> pos (match-beginning 4))
7723 (< pos (match-end 4)))
7724 (setq initial-content (buffer-substring pos (match-end 4)))
7725 (goto-char pos)
7726 (delete-region (point) (match-end 4))
7727 (if (looking-at "[ \t]*$")
7728 (replace-match "")
7729 (insert (make-string (length initial-content) ?\ )))
7730 (setq initial-content (org-trim initial-content)))
7731 (goto-char pos))
7732 ;; a normal line
7733 (unless (bolp)
7734 (setq initial-content (buffer-substring (point) (point-at-eol)))
7735 (delete-region (point) (point-at-eol))
7736 (setq initial-content (org-trim initial-content)))))
7738 ;; If we are at the beginning of the line, insert before it. Else after
7739 (cond
7740 ((and (bolp) (looking-at "[ \t]*$")))
7741 ((and (bolp) (not (looking-at "[ \t]*$")))
7742 (open-line 1))
7744 (goto-char (point-at-eol))
7745 (insert "\n")))
7747 ;; Insert the new heading
7748 (insert stars)
7749 (just-one-space)
7750 (insert initial-content)
7751 (when adjust-empty-lines
7752 (if (or (not blank)
7753 (and blank (not (org-previous-line-empty-p))))
7754 (org-N-empty-lines-before-current (if blank 1 0))))
7755 (run-hooks 'org-insert-heading-hook)))))))
7757 (defun org-N-empty-lines-before-current (N)
7758 "Make the number of empty lines before current exactly N.
7759 So this will delete or add empty lines."
7760 (save-excursion
7761 (goto-char (point-at-bol))
7762 (if (looking-back "\\s-+" nil 'greedy)
7763 (replace-match ""))
7764 (or (bobp) (insert "\n"))
7765 (while (> N 0)
7766 (insert "\n")
7767 (setq N (1- N)))))
7769 (defun org-get-heading (&optional no-tags no-todo)
7770 "Return the heading of the current entry, without the stars.
7771 When NO-TAGS is non-nil, don't include tags.
7772 When NO-TODO is non-nil, don't include TODO keywords."
7773 (save-excursion
7774 (org-back-to-heading t)
7775 (cond
7776 ((and no-tags no-todo)
7777 (looking-at org-complex-heading-regexp)
7778 (match-string 4))
7779 (no-tags
7780 (looking-at (concat org-outline-regexp
7781 "\\(.*?\\)"
7782 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7783 (match-string 1))
7784 (no-todo
7785 (looking-at org-todo-line-regexp)
7786 (match-string 3))
7787 (t (looking-at org-heading-regexp)
7788 (match-string 2)))))
7790 (defvar orgstruct-mode) ; defined below
7792 (defun org-heading-components ()
7793 "Return the components of the current heading.
7794 This is a list with the following elements:
7795 - the level as an integer
7796 - the reduced level, different if `org-odd-levels-only' is set.
7797 - the TODO keyword, or nil
7798 - the priority character, like ?A, or nil if no priority is given
7799 - the headline text itself, or the tags string if no headline text
7800 - the tags string, or nil."
7801 (save-excursion
7802 (org-back-to-heading t)
7803 (if (let (case-fold-search)
7804 (looking-at
7805 (if orgstruct-mode
7806 org-heading-regexp
7807 org-complex-heading-regexp)))
7808 (if orgstruct-mode
7809 (list (length (match-string 1))
7810 (org-reduced-level (length (match-string 1)))
7813 (match-string 2)
7814 nil)
7815 (list (length (match-string 1))
7816 (org-reduced-level (length (match-string 1)))
7817 (org-match-string-no-properties 2)
7818 (and (match-end 3) (aref (match-string 3) 2))
7819 (org-match-string-no-properties 4)
7820 (org-match-string-no-properties 5))))))
7822 (defun org-get-entry ()
7823 "Get the entry text, after heading, entire subtree."
7824 (save-excursion
7825 (org-back-to-heading t)
7826 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7828 (defun org-insert-heading-after-current ()
7829 "Insert a new heading with same level as current, after current subtree."
7830 (interactive)
7831 (org-back-to-heading)
7832 (org-insert-heading)
7833 (org-move-subtree-down)
7834 (end-of-line 1))
7836 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7837 "Insert heading with `org-insert-heading-respect-content' set to t."
7838 (interactive "P")
7839 (let ((org-insert-heading-respect-content t))
7840 (org-insert-heading '(4) invisible-ok)))
7842 (defun org-insert-todo-heading-respect-content (&optional force-state)
7843 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7844 (interactive "P")
7845 (let ((org-insert-heading-respect-content t))
7846 (org-insert-todo-heading force-state '(4))))
7848 (defun org-insert-todo-heading (arg &optional force-heading)
7849 "Insert a new heading with the same level and TODO state as current heading.
7850 If the heading has no TODO state, or if the state is DONE, use the first
7851 state (TODO by default). Also one prefix arg, force first state. With two
7852 prefix args, force inserting at the end of the parent subtree."
7853 (interactive "P")
7854 (when (or force-heading (not (org-insert-item 'checkbox)))
7855 (org-insert-heading (or (and (equal arg '(16)) '(16))
7856 force-heading))
7857 (save-excursion
7858 (org-back-to-heading)
7859 (outline-previous-heading)
7860 (looking-at org-todo-line-regexp))
7861 (let*
7862 ((new-mark-x
7863 (if (or arg
7864 (not (match-beginning 2))
7865 (member (match-string 2) org-done-keywords))
7866 (car org-todo-keywords-1)
7867 (match-string 2)))
7868 (new-mark
7870 (run-hook-with-args-until-success
7871 'org-todo-get-default-hook new-mark-x nil)
7872 new-mark-x)))
7873 (beginning-of-line 1)
7874 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7875 (if org-treat-insert-todo-heading-as-state-change
7876 (org-todo new-mark)
7877 (insert new-mark " "))))
7878 (when org-provide-todo-statistics
7879 (org-update-parent-todo-statistics))))
7881 (defun org-insert-subheading (arg)
7882 "Insert a new subheading and demote it.
7883 Works for outline headings and for plain lists alike."
7884 (interactive "P")
7885 (org-insert-heading arg)
7886 (cond
7887 ((org-at-heading-p) (org-do-demote))
7888 ((org-at-item-p) (org-indent-item))))
7890 (defun org-insert-todo-subheading (arg)
7891 "Insert a new subheading with TODO keyword or checkbox and demote it.
7892 Works for outline headings and for plain lists alike."
7893 (interactive "P")
7894 (org-insert-todo-heading arg)
7895 (cond
7896 ((org-at-heading-p) (org-do-demote))
7897 ((org-at-item-p) (org-indent-item))))
7899 ;;; Promotion and Demotion
7901 (defvar org-after-demote-entry-hook nil
7902 "Hook run after an entry has been demoted.
7903 The cursor will be at the beginning of the entry.
7904 When a subtree is being demoted, the hook will be called for each node.")
7906 (defvar org-after-promote-entry-hook nil
7907 "Hook run after an entry has been promoted.
7908 The cursor will be at the beginning of the entry.
7909 When a subtree is being promoted, the hook will be called for each node.")
7911 (defun org-promote-subtree ()
7912 "Promote the entire subtree.
7913 See also `org-promote'."
7914 (interactive)
7915 (save-excursion
7916 (org-with-limited-levels (org-map-tree 'org-promote)))
7917 (org-fix-position-after-promote))
7919 (defun org-demote-subtree ()
7920 "Demote the entire subtree. See `org-demote'.
7921 See also `org-promote'."
7922 (interactive)
7923 (save-excursion
7924 (org-with-limited-levels (org-map-tree 'org-demote)))
7925 (org-fix-position-after-promote))
7928 (defun org-do-promote ()
7929 "Promote the current heading higher up the tree.
7930 If the region is active in `transient-mark-mode', promote all headings
7931 in the region."
7932 (interactive)
7933 (save-excursion
7934 (if (org-region-active-p)
7935 (org-map-region 'org-promote (region-beginning) (region-end))
7936 (org-promote)))
7937 (org-fix-position-after-promote))
7939 (defun org-do-demote ()
7940 "Demote the current heading lower down the tree.
7941 If the region is active in `transient-mark-mode', demote all headings
7942 in the region."
7943 (interactive)
7944 (save-excursion
7945 (if (org-region-active-p)
7946 (org-map-region 'org-demote (region-beginning) (region-end))
7947 (org-demote)))
7948 (org-fix-position-after-promote))
7950 (defun org-fix-position-after-promote ()
7951 "Make sure that after pro/demotion cursor position is right."
7952 (let ((pos (point)))
7953 (when (save-excursion
7954 (beginning-of-line 1)
7955 (looking-at org-todo-line-regexp)
7956 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7957 (cond ((eobp) (insert " "))
7958 ((eolp) (insert " "))
7959 ((equal (char-after) ?\ ) (forward-char 1))))))
7961 (defun org-current-level ()
7962 "Return the level of the current entry, or nil if before the first headline.
7963 The level is the number of stars at the beginning of the headline."
7964 (save-excursion
7965 (org-with-limited-levels
7966 (if (ignore-errors (org-back-to-heading t))
7967 (funcall outline-level)))))
7969 (defun org-get-previous-line-level ()
7970 "Return the outline depth of the last headline before the current line.
7971 Returns 0 for the first headline in the buffer, and nil if before the
7972 first headline."
7973 (let ((current-level (org-current-level))
7974 (prev-level (when (> (line-number-at-pos) 1)
7975 (save-excursion
7976 (beginning-of-line 0)
7977 (org-current-level)))))
7978 (cond ((null current-level) nil) ; Before first headline
7979 ((null prev-level) 0) ; At first headline
7980 (prev-level))))
7982 (defun org-reduced-level (l)
7983 "Compute the effective level of a heading.
7984 This takes into account the setting of `org-odd-levels-only'."
7985 (cond
7986 ((zerop l) 0)
7987 (org-odd-levels-only (1+ (floor (/ l 2))))
7988 (t l)))
7990 (defun org-level-increment ()
7991 "Return the number of stars that will be added or removed at a
7992 time to headlines when structure editing, based on the value of
7993 `org-odd-levels-only'."
7994 (if org-odd-levels-only 2 1))
7996 (defun org-get-valid-level (level &optional change)
7997 "Rectify a level change under the influence of `org-odd-levels-only'
7998 LEVEL is a current level, CHANGE is by how much the level should be
7999 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8000 even level numbers will become the next higher odd number."
8001 (if org-odd-levels-only
8002 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8003 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8004 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8005 (max 1 (+ level (or change 0)))))
8007 (if (boundp 'define-obsolete-function-alias)
8008 (if (or (featurep 'xemacs) (< emacs-major-version 23))
8009 (define-obsolete-function-alias 'org-get-legal-level
8010 'org-get-valid-level)
8011 (define-obsolete-function-alias 'org-get-legal-level
8012 'org-get-valid-level "23.1")))
8014 (defun org-promote ()
8015 "Promote the current heading higher up the tree.
8016 If the region is active in `transient-mark-mode', promote all headings
8017 in the region."
8018 (org-back-to-heading t)
8019 (let* ((level (save-match-data (funcall outline-level)))
8020 (after-change-functions (remove 'flyspell-after-change-function
8021 after-change-functions))
8022 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8023 (diff (abs (- level (length up-head) -1))))
8024 (cond ((and (= level 1) org-called-with-limited-levels
8025 org-allow-promoting-top-level-subtree)
8026 (replace-match "# " nil t))
8027 ((= level 1)
8028 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8029 (t (replace-match up-head nil t)))
8030 ;; Fixup tag positioning
8031 (unless (= level 1)
8032 (and org-auto-align-tags (org-set-tags nil t))
8033 (if org-adapt-indentation (org-fixup-indentation (- diff))))
8034 (run-hooks 'org-after-promote-entry-hook)))
8036 (defun org-demote ()
8037 "Demote the current heading lower down the tree.
8038 If the region is active in `transient-mark-mode', demote all headings
8039 in the region."
8040 (org-back-to-heading t)
8041 (let* ((level (save-match-data (funcall outline-level)))
8042 (after-change-functions (remove 'flyspell-after-change-function
8043 after-change-functions))
8044 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8045 (diff (abs (- level (length down-head) -1))))
8046 (replace-match down-head nil t)
8047 ;; Fixup tag positioning
8048 (and org-auto-align-tags (org-set-tags nil t))
8049 (if org-adapt-indentation (org-fixup-indentation diff))
8050 (run-hooks 'org-after-demote-entry-hook)))
8052 (defun org-cycle-level ()
8053 "Cycle the level of an empty headline through possible states.
8054 This goes first to child, then to parent, level, then up the hierarchy.
8055 After top level, it switches back to sibling level."
8056 (interactive)
8057 (let ((org-adapt-indentation nil))
8058 (when (org-point-at-end-of-empty-headline)
8059 (setq this-command 'org-cycle-level) ; Only needed for caching
8060 (let ((cur-level (org-current-level))
8061 (prev-level (org-get-previous-line-level)))
8062 (cond
8063 ;; If first headline in file, promote to top-level.
8064 ((= prev-level 0)
8065 (loop repeat (/ (- cur-level 1) (org-level-increment))
8066 do (org-do-promote)))
8067 ;; If same level as prev, demote one.
8068 ((= prev-level cur-level)
8069 (org-do-demote))
8070 ;; If parent is top-level, promote to top level if not already.
8071 ((= prev-level 1)
8072 (loop repeat (/ (- cur-level 1) (org-level-increment))
8073 do (org-do-promote)))
8074 ;; If top-level, return to prev-level.
8075 ((= cur-level 1)
8076 (loop repeat (/ (- prev-level 1) (org-level-increment))
8077 do (org-do-demote)))
8078 ;; If less than prev-level, promote one.
8079 ((< cur-level prev-level)
8080 (org-do-promote))
8081 ;; If deeper than prev-level, promote until higher than
8082 ;; prev-level.
8083 ((> cur-level prev-level)
8084 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8085 do (org-do-promote))))
8086 t))))
8088 (defun org-map-tree (fun)
8089 "Call FUN for every heading underneath the current one."
8090 (org-back-to-heading)
8091 (let ((level (funcall outline-level)))
8092 (save-excursion
8093 (funcall fun)
8094 (while (and (progn
8095 (outline-next-heading)
8096 (> (funcall outline-level) level))
8097 (not (eobp)))
8098 (funcall fun)))))
8100 (defun org-map-region (fun beg end)
8101 "Call FUN for every heading between BEG and END."
8102 (let ((org-ignore-region t))
8103 (save-excursion
8104 (setq end (copy-marker end))
8105 (goto-char beg)
8106 (if (and (re-search-forward org-outline-regexp-bol nil t)
8107 (< (point) end))
8108 (funcall fun))
8109 (while (and (progn
8110 (outline-next-heading)
8111 (< (point) end))
8112 (not (eobp)))
8113 (funcall fun)))))
8115 (defvar org-property-end-re) ; silence byte-compiler
8116 (defun org-fixup-indentation (diff)
8117 "Change the indentation in the current entry by DIFF.
8118 However, if any line in the current entry has no indentation, or if it
8119 would end up with no indentation after the change, nothing at all is done."
8120 (save-excursion
8121 (let ((end (save-excursion (outline-next-heading)
8122 (point-marker)))
8123 (prohibit (if (> diff 0)
8124 "^\\S-"
8125 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8126 col)
8127 (unless (save-excursion (end-of-line 1)
8128 (re-search-forward prohibit end t))
8129 (while (and (< (point) end)
8130 (re-search-forward "^[ \t]+" end t))
8131 (goto-char (match-end 0))
8132 (setq col (current-column))
8133 (if (< diff 0) (replace-match ""))
8134 (org-indent-to-column (+ diff col))))
8135 (move-marker end nil))))
8137 (defun org-convert-to-odd-levels ()
8138 "Convert an org-mode file with all levels allowed to one with odd levels.
8139 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8140 level 5 etc."
8141 (interactive)
8142 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8143 (let ((outline-level 'org-outline-level)
8144 (org-odd-levels-only nil) n)
8145 (save-excursion
8146 (goto-char (point-min))
8147 (while (re-search-forward "^\\*\\*+ " nil t)
8148 (setq n (- (length (match-string 0)) 2))
8149 (while (>= (setq n (1- n)) 0)
8150 (org-demote))
8151 (end-of-line 1))))))
8153 (defun org-convert-to-oddeven-levels ()
8154 "Convert an org-mode file with only odd levels to one with odd/even levels.
8155 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8156 file contains a section with an even level, conversion would
8157 destroy the structure of the file. An error is signaled in this
8158 case."
8159 (interactive)
8160 (goto-char (point-min))
8161 ;; First check if there are no even levels
8162 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8163 (org-show-context t)
8164 (error "Not all levels are odd in this file. Conversion not possible"))
8165 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8166 (let ((outline-regexp org-outline-regexp)
8167 (outline-level 'org-outline-level)
8168 (org-odd-levels-only nil) n)
8169 (save-excursion
8170 (goto-char (point-min))
8171 (while (re-search-forward "^\\*\\*+ " nil t)
8172 (setq n (/ (1- (length (match-string 0))) 2))
8173 (while (>= (setq n (1- n)) 0)
8174 (org-promote))
8175 (end-of-line 1))))))
8177 (defun org-tr-level (n)
8178 "Make N odd if required."
8179 (if org-odd-levels-only (1+ (/ n 2)) n))
8181 ;;; Vertical tree motion, cutting and pasting of subtrees
8183 (defun org-move-subtree-up (&optional arg)
8184 "Move the current subtree up past ARG headlines of the same level."
8185 (interactive "p")
8186 (org-move-subtree-down (- (prefix-numeric-value arg))))
8188 (defun org-move-subtree-down (&optional arg)
8189 "Move the current subtree down past ARG headlines of the same level."
8190 (interactive "p")
8191 (setq arg (prefix-numeric-value arg))
8192 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8193 'org-get-last-sibling))
8194 (ins-point (make-marker))
8195 (cnt (abs arg))
8196 (col (current-column))
8197 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8198 ;; Select the tree
8199 (org-back-to-heading)
8200 (setq beg0 (point))
8201 (save-excursion
8202 (setq ne-beg (org-back-over-empty-lines))
8203 (setq beg (point)))
8204 (save-match-data
8205 (save-excursion (outline-end-of-heading)
8206 (setq folded (outline-invisible-p)))
8207 (outline-end-of-subtree))
8208 (outline-next-heading)
8209 (setq ne-end (org-back-over-empty-lines))
8210 (setq end (point))
8211 (goto-char beg0)
8212 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8213 ;; include less whitespace
8214 (save-excursion
8215 (goto-char beg)
8216 (forward-line (- ne-beg ne-end))
8217 (setq beg (point))))
8218 ;; Find insertion point, with error handling
8219 (while (> cnt 0)
8220 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8221 (progn (goto-char beg0)
8222 (user-error "Cannot move past superior level or buffer limit")))
8223 (setq cnt (1- cnt)))
8224 (if (> arg 0)
8225 ;; Moving forward - still need to move over subtree
8226 (progn (org-end-of-subtree t t)
8227 (save-excursion
8228 (org-back-over-empty-lines)
8229 (or (bolp) (newline)))))
8230 (setq ne-ins (org-back-over-empty-lines))
8231 (move-marker ins-point (point))
8232 (setq txt (buffer-substring beg end))
8233 (org-save-markers-in-region beg end)
8234 (delete-region beg end)
8235 (org-remove-empty-overlays-at beg)
8236 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8237 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8238 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8239 (let ((bbb (point)))
8240 (insert-before-markers txt)
8241 (org-reinstall-markers-in-region bbb)
8242 (move-marker ins-point bbb))
8243 (or (bolp) (insert "\n"))
8244 (setq ins-end (point))
8245 (goto-char ins-point)
8246 (org-skip-whitespace)
8247 (when (and (< arg 0)
8248 (org-first-sibling-p)
8249 (> ne-ins ne-beg))
8250 ;; Move whitespace back to beginning
8251 (save-excursion
8252 (goto-char ins-end)
8253 (let ((kill-whole-line t))
8254 (kill-line (- ne-ins ne-beg)) (point)))
8255 (insert (make-string (- ne-ins ne-beg) ?\n)))
8256 (move-marker ins-point nil)
8257 (if folded
8258 (hide-subtree)
8259 (org-show-entry)
8260 (show-children)
8261 (org-cycle-hide-drawers 'children))
8262 (org-clean-visibility-after-subtree-move)
8263 ;; move back to the initial column we were at
8264 (move-to-column col)))
8266 (defvar org-subtree-clip ""
8267 "Clipboard for cut and paste of subtrees.
8268 This is actually only a copy of the kill, because we use the normal kill
8269 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8271 (defvar org-subtree-clip-folded nil
8272 "Was the last copied subtree folded?
8273 This is used to fold the tree back after pasting.")
8275 (defun org-cut-subtree (&optional n)
8276 "Cut the current subtree into the clipboard.
8277 With prefix arg N, cut this many sequential subtrees.
8278 This is a short-hand for marking the subtree and then cutting it."
8279 (interactive "p")
8280 (org-copy-subtree n 'cut))
8282 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8283 "Copy the current subtree it in the clipboard.
8284 With prefix arg N, copy this many sequential subtrees.
8285 This is a short-hand for marking the subtree and then copying it.
8286 If CUT is non-nil, actually cut the subtree.
8287 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8288 of some markers in the region, even if CUT is non-nil. This is
8289 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8290 (interactive "p")
8291 (let (beg end folded (beg0 (point)))
8292 (if (org-called-interactively-p 'any)
8293 (org-back-to-heading nil) ; take what looks like a subtree
8294 (org-back-to-heading t)) ; take what is really there
8295 (setq beg (point))
8296 (skip-chars-forward " \t\r\n")
8297 (save-match-data
8298 (if nosubtrees
8299 (outline-next-heading)
8300 (save-excursion (outline-end-of-heading)
8301 (setq folded (outline-invisible-p)))
8302 (condition-case nil
8303 (org-forward-heading-same-level (1- n) t)
8304 (error nil))
8305 (org-end-of-subtree t t)))
8306 (setq end (point))
8307 (goto-char beg0)
8308 (when (> end beg)
8309 (setq org-subtree-clip-folded folded)
8310 (when (or cut force-store-markers)
8311 (org-save-markers-in-region beg end))
8312 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8313 (setq org-subtree-clip (current-kill 0))
8314 (message "%s: Subtree(s) with %d characters"
8315 (if cut "Cut" "Copied")
8316 (length org-subtree-clip)))))
8318 (defun org-paste-subtree (&optional level tree for-yank)
8319 "Paste the clipboard as a subtree, with modification of headline level.
8320 The entire subtree is promoted or demoted in order to match a new headline
8321 level.
8323 If the cursor is at the beginning of a headline, the same level as
8324 that headline is used to paste the tree.
8326 If not, the new level is derived from the *visible* headings
8327 before and after the insertion point, and taken to be the inferior headline
8328 level of the two. So if the previous visible heading is level 3 and the
8329 next is level 4 (or vice versa), level 4 will be used for insertion.
8330 This makes sure that the subtree remains an independent subtree and does
8331 not swallow low level entries.
8333 You can also force a different level, either by using a numeric prefix
8334 argument, or by inserting the heading marker by hand. For example, if the
8335 cursor is after \"*****\", then the tree will be shifted to level 5.
8337 If optional TREE is given, use this text instead of the kill ring.
8339 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8340 move back over whitespace before inserting, and move point to the end of
8341 the inserted text when done."
8342 (interactive "P")
8343 (setq tree (or tree (and kill-ring (current-kill 0))))
8344 (unless (org-kill-is-subtree-p tree)
8345 (user-error "%s"
8346 (substitute-command-keys
8347 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8348 (org-with-limited-levels
8349 (let* ((visp (not (outline-invisible-p)))
8350 (txt tree)
8351 (^re_ "\\(\\*+\\)[ \t]*")
8352 (old-level (if (string-match org-outline-regexp-bol txt)
8353 (- (match-end 0) (match-beginning 0) 1)
8354 -1))
8355 (force-level (cond (level (prefix-numeric-value level))
8356 ((and (looking-at "[ \t]*$")
8357 (string-match
8358 "^\\*+$" (buffer-substring
8359 (point-at-bol) (point))))
8360 (- (match-end 1) (match-beginning 1)))
8361 ((and (bolp)
8362 (looking-at org-outline-regexp))
8363 (- (match-end 0) (point) 1))))
8364 (previous-level (save-excursion
8365 (condition-case nil
8366 (progn
8367 (outline-previous-visible-heading 1)
8368 (if (looking-at ^re_)
8369 (- (match-end 0) (match-beginning 0) 1)
8371 (error 1))))
8372 (next-level (save-excursion
8373 (condition-case nil
8374 (progn
8375 (or (looking-at org-outline-regexp)
8376 (outline-next-visible-heading 1))
8377 (if (looking-at ^re_)
8378 (- (match-end 0) (match-beginning 0) 1)
8380 (error 1))))
8381 (new-level (or force-level (max previous-level next-level)))
8382 (shift (if (or (= old-level -1)
8383 (= new-level -1)
8384 (= old-level new-level))
8386 (- new-level old-level)))
8387 (delta (if (> shift 0) -1 1))
8388 (func (if (> shift 0) 'org-demote 'org-promote))
8389 (org-odd-levels-only nil)
8390 beg end newend)
8391 ;; Remove the forced level indicator
8392 (if force-level
8393 (delete-region (point-at-bol) (point)))
8394 ;; Paste
8395 (beginning-of-line (if (bolp) 1 2))
8396 (setq beg (point))
8397 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8398 (insert-before-markers txt)
8399 (unless (string-match "\n\\'" txt) (insert "\n"))
8400 (setq newend (point))
8401 (org-reinstall-markers-in-region beg)
8402 (setq end (point))
8403 (goto-char beg)
8404 (skip-chars-forward " \t\n\r")
8405 (setq beg (point))
8406 (if (and (outline-invisible-p) visp)
8407 (save-excursion (outline-show-heading)))
8408 ;; Shift if necessary
8409 (unless (= shift 0)
8410 (save-restriction
8411 (narrow-to-region beg end)
8412 (while (not (= shift 0))
8413 (org-map-region func (point-min) (point-max))
8414 (setq shift (+ delta shift)))
8415 (goto-char (point-min))
8416 (setq newend (point-max))))
8417 (when (or (org-called-interactively-p 'interactive) for-yank)
8418 (message "Clipboard pasted as level %d subtree" new-level))
8419 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8420 kill-ring
8421 (eq org-subtree-clip (current-kill 0))
8422 org-subtree-clip-folded)
8423 ;; The tree was folded before it was killed/copied
8424 (hide-subtree))
8425 (and for-yank (goto-char newend)))))
8427 (defun org-kill-is-subtree-p (&optional txt)
8428 "Check if the current kill is an outline subtree, or a set of trees.
8429 Returns nil if kill does not start with a headline, or if the first
8430 headline level is not the largest headline level in the tree.
8431 So this will actually accept several entries of equal levels as well,
8432 which is OK for `org-paste-subtree'.
8433 If optional TXT is given, check this string instead of the current kill."
8434 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8435 (re (org-get-limited-outline-regexp))
8436 (^re (concat "^" re))
8437 (start-level (and kill
8438 (string-match
8439 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8440 kill)
8441 (- (match-end 2) (match-beginning 2) 1)))
8442 (start (1+ (or (match-beginning 2) -1))))
8443 (if (not start-level)
8444 (progn
8445 nil) ;; does not even start with a heading
8446 (catch 'exit
8447 (while (setq start (string-match ^re kill (1+ start)))
8448 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8449 (throw 'exit nil)))
8450 t))))
8452 (defvar org-markers-to-move nil
8453 "Markers that should be moved with a cut-and-paste operation.
8454 Those markers are stored together with their positions relative to
8455 the start of the region.")
8457 (defun org-save-markers-in-region (beg end)
8458 "Check markers in region.
8459 If these markers are between BEG and END, record their position relative
8460 to BEG, so that after moving the block of text, we can put the markers back
8461 into place.
8462 This function gets called just before an entry or tree gets cut from the
8463 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8464 called immediately, to move the markers with the entries."
8465 (setq org-markers-to-move nil)
8466 (when (featurep 'org-clock)
8467 (org-clock-save-markers-for-cut-and-paste beg end))
8468 (when (featurep 'org-agenda)
8469 (org-agenda-save-markers-for-cut-and-paste beg end)))
8471 (defun org-check-and-save-marker (marker beg end)
8472 "Check if MARKER is between BEG and END.
8473 If yes, remember the marker and the distance to BEG."
8474 (when (and (marker-buffer marker)
8475 (equal (marker-buffer marker) (current-buffer)))
8476 (if (and (>= marker beg) (< marker end))
8477 (push (cons marker (- marker beg)) org-markers-to-move))))
8479 (defun org-reinstall-markers-in-region (beg)
8480 "Move all remembered markers to their position relative to BEG."
8481 (mapc (lambda (x)
8482 (move-marker (car x) (+ beg (cdr x))))
8483 org-markers-to-move)
8484 (setq org-markers-to-move nil))
8486 (defun org-narrow-to-subtree ()
8487 "Narrow buffer to the current subtree."
8488 (interactive)
8489 (save-excursion
8490 (save-match-data
8491 (org-with-limited-levels
8492 (narrow-to-region
8493 (progn (org-back-to-heading t) (point))
8494 (progn (org-end-of-subtree t t)
8495 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8496 (point)))))))
8498 (defun org-narrow-to-block ()
8499 "Narrow buffer to the current block."
8500 (interactive)
8501 (let* ((case-fold-search t)
8502 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8503 "^[ \t]*#\\+end_.*")))
8504 (if blockp
8505 (narrow-to-region (car blockp) (cdr blockp))
8506 (user-error "Not in a block"))))
8508 (eval-when-compile
8509 (defvar org-property-drawer-re))
8511 (defvar org-property-start-re) ;; defined below
8512 (defun org-clone-subtree-with-time-shift (n &optional shift)
8513 "Clone the task (subtree) at point N times.
8514 The clones will be inserted as siblings.
8516 In interactive use, the user will be prompted for the number of
8517 clones to be produced. If the entry has a timestamp, the user
8518 will also be prompted for a time shift, which may be a repeater
8519 as used in time stamps, for example `+3d'. To disable this,
8520 you can call the function with a universal prefix argument.
8522 When a valid repeater is given and the entry contains any time
8523 stamps, the clones will become a sequence in time, with time
8524 stamps in the subtree shifted for each clone produced. If SHIFT
8525 is nil or the empty string, time stamps will be left alone. The
8526 ID property of the original subtree is removed.
8528 If the original subtree did contain time stamps with a repeater,
8529 the following will happen:
8530 - the repeater will be removed in each clone
8531 - an additional clone will be produced, with the current, unshifted
8532 date(s) in the entry.
8533 - the original entry will be placed *after* all the clones, with
8534 repeater intact.
8535 - the start days in the repeater in the original entry will be shifted
8536 to past the last clone.
8537 In this way you can spell out a number of instances of a repeating task,
8538 and still retain the repeater to cover future instances of the task."
8539 (interactive "nNumber of clones to produce: ")
8540 (let ((shift
8541 (or shift
8542 (if (and (not (equal current-prefix-arg '(4)))
8543 (save-excursion
8544 (re-search-forward org-ts-regexp-both
8545 (save-excursion
8546 (org-end-of-subtree t)
8547 (point)) t)))
8548 (read-from-minibuffer
8549 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8550 ""))) ;; No time shift
8551 (n-no-remove -1)
8552 (drawer-re org-drawer-regexp)
8553 beg end template task idprop
8554 shift-n shift-what doshift nmin nmax)
8555 (if (not (and (integerp n) (> n 0)))
8556 (error "Invalid number of replications %s" n))
8557 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8558 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8559 shift)))
8560 (error "Invalid shift specification %s" shift))
8561 (when doshift
8562 (setq shift-n (string-to-number (match-string 1 shift))
8563 shift-what (cdr (assoc (match-string 2 shift)
8564 '(("d" . day) ("w" . week)
8565 ("m" . month) ("y" . year))))))
8566 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8567 (setq nmin 1 nmax n)
8568 (org-back-to-heading t)
8569 (setq beg (point))
8570 (setq idprop (org-entry-get nil "ID"))
8571 (org-end-of-subtree t t)
8572 (or (bolp) (insert "\n"))
8573 (setq end (point))
8574 (setq template (buffer-substring beg end))
8575 (when (and doshift
8576 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8577 (delete-region beg end)
8578 (setq end beg)
8579 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8580 (goto-char end)
8581 (loop for n from nmin to nmax do
8582 ;; prepare clone
8583 (with-temp-buffer
8584 (insert template)
8585 (org-mode)
8586 (goto-char (point-min))
8587 (org-show-subtree)
8588 (and idprop (if org-clone-delete-id
8589 (org-entry-delete nil "ID")
8590 (org-id-get-create t)))
8591 (unless (= n 0)
8592 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8593 (kill-whole-line))
8594 (goto-char (point-min))
8595 (while (re-search-forward drawer-re nil t)
8596 (org-remove-empty-drawer-at (point))))
8597 (goto-char (point-min))
8598 (when doshift
8599 (while (re-search-forward org-ts-regexp-both nil t)
8600 (org-timestamp-change (* n shift-n) shift-what))
8601 (unless (= n n-no-remove)
8602 (goto-char (point-min))
8603 (while (re-search-forward org-ts-regexp nil t)
8604 (save-excursion
8605 (goto-char (match-beginning 0))
8606 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8607 (delete-region (match-beginning 1) (match-end 1)))))))
8608 (setq task (buffer-string)))
8609 (insert task))
8610 (goto-char beg)))
8612 ;;; Outline Sorting
8614 (defun org-sort (with-case)
8615 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8616 Optional argument WITH-CASE means sort case-sensitively."
8617 (interactive "P")
8618 (cond
8619 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8620 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8622 (org-call-with-arg 'org-sort-entries with-case))))
8624 (defun org-sort-remove-invisible (s)
8625 "Remove invisible links from string S."
8626 (remove-text-properties 0 (length s) org-rm-props s)
8627 (while (string-match org-bracket-link-regexp s)
8628 (setq s (replace-match (if (match-end 2)
8629 (match-string 3 s)
8630 (match-string 1 s)) t t s)))
8631 (let ((st (format " %s " s)))
8632 (while (string-match org-emph-re st)
8633 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8634 (setq s (substring st 1 -1)))
8637 (defvar org-priority-regexp) ; defined later in the file
8639 (defvar org-after-sorting-entries-or-items-hook nil
8640 "Hook that is run after a bunch of entries or items have been sorted.
8641 When children are sorted, the cursor is in the parent line when this
8642 hook gets called. When a region or a plain list is sorted, the cursor
8643 will be in the first entry of the sorted region/list.")
8645 (defun org-sort-entries
8646 (&optional with-case sorting-type getkey-func compare-func property)
8647 "Sort entries on a certain level of an outline tree.
8648 If there is an active region, the entries in the region are sorted.
8649 Else, if the cursor is before the first entry, sort the top-level items.
8650 Else, the children of the entry at point are sorted.
8652 Sorting can be alphabetically, numerically, by date/time as given by
8653 a time stamp, by a property, by priority order, or by a custom function.
8655 The command prompts for the sorting type unless it has been given to the
8656 function through the SORTING-TYPE argument, which needs to be a character,
8657 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8658 precise meaning of each character:
8660 n Numerically, by converting the beginning of the entry/item to a number.
8661 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8662 o By order of TODO keywords.
8663 t By date/time, either the first active time stamp in the entry, or, if
8664 none exist, by the first inactive one.
8665 s By the scheduled date/time.
8666 d By deadline date/time.
8667 c By creation time, which is assumed to be the first inactive time stamp
8668 at the beginning of a line.
8669 p By priority according to the cookie.
8670 r By the value of a property.
8672 Capital letters will reverse the sort order.
8674 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8675 called with point at the beginning of the record. It must return either
8676 a string or a number that should serve as the sorting key for that record.
8678 Comparing entries ignores case by default. However, with an optional argument
8679 WITH-CASE, the sorting considers case as well.
8681 Sorting is done against the visible part of the headlines, it ignores hidden
8682 links.
8684 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
8685 (interactive "P")
8686 (let ((case-func (if with-case 'identity 'downcase))
8687 (cmstr
8688 ;; The clock marker is lost when using `sort-subr', let's
8689 ;; store the clocking string.
8690 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8691 (save-excursion
8692 (goto-char org-clock-marker)
8693 (looking-back "^.*") (match-string-no-properties 0))))
8694 start beg end stars re re2
8695 txt what tmp)
8696 ;; Find beginning and end of region to sort
8697 (cond
8698 ((org-region-active-p)
8699 ;; we will sort the region
8700 (setq end (region-end)
8701 what "region")
8702 (goto-char (region-beginning))
8703 (if (not (org-at-heading-p)) (outline-next-heading))
8704 (setq start (point)))
8705 ((or (org-at-heading-p)
8706 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8707 ;; we will sort the children of the current headline
8708 (org-back-to-heading)
8709 (setq start (point)
8710 end (progn (org-end-of-subtree t t)
8711 (or (bolp) (insert "\n"))
8712 (org-back-over-empty-lines)
8713 (point))
8714 what "children")
8715 (goto-char start)
8716 (show-subtree)
8717 (outline-next-heading))
8719 ;; we will sort the top-level entries in this file
8720 (goto-char (point-min))
8721 (or (org-at-heading-p) (outline-next-heading))
8722 (setq start (point))
8723 (goto-char (point-max))
8724 (beginning-of-line 1)
8725 (when (looking-at ".*?\\S-")
8726 ;; File ends in a non-white line
8727 (end-of-line 1)
8728 (insert "\n"))
8729 (setq end (point-max))
8730 (setq what "top-level")
8731 (goto-char start)
8732 (show-all)))
8734 (setq beg (point))
8735 (if (>= beg end) (user-error "Nothing to sort"))
8737 (looking-at "\\(\\*+\\)")
8738 (setq stars (match-string 1)
8739 re (concat "^" (regexp-quote stars) " +")
8740 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8741 txt (buffer-substring beg end))
8742 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8743 (if (and (not (equal stars "*")) (string-match re2 txt))
8744 (user-error "Region to sort contains a level above the first entry"))
8746 (unless sorting-type
8747 (message
8748 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8749 [t]ime [s]cheduled [d]eadline [c]reated
8750 A/N/P/R/O/F/T/S/D/C means reversed:"
8751 what)
8752 (setq sorting-type (read-char-exclusive))
8754 (unless getkey-func
8755 (and (= (downcase sorting-type) ?f)
8756 (setq getkey-func
8757 (org-icompleting-read "Sort using function: "
8758 obarray 'fboundp t nil nil))
8759 (setq getkey-func (intern getkey-func))))
8761 (and (= (downcase sorting-type) ?r)
8762 (not property)
8763 (setq property
8764 (org-icompleting-read "Property: "
8765 (mapcar 'list (org-buffer-property-keys t))
8766 nil t))))
8768 (message "Sorting entries...")
8770 (save-restriction
8771 (narrow-to-region start end)
8772 (let ((dcst (downcase sorting-type))
8773 (case-fold-search nil)
8774 (now (current-time)))
8775 (sort-subr
8776 (/= dcst sorting-type)
8777 ;; This function moves to the beginning character of the "record" to
8778 ;; be sorted.
8779 (lambda nil
8780 (if (re-search-forward re nil t)
8781 (goto-char (match-beginning 0))
8782 (goto-char (point-max))))
8783 ;; This function moves to the last character of the "record" being
8784 ;; sorted.
8785 (lambda nil
8786 (save-match-data
8787 (condition-case nil
8788 (outline-forward-same-level 1)
8789 (error
8790 (goto-char (point-max))))))
8791 ;; This function returns the value that gets sorted against.
8792 (lambda nil
8793 (cond
8794 ((= dcst ?n)
8795 (if (looking-at org-complex-heading-regexp)
8796 (string-to-number (org-sort-remove-invisible (match-string 4)))
8797 nil))
8798 ((= dcst ?a)
8799 (if (looking-at org-complex-heading-regexp)
8800 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8801 nil))
8802 ((= dcst ?t)
8803 (let ((end (save-excursion (outline-next-heading) (point))))
8804 (if (or (re-search-forward org-ts-regexp end t)
8805 (re-search-forward org-ts-regexp-both end t))
8806 (org-time-string-to-seconds (match-string 0))
8807 (org-float-time now))))
8808 ((= dcst ?c)
8809 (let ((end (save-excursion (outline-next-heading) (point))))
8810 (if (re-search-forward
8811 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8812 end t)
8813 (org-time-string-to-seconds (match-string 0))
8814 (org-float-time now))))
8815 ((= dcst ?s)
8816 (let ((end (save-excursion (outline-next-heading) (point))))
8817 (if (re-search-forward org-scheduled-time-regexp end t)
8818 (org-time-string-to-seconds (match-string 1))
8819 (org-float-time now))))
8820 ((= dcst ?d)
8821 (let ((end (save-excursion (outline-next-heading) (point))))
8822 (if (re-search-forward org-deadline-time-regexp end t)
8823 (org-time-string-to-seconds (match-string 1))
8824 (org-float-time now))))
8825 ((= dcst ?p)
8826 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8827 (string-to-char (match-string 2))
8828 org-default-priority))
8829 ((= dcst ?r)
8830 (or (org-entry-get nil property) ""))
8831 ((= dcst ?o)
8832 (if (looking-at org-complex-heading-regexp)
8833 (- 9999 (length (member (match-string 2)
8834 org-todo-keywords-1)))))
8835 ((= dcst ?f)
8836 (if getkey-func
8837 (progn
8838 (setq tmp (funcall getkey-func))
8839 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8840 tmp)
8841 (error "Invalid key function `%s'" getkey-func)))
8842 (t (error "Invalid sorting type `%c'" sorting-type))))
8844 (cond
8845 ((= dcst ?a) 'string<)
8846 ((= dcst ?f) compare-func)
8847 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8848 (run-hooks 'org-after-sorting-entries-or-items-hook)
8849 ;; Reset the clock marker if needed
8850 (when cmstr
8851 (save-excursion
8852 (goto-char start)
8853 (search-forward cmstr nil t)
8854 (move-marker org-clock-marker (point))))
8855 (message "Sorting entries...done")))
8857 (defun org-do-sort (table what &optional with-case sorting-type)
8858 "Sort TABLE of WHAT according to SORTING-TYPE.
8859 The user will be prompted for the SORTING-TYPE if the call to this
8860 function does not specify it. WHAT is only for the prompt, to indicate
8861 what is being sorted. The sorting key will be extracted from
8862 the car of the elements of the table.
8863 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8864 (unless sorting-type
8865 (message
8866 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8867 what)
8868 (setq sorting-type (read-char-exclusive)))
8869 (let ((dcst (downcase sorting-type))
8870 extractfun comparefun)
8871 ;; Define the appropriate functions
8872 (cond
8873 ((= dcst ?n)
8874 (setq extractfun 'string-to-number
8875 comparefun (if (= dcst sorting-type) '< '>)))
8876 ((= dcst ?a)
8877 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8878 (lambda(x) (downcase (org-sort-remove-invisible x))))
8879 comparefun (if (= dcst sorting-type)
8880 'string<
8881 (lambda (a b) (and (not (string< a b))
8882 (not (string= a b)))))))
8883 ((= dcst ?t)
8884 (setq extractfun
8885 (lambda (x)
8886 (if (or (string-match org-ts-regexp x)
8887 (string-match org-ts-regexp-both x))
8888 (org-float-time
8889 (org-time-string-to-time (match-string 0 x)))
8891 comparefun (if (= dcst sorting-type) '< '>)))
8892 (t (error "Invalid sorting type `%c'" sorting-type)))
8894 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8895 table)
8896 (lambda (a b) (funcall comparefun (car a) (car b))))))
8899 ;;; The orgstruct minor mode
8901 ;; Define a minor mode which can be used in other modes in order to
8902 ;; integrate the org-mode structure editing commands.
8904 ;; This is really a hack, because the org-mode structure commands use
8905 ;; keys which normally belong to the major mode. Here is how it
8906 ;; works: The minor mode defines all the keys necessary to operate the
8907 ;; structure commands, but wraps the commands into a function which
8908 ;; tests if the cursor is currently at a headline or a plain list
8909 ;; item. If that is the case, the structure command is used,
8910 ;; temporarily setting many Org-mode variables like regular
8911 ;; expressions for filling etc. However, when any of those keys is
8912 ;; used at a different location, function uses `key-binding' to look
8913 ;; up if the key has an associated command in another currently active
8914 ;; keymap (minor modes, major mode, global), and executes that
8915 ;; command. There might be problems if any of the keys is otherwise
8916 ;; used as a prefix key.
8918 (defcustom orgstruct-heading-prefix-regexp ""
8919 "Regexp that matches the custom prefix of Org headlines in
8920 orgstruct(++)-mode."
8921 :group 'org
8922 :version "24.4"
8923 :package-version '(Org . "8.3")
8924 :type 'regexp)
8925 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8927 (defcustom orgstruct-setup-hook nil
8928 "Hook run after orgstruct-mode-map is filled."
8929 :group 'org
8930 :version "24.4"
8931 :package-version '(Org . "8.0")
8932 :type 'hook)
8934 (defvar orgstruct-initialized nil)
8936 (defvar org-local-vars nil
8937 "List of local variables, for use by `orgstruct-mode'.")
8939 ;;;###autoload
8940 (define-minor-mode orgstruct-mode
8941 "Toggle the minor mode `orgstruct-mode'.
8942 This mode is for using Org-mode structure commands in other
8943 modes. The following keys behave as if Org-mode were active, if
8944 the cursor is on a headline, or on a plain list item (both as
8945 defined by Org-mode)."
8946 nil " OrgStruct" (make-sparse-keymap)
8947 (funcall (if orgstruct-mode
8948 'add-to-invisibility-spec
8949 'remove-from-invisibility-spec)
8950 '(outline . t))
8951 (when orgstruct-mode
8952 (org-load-modules-maybe)
8953 (unless orgstruct-initialized
8954 (orgstruct-setup)
8955 (setq orgstruct-initialized t))))
8957 ;;;###autoload
8958 (defun turn-on-orgstruct ()
8959 "Unconditionally turn on `orgstruct-mode'."
8960 (orgstruct-mode 1))
8962 (defvar org-fb-vars nil)
8963 (make-variable-buffer-local 'org-fb-vars)
8964 (defun orgstruct++-mode (&optional arg)
8965 "Toggle `orgstruct-mode', the enhanced version of it.
8966 In addition to setting orgstruct-mode, this also exports all
8967 indentation and autofilling variables from org-mode into the
8968 buffer. It will also recognize item context in multiline items."
8969 (interactive "P")
8970 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8971 (if (< arg 1)
8972 (progn (orgstruct-mode -1)
8973 (mapc (lambda(v)
8974 (org-set-local (car v)
8975 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8976 org-fb-vars))
8977 (orgstruct-mode 1)
8978 (setq org-fb-vars nil)
8979 (unless org-local-vars
8980 (setq org-local-vars (org-get-local-variables)))
8981 (let (var val)
8982 (mapc
8983 (lambda (x)
8984 (when (string-match
8985 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8986 (symbol-name (car x)))
8987 (setq var (car x) val (nth 1 x))
8988 (push (list var `(quote ,(eval var))) org-fb-vars)
8989 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8990 org-local-vars)
8991 (org-set-local 'orgstruct-is-++ t))))
8993 (defvar orgstruct-is-++ nil
8994 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8995 (make-variable-buffer-local 'orgstruct-is-++)
8997 ;;;###autoload
8998 (defun turn-on-orgstruct++ ()
8999 "Unconditionally turn on `orgstruct++-mode'."
9000 (orgstruct++-mode 1))
9002 (defun orgstruct-error ()
9003 "Error when there is no default binding for a structure key."
9004 (interactive)
9005 (funcall (if (fboundp 'user-error)
9006 'user-error
9007 'error)
9008 "This key has no function outside structure elements"))
9010 (defun orgstruct-setup ()
9011 "Setup orgstruct keymap."
9012 (dolist (cell '((org-demote . t)
9013 (org-metaleft . t)
9014 (org-metaright . t)
9015 (org-promote . t)
9016 (org-shiftmetaleft . t)
9017 (org-shiftmetaright . t)
9018 org-backward-element
9019 org-backward-heading-same-level
9020 org-ctrl-c-ret
9021 org-ctrl-c-minus
9022 org-ctrl-c-star
9023 org-cycle
9024 org-forward-heading-same-level
9025 org-insert-heading
9026 org-insert-heading-respect-content
9027 org-kill-note-or-show-branches
9028 org-mark-subtree
9029 org-meta-return
9030 org-metadown
9031 org-metaup
9032 org-narrow-to-subtree
9033 org-promote-subtree
9034 org-reveal
9035 org-shiftdown
9036 org-shiftleft
9037 org-shiftmetadown
9038 org-shiftmetaup
9039 org-shiftright
9040 org-shifttab
9041 org-shifttab
9042 org-shiftup
9043 org-show-subtree
9044 org-sort
9045 org-up-element
9046 outline-demote
9047 outline-next-visible-heading
9048 outline-previous-visible-heading
9049 outline-promote
9050 outline-up-heading
9051 show-children))
9052 (let ((f (or (car-safe cell) cell))
9053 (disable-when-heading-prefix (cdr-safe cell)))
9054 (when (fboundp f)
9055 (let ((new-bindings))
9056 (dolist (binding (nconc (where-is-internal f org-mode-map)
9057 (where-is-internal f outline-mode-map)))
9058 (push binding new-bindings)
9059 ;; TODO use local-function-key-map
9060 (dolist (rep '(("<tab>" . "TAB")
9061 ("<return>" . "RET")
9062 ("<escape>" . "ESC")
9063 ("<delete>" . "DEL")))
9064 (setq binding (read-kbd-macro
9065 (let ((case-fold-search))
9066 (replace-regexp-in-string
9067 (regexp-quote (cdr rep))
9068 (car rep)
9069 (key-description binding)))))
9070 (pushnew binding new-bindings :test 'equal)))
9071 (dolist (binding new-bindings)
9072 (let ((key (lookup-key orgstruct-mode-map binding)))
9073 (when (or (not key) (numberp key))
9074 (condition-case nil
9075 (org-defkey orgstruct-mode-map
9076 binding
9077 (orgstruct-make-binding f binding disable-when-heading-prefix))
9078 (error nil)))))))))
9079 (run-hooks 'orgstruct-setup-hook))
9081 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9082 "Create a function for binding in the structure minor mode.
9083 FUN is the command to call inside a table. KEY is the key that
9084 should be checked in for a command to execute outside of tables.
9085 Non-nil `disable-when-heading-prefix' means to disable the command
9086 if `orgstruct-heading-prefix-regexp' is not empty."
9087 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9088 (let ((nname name)
9089 (i 0))
9090 (while (fboundp (intern nname))
9091 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9092 (setq name (intern nname)))
9093 (eval
9094 (let ((bindings '((org-heading-regexp
9095 (concat "^"
9096 orgstruct-heading-prefix-regexp
9097 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9098 (org-outline-regexp
9099 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9100 (org-outline-regexp-bol
9101 (concat "^" org-outline-regexp))
9102 (outline-regexp org-outline-regexp)
9103 (outline-heading-end-regexp "\n")
9104 (outline-level 'org-outline-level)
9105 (outline-heading-alist))))
9106 `(defun ,name (arg)
9107 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9108 "Outside of structure, run the binding of `"
9109 (key-description key) "'."
9110 (when disable-when-heading-prefix
9111 (concat
9112 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9113 "back to the default binding due to limitations of Org's implementation of\n"
9114 "`" (symbol-name fun) "'.")))
9115 (interactive "p")
9116 (let* ((disable
9117 ,(and disable-when-heading-prefix
9118 '(not (string= orgstruct-heading-prefix-regexp ""))))
9119 (fallback
9120 (or disable
9121 (not
9122 (let* ,bindings
9123 (org-context-p 'headline 'item
9124 ,(when (memq fun
9125 '(org-insert-heading
9126 org-insert-heading-respect-content
9127 org-meta-return))
9128 '(when orgstruct-is-++
9129 'item-body))))))))
9130 (if fallback
9131 (let* ((orgstruct-mode)
9132 (binding
9133 (loop with key = ,key
9134 for rep in
9135 '(nil
9136 ("<\\([^>]*\\)tab>" . "\\1TAB")
9137 ("<\\([^>]*\\)return>" . "\\1RET")
9138 ("<\\([^>]*\\)escape>" . "\\1ESC")
9139 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9141 (when rep
9142 (setq key (read-kbd-macro
9143 (let ((case-fold-search))
9144 (replace-regexp-in-string
9145 (car rep)
9146 (cdr rep)
9147 (key-description key))))))
9148 thereis (key-binding key))))
9149 (if (keymapp binding)
9150 (set-transient-map binding)
9151 (let ((func (or binding
9152 (unless disable
9153 'orgstruct-error))))
9154 (when func
9155 (call-interactively func)))))
9156 (org-run-like-in-org-mode
9157 (lambda ()
9158 (interactive)
9159 (let* ,bindings
9160 (call-interactively ',fun)))))))))
9161 name))
9163 (defun org-contextualize-keys (alist contexts)
9164 "Return valid elements in ALIST depending on CONTEXTS.
9166 `org-agenda-custom-commands' or `org-capture-templates' are the
9167 values used for ALIST, and `org-agenda-custom-commands-contexts'
9168 or `org-capture-templates-contexts' are the associated contexts
9169 definitions."
9170 (let ((contexts
9171 ;; normalize contexts
9172 (mapcar
9173 (lambda(c) (cond ((listp (cadr c))
9174 (list (car c) (car c) (cadr c)))
9175 ((string= "" (cadr c))
9176 (list (car c) (car c) (caddr c)))
9177 (t c))) contexts))
9178 (a alist) c r s)
9179 ;; loop over all commands or templates
9180 (while (setq c (pop a))
9181 (let (vrules repl)
9182 (cond
9183 ((not (assoc (car c) contexts))
9184 (push c r))
9185 ((and (assoc (car c) contexts)
9186 (setq vrules (org-contextualize-validate-key
9187 (car c) contexts)))
9188 (mapc (lambda (vr)
9189 (when (not (equal (car vr) (cadr vr)))
9190 (setq repl vr))) vrules)
9191 (if (not repl) (push c r)
9192 (push (cadr repl) s)
9193 (push
9194 (cons (car c)
9195 (cdr (or (assoc (cadr repl) alist)
9196 (error "Undefined key `%s' as contextual replacement for `%s'"
9197 (cadr repl) (car c)))))
9198 r))))))
9199 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9200 (delq
9202 (delete-dups
9203 (mapcar (lambda (x)
9204 (let ((tpl (car x)))
9205 (when (not (delq
9207 (mapcar (lambda(y)
9208 (equal y tpl)) s))) x)))
9209 (reverse r))))))
9211 (defun org-contextualize-validate-key (key contexts)
9212 "Check CONTEXTS for agenda or capture KEY."
9213 (let (r rr res)
9214 (while (setq r (pop contexts))
9215 (mapc
9216 (lambda (rr)
9217 (when
9218 (and (equal key (car r))
9219 (if (functionp rr) (funcall rr)
9220 (or (and (eq (car rr) 'in-file)
9221 (buffer-file-name)
9222 (string-match (cdr rr) (buffer-file-name)))
9223 (and (eq (car rr) 'in-mode)
9224 (string-match (cdr rr) (symbol-name major-mode)))
9225 (and (eq (car rr) 'in-buffer)
9226 (string-match (cdr rr) (buffer-name)))
9227 (when (and (eq (car rr) 'not-in-file)
9228 (buffer-file-name))
9229 (not (string-match (cdr rr) (buffer-file-name))))
9230 (when (eq (car rr) 'not-in-mode)
9231 (not (string-match (cdr rr) (symbol-name major-mode))))
9232 (when (eq (car rr) 'not-in-buffer)
9233 (not (string-match (cdr rr) (buffer-name)))))))
9234 (push r res)))
9235 (car (last r))))
9236 (delete-dups (delq nil res))))
9238 (defun org-context-p (&rest contexts)
9239 "Check if local context is any of CONTEXTS.
9240 Possible values in the list of contexts are `table', `headline', and `item'."
9241 (let ((pos (point)))
9242 (goto-char (point-at-bol))
9243 (prog1 (or (and (memq 'table contexts)
9244 (looking-at "[ \t]*|"))
9245 (and (memq 'headline contexts)
9246 (looking-at org-outline-regexp))
9247 (and (memq 'item contexts)
9248 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9249 (and (memq 'item-body contexts)
9250 (org-in-item-p)))
9251 (goto-char pos))))
9253 (defun org-get-local-variables ()
9254 "Return a list of all local variables in an Org mode buffer."
9255 (let (varlist)
9256 (with-current-buffer (get-buffer-create "*Org tmp*")
9257 (erase-buffer)
9258 (org-mode)
9259 (setq varlist (buffer-local-variables)))
9260 (kill-buffer "*Org tmp*")
9261 (delq nil
9262 (mapcar
9263 (lambda (x)
9264 (setq x
9265 (if (symbolp x)
9266 (list x)
9267 (list (car x) (cdr x))))
9268 (if (and (not (get (car x) 'org-state))
9269 (string-match
9270 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9271 (symbol-name (car x))))
9272 x nil))
9273 varlist))))
9275 (defun org-clone-local-variables (from-buffer &optional regexp)
9276 "Clone local variables from FROM-BUFFER.
9277 Optional argument REGEXP selects variables to clone."
9278 (mapc
9279 (lambda (pair)
9280 (and (symbolp (car pair))
9281 (or (null regexp)
9282 (string-match regexp (symbol-name (car pair))))
9283 (set (make-local-variable (car pair))
9284 (cdr pair))))
9285 (buffer-local-variables from-buffer)))
9287 ;;;###autoload
9288 (defun org-run-like-in-org-mode (cmd)
9289 "Run a command, pretending that the current buffer is in Org-mode.
9290 This will temporarily bind local variables that are typically bound in
9291 Org-mode to the values they have in Org-mode, and then interactively
9292 call CMD."
9293 (org-load-modules-maybe)
9294 (unless org-local-vars
9295 (setq org-local-vars (org-get-local-variables)))
9296 (let (binds)
9297 (dolist (var org-local-vars)
9298 (when (or (not (boundp (car var)))
9299 (eq (symbol-value (car var))
9300 (default-value (car var))))
9301 (push (list (car var) `(quote ,(cadr var))) binds)))
9302 (eval `(let ,binds
9303 (call-interactively (quote ,cmd))))))
9305 ;;;; Archiving
9307 (defun org-get-category (&optional pos force-refresh)
9308 "Get the category applying to position POS."
9309 (save-match-data
9310 (if force-refresh (org-refresh-category-properties))
9311 (let ((pos (or pos (point))))
9312 (or (get-text-property pos 'org-category)
9313 (progn (org-refresh-category-properties)
9314 (get-text-property pos 'org-category))))))
9316 (defun org-refresh-category-properties ()
9317 "Refresh category text properties in the buffer."
9318 (let ((case-fold-search t)
9319 (inhibit-read-only t)
9320 (def-cat (cond
9321 ((null org-category)
9322 (if buffer-file-name
9323 (file-name-sans-extension
9324 (file-name-nondirectory buffer-file-name))
9325 "???"))
9326 ((symbolp org-category) (symbol-name org-category))
9327 (t org-category)))
9328 beg end cat pos optionp)
9329 (org-with-silent-modifications
9330 (save-excursion
9331 (save-restriction
9332 (widen)
9333 (goto-char (point-min))
9334 (put-text-property (point) (point-max) 'org-category def-cat)
9335 (while (re-search-forward
9336 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9337 (setq pos (match-end 0)
9338 optionp (equal (char-after (match-beginning 0)) ?#)
9339 cat (org-trim (match-string 2)))
9340 (if optionp
9341 (setq beg (point-at-bol) end (point-max))
9342 (org-back-to-heading t)
9343 (setq beg (point) end (org-end-of-subtree t t)))
9344 (put-text-property beg end 'org-category cat)
9345 (put-text-property beg end 'org-category-position beg)
9346 (goto-char pos)))))))
9348 (defun org-refresh-properties (dprop tprop)
9349 "Refresh buffer text properties.
9350 DPROP is the drawer property and TPROP is the corresponding text
9351 property to set."
9352 (let ((case-fold-search t)
9353 (inhibit-read-only t) p)
9354 (org-with-silent-modifications
9355 (save-excursion
9356 (save-restriction
9357 (widen)
9358 (goto-char (point-min))
9359 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9360 (setq p (org-match-string-no-properties 1))
9361 (save-excursion
9362 (org-back-to-heading t)
9363 (put-text-property
9364 (point-at-bol) (org-end-of-subtree t t) tprop p))))))))
9367 ;;;; Link Stuff
9369 ;;; Link abbreviations
9371 (defun org-link-expand-abbrev (link)
9372 "Apply replacements as defined in `org-link-abbrev-alist'."
9373 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9374 (let* ((key (match-string 1 link))
9375 (as (or (assoc key org-link-abbrev-alist-local)
9376 (assoc key org-link-abbrev-alist)))
9377 (tag (and (match-end 2) (match-string 3 link)))
9378 rpl)
9379 (if (not as)
9380 link
9381 (setq rpl (cdr as))
9382 (cond
9383 ((symbolp rpl) (funcall rpl tag))
9384 ((string-match "%(\\([^)]+\\))" rpl)
9385 (replace-match
9386 (save-match-data
9387 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9388 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9389 ((string-match "%h" rpl)
9390 (replace-match (url-hexify-string (or tag "")) t t rpl))
9391 (t (concat rpl tag)))))
9392 link))
9394 ;;; Storing and inserting links
9396 (defvar org-insert-link-history nil
9397 "Minibuffer history for links inserted with `org-insert-link'.")
9399 (defvar org-stored-links nil
9400 "Contains the links stored with `org-store-link'.")
9402 (defvar org-store-link-plist nil
9403 "Plist with info about the most recently link created with `org-store-link'.")
9405 (defvar org-link-protocols nil
9406 "Link protocols added to Org-mode using `org-add-link-type'.")
9408 (defvar org-store-link-functions nil
9409 "List of functions that are called to create and store a link.
9410 Each function will be called in turn until one returns a non-nil
9411 value. Each function should check if it is responsible for creating
9412 this link (for example by looking at the major mode).
9413 If not, it must exit and return nil.
9414 If yes, it should return a non-nil value after a calling
9415 `org-store-link-props' with a list of properties and values.
9416 Special properties are:
9418 :type The link prefix, like \"http\". This must be given.
9419 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9420 This is obligatory as well.
9421 :description Optional default description for the second pair
9422 of brackets in an Org-mode link. The user can still change
9423 this when inserting this link into an Org-mode buffer.
9425 In addition to these, any additional properties can be specified
9426 and then used in capture templates.")
9428 (defun org-add-link-type (type &optional follow export)
9429 "Add TYPE to the list of `org-link-types'.
9430 Re-compute all regular expressions depending on `org-link-types'
9432 FOLLOW and EXPORT are two functions.
9434 FOLLOW should take the link path as the single argument and do whatever
9435 is necessary to follow the link, for example find a file or display
9436 a mail message.
9438 EXPORT should format the link path for export to one of the export formats.
9439 It should be a function accepting three arguments:
9441 path the path of the link, the text after the prefix (like \"http:\")
9442 desc the description of the link, if any, or a description added by
9443 org-export-normalize-links if there is none
9444 format the export format, a symbol like `html' or `latex' or `ascii'..
9446 The function may use the FORMAT information to return different values
9447 depending on the format. The return value will be put literally into
9448 the exported file. If the return value is nil, this means Org should
9449 do what it normally does with links which do not have EXPORT defined.
9451 Org-mode has a built-in default for exporting links. If you are happy with
9452 this default, there is no need to define an export function for the link
9453 type. For a simple example of an export function, see `org-bbdb.el'."
9454 (add-to-list 'org-link-types type t)
9455 (org-make-link-regexps)
9456 (if (assoc type org-link-protocols)
9457 (setcdr (assoc type org-link-protocols) (list follow export))
9458 (push (list type follow export) org-link-protocols)))
9460 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9461 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9463 ;;;###autoload
9464 (defun org-store-link (arg)
9465 "\\<org-mode-map>Store an org-link to the current location.
9466 This link is added to `org-stored-links' and can later be inserted
9467 into an org-buffer with \\[org-insert-link].
9469 For some link types, a prefix arg is interpreted.
9470 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9471 For file links, arg negates `org-context-in-file-links'.
9473 A double prefix arg force skipping storing functions that are not
9474 part of Org's core.
9476 A triple prefix arg force storing a link for each line in the
9477 active region."
9478 (interactive "P")
9479 (org-load-modules-maybe)
9480 (if (and (equal arg '(64)) (org-region-active-p))
9481 (save-excursion
9482 (let ((end (region-end)))
9483 (goto-char (region-beginning))
9484 (set-mark (point))
9485 (while (< (point-at-eol) end)
9486 (move-end-of-line 1) (activate-mark)
9487 (let (current-prefix-arg)
9488 (call-interactively 'org-store-link))
9489 (move-beginning-of-line 2)
9490 (set-mark (point)))))
9491 (org-with-limited-levels
9492 (setq org-store-link-plist nil)
9493 (let (link cpltxt desc description search
9494 txt custom-id agenda-link sfuns sfunsn)
9495 (cond
9497 ;; Store a link using an external link type
9498 ((and (not (equal arg '(16)))
9499 (setq sfuns
9500 (delq
9501 nil (mapcar (lambda (f)
9502 (let (fs) (if (funcall f) (push f fs))))
9503 org-store-link-functions))
9504 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9505 (or (and (cdr sfuns)
9506 (funcall (intern
9507 (completing-read
9508 "Which function for creating the link? "
9509 sfunsn t (car sfunsn)))))
9510 (funcall (caar sfuns)))
9511 (setq link (plist-get org-store-link-plist :link)
9512 desc (or (plist-get org-store-link-plist
9513 :description) link))))
9515 ;; Store a link from a source code buffer
9516 ((org-src-edit-buffer-p)
9517 (let (label gc)
9518 (while (or (not label)
9519 (save-excursion
9520 (save-restriction
9521 (widen)
9522 (goto-char (point-min))
9523 (re-search-forward
9524 (regexp-quote (format org-coderef-label-format label))
9525 nil t))))
9526 (when label (message "Label exists already") (sit-for 2))
9527 (setq label (read-string "Code line label: " label)))
9528 (end-of-line 1)
9529 (setq link (format org-coderef-label-format label))
9530 (setq gc (- 79 (length link)))
9531 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9532 (insert link)
9533 (setq link (concat "(" label ")") desc nil)))
9535 ;; We are in the agenda, link to referenced location
9536 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9537 (let ((m (or (get-text-property (point) 'org-hd-marker)
9538 (get-text-property (point) 'org-marker))))
9539 (when m
9540 (org-with-point-at m
9541 (setq agenda-link
9542 (if (org-called-interactively-p 'any)
9543 (call-interactively 'org-store-link)
9544 (org-store-link nil)))))))
9546 ((eq major-mode 'calendar-mode)
9547 (let ((cd (calendar-cursor-to-date)))
9548 (setq link
9549 (format-time-string
9550 (car org-time-stamp-formats)
9551 (apply 'encode-time
9552 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9553 nil nil nil))))
9554 (org-store-link-props :type "calendar" :date cd)))
9556 ((eq major-mode 'help-mode)
9557 (setq link (concat "help:" (save-excursion
9558 (goto-char (point-min))
9559 (looking-at "^[^ ]+")
9560 (match-string 0))))
9561 (org-store-link-props :type "help"))
9563 ((eq major-mode 'w3-mode)
9564 (setq cpltxt (if (and (buffer-name)
9565 (not (string-match "Untitled" (buffer-name))))
9566 (buffer-name)
9567 (url-view-url t))
9568 link (url-view-url t))
9569 (org-store-link-props :type "w3" :url (url-view-url t)))
9571 ((eq major-mode 'image-mode)
9572 (setq cpltxt (concat "file:"
9573 (abbreviate-file-name buffer-file-name))
9574 link cpltxt)
9575 (org-store-link-props :type "image" :file buffer-file-name))
9577 ;; In dired, store a link to the file of the current line
9578 ((eq major-mode 'dired-mode)
9579 (let ((file (dired-get-filename nil t)))
9580 (setq file (if file
9581 (abbreviate-file-name
9582 (expand-file-name (dired-get-filename nil t)))
9583 ;; otherwise, no file so use current directory.
9584 default-directory))
9585 (setq cpltxt (concat "file:" file)
9586 link cpltxt)))
9588 ((setq search (run-hook-with-args-until-success
9589 'org-create-file-search-functions))
9590 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9591 "::" search))
9592 (setq cpltxt (or description link)))
9594 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9595 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9596 (cond
9597 ;; Store a link using the target at point
9598 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9599 (setq cpltxt
9600 (concat "file:"
9601 (abbreviate-file-name
9602 (buffer-file-name (buffer-base-buffer)))
9603 "::" (match-string 1))
9604 link cpltxt))
9605 ((and (featurep 'org-id)
9606 (or (eq org-id-link-to-org-use-id t)
9607 (and (org-called-interactively-p 'any)
9608 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9609 (and (eq org-id-link-to-org-use-id
9610 'create-if-interactive-and-no-custom-id)
9611 (not custom-id))))
9612 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9613 ;; Store a link using the ID at point
9614 (setq link (condition-case nil
9615 (prog1 (org-id-store-link)
9616 (setq desc (plist-get org-store-link-plist
9617 :description)))
9618 (error
9619 ;; Probably before first headline, link only to file
9620 (concat "file:"
9621 (abbreviate-file-name
9622 (buffer-file-name (buffer-base-buffer))))))))
9624 ;; Just link to current headline
9625 (setq cpltxt (concat "file:"
9626 (abbreviate-file-name
9627 (buffer-file-name (buffer-base-buffer)))))
9628 ;; Add a context search string
9629 (when (org-xor org-context-in-file-links arg)
9630 (let* ((ee (org-element-at-point))
9631 (et (org-element-type ee))
9632 (ev (plist-get (cadr ee) :value))
9633 (ek (plist-get (cadr ee) :key))
9634 (eok (and (stringp ek) (string-match "name" ek))))
9635 (setq txt (cond
9636 ((org-at-heading-p) nil)
9637 ((and (eq et 'keyword) eok) ev)
9638 ((org-region-active-p)
9639 (buffer-substring (region-beginning) (region-end)))))
9640 (when (or (null txt) (string-match "\\S-" txt))
9641 (setq cpltxt
9642 (concat cpltxt "::"
9643 (condition-case nil
9644 (org-make-org-heading-search-string txt)
9645 (error "")))
9646 desc (or (and (eq et 'keyword) eok ev)
9647 (nth 4 (ignore-errors (org-heading-components)))
9648 "NONE")))))
9649 (if (string-match "::\\'" cpltxt)
9650 (setq cpltxt (substring cpltxt 0 -2)))
9651 (setq link cpltxt))))
9653 ((buffer-file-name (buffer-base-buffer))
9654 ;; Just link to this file here.
9655 (setq cpltxt (concat "file:"
9656 (abbreviate-file-name
9657 (buffer-file-name (buffer-base-buffer)))))
9658 ;; Add a context string.
9659 (when (org-xor org-context-in-file-links arg)
9660 (setq txt (if (org-region-active-p)
9661 (buffer-substring (region-beginning) (region-end))
9662 (buffer-substring (point-at-bol) (point-at-eol))))
9663 ;; Only use search option if there is some text.
9664 (when (string-match "\\S-" txt)
9665 (setq cpltxt
9666 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9667 desc "NONE")))
9668 (setq link cpltxt))
9670 ((org-called-interactively-p 'interactive)
9671 (user-error "No method for storing a link from this buffer"))
9673 (t (setq link nil)))
9675 ;; We're done setting link and desc, clean up
9676 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9677 (setq link (or link cpltxt)
9678 desc (or desc cpltxt))
9679 (cond ((equal desc "NONE") (setq desc nil))
9680 ((string-match org-bracket-link-analytic-regexp desc)
9681 (let ((d0 (match-string 3 desc))
9682 (p0 (match-string 5 desc)))
9683 (setq desc
9684 (replace-regexp-in-string
9685 org-bracket-link-regexp
9686 (concat (or p0 d0)
9687 (if (equal (length (match-string 0 desc))
9688 (length desc)) "*" "")) desc)))))
9690 ;; Return the link
9691 (if (not (and (or (org-called-interactively-p 'any)
9692 executing-kbd-macro) link))
9693 (or agenda-link (and link (org-make-link-string link desc)))
9694 (push (list link desc) org-stored-links)
9695 (message "Stored: %s" (or desc link))
9696 (when custom-id
9697 (setq link (concat "file:" (abbreviate-file-name
9698 (buffer-file-name)) "::#" custom-id))
9699 (push (list link desc) org-stored-links)))))))
9701 (defun org-store-link-props (&rest plist)
9702 "Store link properties, extract names and addresses."
9703 (let (x adr)
9704 (when (setq x (plist-get plist :from))
9705 (setq adr (mail-extract-address-components x))
9706 (setq plist (plist-put plist :fromname (car adr)))
9707 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9708 (when (setq x (plist-get plist :to))
9709 (setq adr (mail-extract-address-components x))
9710 (setq plist (plist-put plist :toname (car adr)))
9711 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9712 (let ((from (plist-get plist :from))
9713 (to (plist-get plist :to)))
9714 (when (and from to org-from-is-user-regexp)
9715 (setq plist
9716 (plist-put plist :fromto
9717 (if (string-match org-from-is-user-regexp from)
9718 (concat "to %t")
9719 (concat "from %f"))))))
9720 (setq org-store-link-plist plist))
9722 (defun org-add-link-props (&rest plist)
9723 "Add these properties to the link property list."
9724 (let (key value)
9725 (while plist
9726 (setq key (pop plist) value (pop plist))
9727 (setq org-store-link-plist
9728 (plist-put org-store-link-plist key value)))))
9730 (defun org-email-link-description (&optional fmt)
9731 "Return the description part of an email link.
9732 This takes information from `org-store-link-plist' and formats it
9733 according to FMT (default from `org-email-link-description-format')."
9734 (setq fmt (or fmt org-email-link-description-format))
9735 (let* ((p org-store-link-plist)
9736 (to (plist-get p :toaddress))
9737 (from (plist-get p :fromaddress))
9738 (table
9739 (list
9740 (cons "%c" (plist-get p :fromto))
9741 (cons "%F" (plist-get p :from))
9742 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9743 (cons "%T" (plist-get p :to))
9744 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9745 (cons "%s" (plist-get p :subject))
9746 (cons "%d" (plist-get p :date))
9747 (cons "%m" (plist-get p :message-id)))))
9748 (when (string-match "%c" fmt)
9749 ;; Check if the user wrote this message
9750 (if (and org-from-is-user-regexp from to
9751 (save-match-data (string-match org-from-is-user-regexp from)))
9752 (setq fmt (replace-match "to %t" t t fmt))
9753 (setq fmt (replace-match "from %f" t t fmt))))
9754 (org-replace-escapes fmt table)))
9756 (defun org-make-org-heading-search-string (&optional string)
9757 "Make search string for the current headline or STRING."
9758 (let ((s (or string
9759 (and (derived-mode-p 'org-mode)
9760 (save-excursion
9761 (org-back-to-heading t)
9762 (org-element-property :raw-value (org-element-at-point))))))
9763 (lines org-context-in-file-links))
9764 (or string (setq s (concat "*" s))) ; Add * for headlines
9765 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9766 (when (and string (integerp lines) (> lines 0))
9767 (let ((slines (org-split-string s "\n")))
9768 (when (< lines (length slines))
9769 (setq s (mapconcat
9770 'identity
9771 (reverse (nthcdr (- (length slines) lines)
9772 (reverse slines))) "\n")))))
9773 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9775 (defun org-make-link-string (link &optional description)
9776 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9777 (unless (string-match "\\S-" link)
9778 (error "Empty link"))
9779 (when (and description
9780 (stringp description)
9781 (not (string-match "\\S-" description)))
9782 (setq description nil))
9783 (when (stringp description)
9784 ;; Remove brackets from the description, they are fatal.
9785 (while (string-match "\\[" description)
9786 (setq description (replace-match "{" t t description)))
9787 (while (string-match "\\]" description)
9788 (setq description (replace-match "}" t t description))))
9789 (when (equal link description)
9790 ;; No description needed, it is identical
9791 (setq description nil))
9792 (when (and (not description)
9793 (not (string-match (org-image-file-name-regexp) link))
9794 (not (equal link (org-link-escape link))))
9795 (setq description (org-extract-attributes link)))
9796 (setq link
9797 (cond ((string-match (org-image-file-name-regexp) link) link)
9798 ((string-match org-link-types-re link)
9799 (concat (match-string 1 link)
9800 (org-link-escape (substring link (match-end 1)))))
9801 (t (org-link-escape link))))
9802 (concat "[[" link "]"
9803 (if description (concat "[" description "]") "")
9804 "]"))
9806 (defconst org-link-escape-chars
9807 ;;%20 %2B %3B %3D %5B %5D
9808 '(?\ ?\+ ?\; ?\= ?\[ ?\])
9809 "List of characters that should be escaped in link.
9810 This is the list that is used for internal purposes.")
9812 (defconst org-link-escape-chars-browser
9813 ;;%20 %22
9814 '(?\ ?\")
9815 "List of escapes for characters that are problematic in links.
9816 This is the list that is used before handing over to the browser.")
9818 (defun org-link-escape (text &optional table merge)
9819 "Return percent escaped representation of TEXT.
9820 TEXT is a string with the text to escape.
9821 Optional argument TABLE is a list with characters that should be
9822 escaped. When nil, `org-link-escape-chars' is used.
9823 If optional argument MERGE is set, merge TABLE into
9824 `org-link-escape-chars'."
9825 (cond
9826 ((and table merge)
9827 (mapc (lambda (defchr)
9828 (unless (member defchr table)
9829 (setq table (cons defchr table)))) org-link-escape-chars))
9830 ((null table)
9831 (setq table org-link-escape-chars)))
9832 (mapconcat
9833 (lambda (char)
9834 (if (or (member char table)
9835 (and (or (< char 32) (= char ?\%) (> char 126))
9836 org-url-hexify-p))
9837 (mapconcat (lambda (sequence-element)
9838 (format "%%%.2X" sequence-element))
9839 (or (encode-coding-char char 'utf-8)
9840 (error "Unable to percent escape character: %s"
9841 (char-to-string char))) "")
9842 (char-to-string char))) text ""))
9844 (defun org-link-escape-browser (text)
9845 (if (org-string-match-p
9846 (concat "[[:nonascii:]" org-link-escape-chars-browser "]")
9847 text)
9848 (org-link-escape text org-link-escape-chars-browser)
9849 text))
9851 (defun org-link-unescape (str)
9852 "Unhex hexified Unicode strings as returned from the JavaScript function
9853 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9854 (unless (and (null str) (string= "" str))
9855 (let ((pos 0) (case-fold-search t) unhexed)
9856 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9857 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9858 (setq str (replace-match unhexed t t str))
9859 (setq pos (+ pos (length unhexed))))))
9860 str)
9862 (defun org-link-unescape-compound (hex)
9863 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9864 Note: this function also decodes single byte encodings like
9865 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9866 (save-match-data
9867 (let* ((bytes (cdr (split-string hex "%")))
9868 (ret "")
9869 (eat 0)
9870 (sum 0))
9871 (while bytes
9872 (let* ((val (string-to-number (pop bytes) 16))
9873 (shift-xor
9874 (if (= 0 eat)
9875 (cond
9876 ((>= val 252) (cons 6 252))
9877 ((>= val 248) (cons 5 248))
9878 ((>= val 240) (cons 4 240))
9879 ((>= val 224) (cons 3 224))
9880 ((>= val 192) (cons 2 192))
9881 (t (cons 0 0)))
9882 (cons 6 128))))
9883 (if (>= val 192) (setq eat (car shift-xor)))
9884 (setq val (logxor val (cdr shift-xor)))
9885 (setq sum (+ (lsh sum (car shift-xor)) val))
9886 (if (> eat 0) (setq eat (- eat 1)))
9887 (cond
9888 ((= 0 eat) ;multi byte
9889 (setq ret (concat ret (org-char-to-string sum)))
9890 (setq sum 0))
9891 ((not bytes) ; single byte(s)
9892 (setq ret (org-link-unescape-single-byte-sequence hex))))
9893 )) ;; end (while bytes
9894 ret )))
9896 (defun org-link-unescape-single-byte-sequence (hex)
9897 "Unhexify hex-encoded single byte character sequences."
9898 (mapconcat (lambda (byte)
9899 (char-to-string (string-to-number byte 16)))
9900 (cdr (split-string hex "%")) ""))
9902 (defun org-xor (a b)
9903 "Exclusive or."
9904 (if a (not b) b))
9906 (defun org-fixup-message-id-for-http (s)
9907 "Replace special characters in a message id, so it can be used in an http query."
9908 (when (string-match "%" s)
9909 (setq s (mapconcat (lambda (c)
9910 (if (eq c ?%)
9911 "%25"
9912 (char-to-string c)))
9913 s "")))
9914 (while (string-match "<" s)
9915 (setq s (replace-match "%3C" t t s)))
9916 (while (string-match ">" s)
9917 (setq s (replace-match "%3E" t t s)))
9918 (while (string-match "@" s)
9919 (setq s (replace-match "%40" t t s)))
9922 (defun org-link-prettify (link)
9923 "Return a human-readable representation of LINK.
9924 The car of LINK must be a raw link the cdr of LINK must be either
9925 a link description or nil."
9926 (let ((desc (or (cadr link) "<no description>")))
9927 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9928 "<" (car link) ">")))
9930 ;;;###autoload
9931 (defun org-insert-link-global ()
9932 "Insert a link like Org-mode does.
9933 This command can be called in any mode to insert a link in Org-mode syntax."
9934 (interactive)
9935 (org-load-modules-maybe)
9936 (org-run-like-in-org-mode 'org-insert-link))
9938 (defun org-insert-all-links (&optional keep)
9939 "Insert all links in `org-stored-links'."
9940 (interactive "P")
9941 (let ((links (copy-sequence org-stored-links)) l)
9942 (while (setq l (if keep (pop links) (pop org-stored-links)))
9943 (insert "- ")
9944 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9945 (insert "\n"))))
9947 (defun org-link-fontify-links-to-this-file ()
9948 "Fontify links to the current file in `org-stored-links'."
9949 (let ((f (buffer-file-name)) a b)
9950 (setq a (mapcar (lambda(l)
9951 (let ((ll (car l)))
9952 (when (and (string-match "^file:\\(.+\\)::" ll)
9953 (equal f (expand-file-name (match-string 1 ll))))
9954 ll)))
9955 org-stored-links))
9956 (when (featurep 'org-id)
9957 (setq b (mapcar (lambda(l)
9958 (let ((ll (car l)))
9959 (when (and (string-match "^id:\\(.+\\)$" ll)
9960 (equal f (expand-file-name
9961 (or (org-id-find-id-file
9962 (match-string 1 ll)) ""))))
9963 ll)))
9964 org-stored-links)))
9965 (mapcar (lambda(l)
9966 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9967 (delq nil (append a b)))))
9969 (defvar org-link-links-in-this-file nil)
9970 (defun org-insert-link (&optional complete-file link-location default-description)
9971 "Insert a link. At the prompt, enter the link.
9973 Completion can be used to insert any of the link protocol prefixes like
9974 http or ftp in use.
9976 The history can be used to select a link previously stored with
9977 `org-store-link'. When the empty string is entered (i.e. if you just
9978 press RET at the prompt), the link defaults to the most recently
9979 stored link. As SPC triggers completion in the minibuffer, you need to
9980 use M-SPC or C-q SPC to force the insertion of a space character.
9982 You will also be prompted for a description, and if one is given, it will
9983 be displayed in the buffer instead of the link.
9985 If there is already a link at point, this command will allow you to edit link
9986 and description parts.
9988 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9989 be selected using completion. The path to the file will be relative to the
9990 current directory if the file is in the current directory or a subdirectory.
9991 Otherwise, the link will be the absolute path as completed in the minibuffer
9992 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9993 option `org-link-file-path-type'.
9995 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9996 the current directory or below.
9998 With three \\[universal-argument] prefixes, negate the meaning of
9999 `org-keep-stored-link-after-insertion'.
10001 If `org-make-link-description-function' is non-nil, this function will be
10002 called with the link target, and the result will be the default
10003 link description.
10005 If the LINK-LOCATION parameter is non-nil, this value will be
10006 used as the link location instead of reading one interactively.
10008 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10009 be used as the default description."
10010 (interactive "P")
10011 (let* ((wcf (current-window-configuration))
10012 (origbuf (current-buffer))
10013 (region (if (org-region-active-p)
10014 (buffer-substring (region-beginning) (region-end))))
10015 (remove (and region (list (region-beginning) (region-end))))
10016 (desc region)
10017 tmphist ; byte-compile incorrectly complains about this
10018 (link link-location)
10019 (abbrevs org-link-abbrev-alist-local)
10020 entry file all-prefixes auto-desc)
10021 (cond
10022 (link-location) ; specified by arg, just use it.
10023 ((org-in-regexp org-bracket-link-regexp 1)
10024 ;; We do have a link at point, and we are going to edit it.
10025 (setq remove (list (match-beginning 0) (match-end 0)))
10026 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
10027 (setq link (read-string "Link: "
10028 (org-link-unescape
10029 (org-match-string-no-properties 1)))))
10030 ((or (org-in-regexp org-angle-link-re)
10031 (org-in-regexp org-plain-link-re))
10032 ;; Convert to bracket link
10033 (setq remove (list (match-beginning 0) (match-end 0))
10034 link (read-string "Link: "
10035 (org-remove-angle-brackets (match-string 0)))))
10036 ((member complete-file '((4) (16)))
10037 ;; Completing read for file names.
10038 (setq link (org-file-complete-link complete-file)))
10040 ;; Read link, with completion for stored links.
10041 (org-link-fontify-links-to-this-file)
10042 (org-switch-to-buffer-other-window "*Org Links*")
10043 (with-current-buffer "*Org Links*"
10044 (erase-buffer)
10045 (insert "Insert a link.
10046 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10047 (when org-stored-links
10048 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10049 (insert (mapconcat 'org-link-prettify
10050 (reverse org-stored-links) "\n")))
10051 (goto-char (point-min)))
10052 (let ((cw (selected-window)))
10053 (select-window (get-buffer-window "*Org Links*" 'visible))
10054 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10055 (unless (pos-visible-in-window-p (point-max))
10056 (org-fit-window-to-buffer))
10057 (and (window-live-p cw) (select-window cw)))
10058 ;; Fake a link history, containing the stored links.
10059 (setq tmphist (append (mapcar 'car org-stored-links)
10060 org-insert-link-history))
10061 (setq all-prefixes (append (mapcar 'car abbrevs)
10062 (mapcar 'car org-link-abbrev-alist)
10063 org-link-types))
10064 (unwind-protect
10065 (progn
10066 (setq link
10067 (org-completing-read
10068 "Link: "
10069 (append
10070 (mapcar (lambda (x) (concat x ":"))
10071 all-prefixes)
10072 (mapcar 'car org-stored-links))
10073 nil nil nil
10074 'tmphist
10075 (caar org-stored-links)))
10076 (if (not (string-match "\\S-" link))
10077 (user-error "No link selected"))
10078 (mapc (lambda(l)
10079 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
10080 org-stored-links)
10081 (if (or (member link all-prefixes)
10082 (and (equal ":" (substring link -1))
10083 (member (substring link 0 -1) all-prefixes)
10084 (setq link (substring link 0 -1))))
10085 (setq link (with-current-buffer origbuf
10086 (org-link-try-special-completion link)))))
10087 (set-window-configuration wcf)
10088 (kill-buffer "*Org Links*"))
10089 (setq entry (assoc link org-stored-links))
10090 (or entry (push link org-insert-link-history))
10091 (setq desc (or desc (nth 1 entry)))))
10093 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10094 (not org-keep-stored-link-after-insertion))
10095 (setq org-stored-links (delq (assoc link org-stored-links)
10096 org-stored-links)))
10098 (if (and (string-match org-plain-link-re link)
10099 (not (string-match org-ts-regexp link)))
10100 ;; URL-like link, normalize the use of angular brackets.
10101 (setq link (org-remove-angle-brackets link)))
10103 ;; Check if we are linking to the current file with a search
10104 ;; option If yes, simplify the link by using only the search
10105 ;; option.
10106 (when (and buffer-file-name
10107 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10108 (let* ((path (match-string 1 link))
10109 (case-fold-search nil)
10110 (search (match-string 2 link)))
10111 (save-match-data
10112 (if (equal (file-truename buffer-file-name) (file-truename path))
10113 ;; We are linking to this same file, with a search option
10114 (setq link search)))))
10116 ;; Check if we can/should use a relative path. If yes, simplify the link
10117 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10118 (let* ((type (match-string 1 link))
10119 (path (match-string 2 link))
10120 (origpath path)
10121 (case-fold-search nil))
10122 (cond
10123 ((or (eq org-link-file-path-type 'absolute)
10124 (equal complete-file '(16)))
10125 (setq path (abbreviate-file-name (expand-file-name path))))
10126 ((eq org-link-file-path-type 'noabbrev)
10127 (setq path (expand-file-name path)))
10128 ((eq org-link-file-path-type 'relative)
10129 (setq path (file-relative-name path)))
10131 (save-match-data
10132 (if (string-match (concat "^" (regexp-quote
10133 (expand-file-name
10134 (file-name-as-directory
10135 default-directory))))
10136 (expand-file-name path))
10137 ;; We are linking a file with relative path name.
10138 (setq path (substring (expand-file-name path)
10139 (match-end 0)))
10140 (setq path (abbreviate-file-name (expand-file-name path)))))))
10141 (setq link (concat type path))
10142 (if (equal desc origpath)
10143 (setq desc path))))
10145 (if org-make-link-description-function
10146 (setq desc
10147 (or (condition-case nil
10148 (funcall org-make-link-description-function link desc)
10149 (error (progn (message "Can't get link description from `%s'"
10150 (symbol-name org-make-link-description-function))
10151 (sit-for 2) nil)))
10152 (read-string "Description: " default-description)))
10153 (if default-description (setq desc default-description)
10154 (setq desc (or (and auto-desc desc)
10155 (read-string "Description: " desc)))))
10157 (unless (string-match "\\S-" desc) (setq desc nil))
10158 (if remove (apply 'delete-region remove))
10159 (insert (org-make-link-string link desc))))
10161 (defun org-link-try-special-completion (type)
10162 "If there is completion support for link type TYPE, offer it."
10163 (let ((fun (intern (concat "org-" type "-complete-link"))))
10164 (if (functionp fun)
10165 (funcall fun)
10166 (read-string "Link (no completion support): " (concat type ":")))))
10168 (defun org-file-complete-link (&optional arg)
10169 "Create a file link using completion."
10170 (let (file link)
10171 (setq file (org-iread-file-name "File: "))
10172 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10173 (pwd1 (file-name-as-directory (abbreviate-file-name
10174 (expand-file-name ".")))))
10175 (cond
10176 ((equal arg '(16))
10177 (setq link (concat
10178 "file:"
10179 (abbreviate-file-name (expand-file-name file)))))
10180 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10181 (setq link (concat "file:" (match-string 1 file))))
10182 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10183 (expand-file-name file))
10184 (setq link (concat
10185 "file:" (match-string 1 (expand-file-name file)))))
10186 (t (setq link (concat "file:" file)))))
10187 link))
10189 (defun org-iread-file-name (&rest args)
10190 "Read-file-name using `ido-mode' speedup if available.
10191 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10192 See `read-file-name' for a description of parameters."
10193 (org-without-partial-completion
10194 (if (and org-completion-use-ido
10195 (fboundp 'ido-read-file-name)
10196 (boundp 'ido-mode) ido-mode
10197 (listp (second args)))
10198 (let ((ido-enter-matching-directory nil))
10199 (apply 'ido-read-file-name args))
10200 (apply 'read-file-name args))))
10202 (defun org-completing-read (&rest args)
10203 "Completing-read with SPACE being a normal character."
10204 (let ((enable-recursive-minibuffers t)
10205 (minibuffer-local-completion-map
10206 (copy-keymap minibuffer-local-completion-map)))
10207 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10208 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10209 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10210 (apply 'org-icompleting-read args)))
10212 (defun org-completing-read-no-i (&rest args)
10213 (let (org-completion-use-ido org-completion-use-iswitchb)
10214 (apply 'org-completing-read args)))
10216 (defun org-iswitchb-completing-read (prompt choices &rest args)
10217 "Use iswitch as a completing-read replacement to choose from choices.
10218 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10219 from."
10220 (let* ((iswitchb-use-virtual-buffers nil)
10221 (iswitchb-make-buflist-hook
10222 (lambda ()
10223 (setq iswitchb-temp-buflist choices))))
10224 (iswitchb-read-buffer prompt)))
10226 (defun org-icompleting-read (&rest args)
10227 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10228 (org-without-partial-completion
10229 (if (and org-completion-use-ido
10230 (fboundp 'ido-completing-read)
10231 (boundp 'ido-mode) ido-mode
10232 (listp (second args)))
10233 (let ((ido-enter-matching-directory nil))
10234 (apply 'ido-completing-read (concat (car args))
10235 (if (consp (car (nth 1 args)))
10236 (mapcar 'car (nth 1 args))
10237 (nth 1 args))
10238 (cddr args)))
10239 (if (and org-completion-use-iswitchb
10240 (boundp 'iswitchb-mode) iswitchb-mode
10241 (listp (second args)))
10242 (apply 'org-iswitchb-completing-read (concat (car args))
10243 (if (consp (car (nth 1 args)))
10244 (mapcar 'car (nth 1 args))
10245 (nth 1 args))
10246 (cddr args))
10247 (apply 'completing-read args)))))
10249 (defun org-extract-attributes (s)
10250 "Extract the attributes cookie from a string and set as text property."
10251 (let (a attr (start 0) key value)
10252 (save-match-data
10253 (when (string-match "{{\\([^}]+\\)}}$" s)
10254 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10255 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10256 (setq key (match-string 1 a) value (match-string 2 a)
10257 start (match-end 0)
10258 attr (plist-put attr (intern key) value))))
10259 (org-add-props s nil 'org-attr attr))
10262 ;;; Opening/following a link
10264 (defvar org-link-search-failed nil)
10266 (defvar org-open-link-functions nil
10267 "Hook for functions finding a plain text link.
10268 These functions must take a single argument, the link content.
10269 They will be called for links that look like [[link text][description]]
10270 when LINK TEXT does not have a protocol like \"http:\" and does not look
10271 like a filename (e.g. \"./blue.png\").
10273 These functions will be called *before* Org attempts to resolve the
10274 link by doing text searches in the current buffer - so if you want a
10275 link \"[[target]]\" to still find \"<<target>>\", your function should
10276 handle this as a special case.
10278 When the function does handle the link, it must return a non-nil value.
10279 If it decides that it is not responsible for this link, it must return
10280 nil to indicate that that Org-mode can continue with other options
10281 like exact and fuzzy text search.")
10283 (defun org-next-link (&optional search-backward)
10284 "Move forward to the next link.
10285 If the link is in hidden text, expose it."
10286 (interactive "P")
10287 (when (and org-link-search-failed (eq this-command last-command))
10288 (goto-char (point-min))
10289 (message "Link search wrapped back to beginning of buffer"))
10290 (setq org-link-search-failed nil)
10291 (let* ((pos (point))
10292 (ct (org-context))
10293 (a (assoc :link ct))
10294 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10295 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10296 ((looking-at org-any-link-re)
10297 ;; Don't stay stuck at link without an org-link face
10298 (forward-char (if search-backward -1 1))))
10299 (if (funcall srch-fun org-any-link-re nil t)
10300 (progn
10301 (goto-char (match-beginning 0))
10302 (if (outline-invisible-p) (org-show-context)))
10303 (goto-char pos)
10304 (setq org-link-search-failed t)
10305 (message "No further link found"))))
10307 (defun org-previous-link ()
10308 "Move backward to the previous link.
10309 If the link is in hidden text, expose it."
10310 (interactive)
10311 (funcall 'org-next-link t))
10313 (defun org-translate-link (s)
10314 "Translate a link string if a translation function has been defined."
10315 (if (and org-link-translation-function
10316 (fboundp org-link-translation-function)
10317 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10318 (progn
10319 (setq s (funcall org-link-translation-function
10320 (match-string 1 s) (match-string 2 s)))
10321 (concat (car s) ":" (cdr s)))
10324 (defun org-translate-link-from-planner (type path)
10325 "Translate a link from Emacs Planner syntax so that Org can follow it.
10326 This is still an experimental function, your mileage may vary."
10327 (cond
10328 ((member type '("http" "https" "news" "ftp"))
10329 ;; standard Internet links are the same.
10330 nil)
10331 ((and (equal type "irc") (string-match "^//" path))
10332 ;; Planner has two / at the beginning of an irc link, we have 1.
10333 ;; We should have zero, actually....
10334 (setq path (substring path 1)))
10335 ((and (equal type "lisp") (string-match "^/" path))
10336 ;; Planner has a slash, we do not.
10337 (setq type "elisp" path (substring path 1)))
10338 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10339 ;; A typical message link. Planner has the id after the final slash,
10340 ;; we separate it with a hash mark
10341 (setq path (concat (match-string 1 path) "#"
10342 (org-remove-angle-brackets (match-string 2 path))))))
10343 (cons type path))
10345 (defun org-find-file-at-mouse (ev)
10346 "Open file link or URL at mouse."
10347 (interactive "e")
10348 (mouse-set-point ev)
10349 (org-open-at-point 'in-emacs))
10351 (defun org-open-at-mouse (ev)
10352 "Open file link or URL at mouse.
10353 See the docstring of `org-open-file' for details."
10354 (interactive "e")
10355 (mouse-set-point ev)
10356 (if (eq major-mode 'org-agenda-mode)
10357 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10358 (org-open-at-point))
10360 (defvar org-window-config-before-follow-link nil
10361 "The window configuration before following a link.
10362 This is saved in case the need arises to restore it.")
10364 (defvar org-open-link-marker (make-marker)
10365 "Marker pointing to the location where `org-open-at-point; was called.")
10367 ;;;###autoload
10368 (defun org-open-at-point-global ()
10369 "Follow a link like Org-mode does.
10370 This command can be called in any mode to follow a link that has
10371 Org-mode syntax."
10372 (interactive)
10373 (org-run-like-in-org-mode 'org-open-at-point))
10375 ;;;###autoload
10376 (defun org-open-link-from-string (s &optional arg reference-buffer)
10377 "Open a link in the string S, as if it was in Org-mode."
10378 (interactive "sLink: \nP")
10379 (let ((reference-buffer (or reference-buffer (current-buffer))))
10380 (with-temp-buffer
10381 (let ((org-inhibit-startup (not reference-buffer)))
10382 (org-mode)
10383 (insert s)
10384 (goto-char (point-min))
10385 (when reference-buffer
10386 (setq org-link-abbrev-alist-local
10387 (with-current-buffer reference-buffer
10388 org-link-abbrev-alist-local)))
10389 (org-open-at-point arg reference-buffer)))))
10391 (defvar org-open-at-point-functions nil
10392 "Hook that is run when following a link at point.
10394 Functions in this hook must return t if they identify and follow
10395 a link at point. If they don't find anything interesting at point,
10396 they must return nil.")
10398 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10399 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10400 (defun org-open-at-point (&optional arg reference-buffer)
10401 "Open link at or after point.
10402 If there is no link at point, this function will search forward up to
10403 the end of the current line.
10404 Normally, files will be opened by an appropriate application. If the
10405 optional prefix argument ARG is non-nil, Emacs will visit the file.
10406 With a double prefix argument, try to open outside of Emacs, in the
10407 application the system uses for this file type."
10408 (interactive "P")
10409 ;; if in a code block, then open the block's results
10410 (unless (call-interactively #'org-babel-open-src-block-result)
10411 (org-load-modules-maybe)
10412 (move-marker org-open-link-marker (point))
10413 (setq org-window-config-before-follow-link (current-window-configuration))
10414 (org-remove-occur-highlights nil nil t)
10415 (cond
10416 ((and (org-at-heading-p)
10417 (not (org-at-timestamp-p t))
10418 (not (org-in-regexp
10419 (concat org-plain-link-re "\\|"
10420 org-bracket-link-regexp "\\|"
10421 org-angle-link-re "\\|"
10422 "[ \t]:[^ \t\n]+:[ \t]*$")))
10423 (not (get-text-property (point) 'org-linked-text)))
10424 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10425 (lk0 (car lkall))
10426 (lk (if (stringp lk0) (list lk0) lk0))
10427 (lkend (cdr lkall)))
10428 (mapcar (lambda(l)
10429 (search-forward l nil lkend)
10430 (goto-char (match-beginning 0))
10431 (org-open-at-point))
10432 lk))
10433 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10434 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10435 ((and (org-at-timestamp-p t)
10436 (not (org-in-regexp org-bracket-link-regexp)))
10437 (org-follow-timestamp-link))
10438 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10439 (not (org-in-regexp org-any-link-re)))
10440 (org-footnote-action))
10442 (let (type path link line search (pos (point)))
10443 (catch 'match
10444 (save-excursion
10445 (skip-chars-forward "^]\n\r")
10446 (when (org-in-regexp org-bracket-link-regexp 1)
10447 (setq link (org-extract-attributes
10448 (org-link-unescape (org-match-string-no-properties 1))))
10449 (while (string-match " *\n *" link)
10450 (setq link (replace-match " " t t link)))
10451 (setq link (org-link-expand-abbrev link))
10452 (cond
10453 ((or (file-name-absolute-p link)
10454 (string-match "^\\.\\.?/" link))
10455 (setq type "file" path link))
10456 ((string-match org-link-re-with-space3 link)
10457 (setq type (match-string 1 link) path (match-string 2 link)))
10458 ((string-match "^help:+\\(.+\\)" link)
10459 (setq type "help" path (match-string 1 link)))
10460 (t (setq type "thisfile" path link)))
10461 (throw 'match t)))
10463 (when (get-text-property (point) 'org-linked-text)
10464 (setq type "thisfile"
10465 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10466 (1+ (point)) (point))
10467 path (buffer-substring
10468 (or (previous-single-property-change pos 'org-linked-text)
10469 (point-min))
10470 (or (next-single-property-change pos 'org-linked-text)
10471 (point-max)))
10472 ;; Ensure we will search for a <<<radio>>> link, not
10473 ;; a simple reference like <<ref>>
10474 path (concat "<" path))
10475 (throw 'match t))
10477 (save-excursion
10478 (when (or (org-in-regexp org-angle-link-re)
10479 (let ((match (org-in-regexp org-plain-link-re)))
10480 ;; Check a plain link is not within a bracket link
10481 (and match
10482 (save-excursion
10483 (progn
10484 (goto-char (car match))
10485 (not (org-in-regexp org-bracket-link-regexp))))))
10486 (let ((line_ending (save-excursion (end-of-line) (point))))
10487 ;; We are in a line before a plain or bracket link
10488 (or (re-search-forward org-plain-link-re line_ending t)
10489 (re-search-forward org-bracket-link-regexp line_ending t))))
10490 (setq type (match-string 1)
10491 path (org-link-unescape (match-string 2)))
10492 (throw 'match t)))
10493 (save-excursion
10494 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10495 (setq type "tags"
10496 path (match-string 1))
10497 (while (string-match ":" path)
10498 (setq path (replace-match "+" t t path)))
10499 (throw 'match t)))
10500 (when (org-in-regexp "<\\([^><\n]+\\)>")
10501 (setq type "tree-match"
10502 path (match-string 1))
10503 (throw 'match t)))
10504 (unless path
10505 (user-error "No link found"))
10507 ;; switch back to reference buffer
10508 ;; needed when if called in a temporary buffer through
10509 ;; org-open-link-from-string
10510 (with-current-buffer (or reference-buffer (current-buffer))
10512 ;; Remove any trailing spaces in path
10513 (if (string-match " +\\'" path)
10514 (setq path (replace-match "" t t path)))
10515 (if (and org-link-translation-function
10516 (fboundp org-link-translation-function))
10517 ;; Check if we need to translate the link
10518 (let ((tmp (funcall org-link-translation-function type path)))
10519 (setq type (car tmp) path (cdr tmp))))
10521 (cond
10523 ((assoc type org-link-protocols)
10524 (funcall (nth 1 (assoc type org-link-protocols)) path))
10526 ((equal type "help")
10527 (let ((f-or-v (intern path)))
10528 (cond ((fboundp f-or-v)
10529 (describe-function f-or-v))
10530 ((boundp f-or-v)
10531 (describe-variable f-or-v))
10532 (t (error "Not a known function or variable")))))
10534 ((equal type "mailto")
10535 (let ((cmd (car org-link-mailto-program))
10536 (args (cdr org-link-mailto-program)) args1
10537 (address path) (subject "") a)
10538 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10539 (setq address (match-string 1 path)
10540 subject (org-link-escape (match-string 2 path))))
10541 (while args
10542 (cond
10543 ((not (stringp (car args))) (push (pop args) args1))
10544 (t (setq a (pop args))
10545 (if (string-match "%a" a)
10546 (setq a (replace-match address t t a)))
10547 (if (string-match "%s" a)
10548 (setq a (replace-match subject t t a)))
10549 (push a args1))))
10550 (apply cmd (nreverse args1))))
10552 ((member type '("http" "https" "ftp" "news"))
10553 ;; In the example of the http Org link
10554 ;; [[http://lists.gnu.org/archive/cgi-bin/namazu.cgi?idxname=emacs-orgmode&query=%252Bsubject:"Release+8.2"]]
10555 ;; to open a browser with +subject:"Release 8.2" in the
10556 ;; query field the variable `path' contains
10557 ;; [...]=%2Bsubject:"Release+8.2", `url-encode-url'
10558 ;; converts correct to [...]=%2Bsubject:%22Release+8.2%22
10559 ;; and `org-link-escape-browser' converts wrong to
10560 ;; [...]=%252Bsubject:%22Release+8.2%22.
10562 ;; `url-encode-url' is available since Emacs 24.3.1 and
10563 ;; `org-link-escape-browser' can be removed altogether
10564 ;; once Org drops support for Emacs 24.1 and 24.2.
10565 (browse-url (funcall (if (fboundp 'url-encode-url)
10566 #'url-encode-url
10567 #'org-link-escape-browser)
10568 (concat type ":" path))))
10570 ((string= type "doi")
10571 ;; See comments for type http above
10572 (browse-url (funcall (if (fboundp 'url-encode-url)
10573 #'url-encode-url
10574 #'org-link-escape-browser)
10575 (concat org-doi-server-url path))))
10577 ((member type '("message"))
10578 (browse-url (concat type ":" path)))
10580 ((string= type "tags")
10581 (org-tags-view arg path))
10583 ((string= type "tree-match")
10584 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10586 ((string= type "file")
10587 (if (string-match "::\\([0-9]+\\)\\'" path)
10588 (setq line (string-to-number (match-string 1 path))
10589 path (substring path 0 (match-beginning 0)))
10590 (if (string-match "::\\(.+\\)\\'" path)
10591 (setq search (match-string 1 path)
10592 path (substring path 0 (match-beginning 0)))))
10593 (if (string-match "[*?{]" (file-name-nondirectory path))
10594 (dired path)
10595 (org-open-file path arg line search)))
10597 ((string= type "shell")
10598 (let ((buf (generate-new-buffer "*Org Shell Output"))
10599 (cmd path))
10600 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10601 (string-match org-confirm-shell-link-not-regexp cmd))
10602 (not org-confirm-shell-link-function)
10603 (funcall org-confirm-shell-link-function
10604 (format "Execute \"%s\" in shell? "
10605 (org-add-props cmd nil
10606 'face 'org-warning))))
10607 (progn
10608 (message "Executing %s" cmd)
10609 (shell-command cmd buf)
10610 (if (featurep 'midnight)
10611 (setq clean-buffer-list-kill-buffer-names
10612 (cons buf clean-buffer-list-kill-buffer-names))))
10613 (error "Abort"))))
10615 ((string= type "elisp")
10616 (let ((cmd path))
10617 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10618 (string-match org-confirm-elisp-link-not-regexp cmd))
10619 (not org-confirm-elisp-link-function)
10620 (funcall org-confirm-elisp-link-function
10621 (format "Execute \"%s\" as elisp? "
10622 (org-add-props cmd nil
10623 'face 'org-warning))))
10624 (message "%s => %s" cmd
10625 (if (equal (string-to-char cmd) ?\()
10626 (eval (read cmd))
10627 (call-interactively (read cmd))))
10628 (error "Abort"))))
10630 ((and (string= type "thisfile")
10631 (or (run-hook-with-args-until-success
10632 'org-open-link-functions path)
10633 (and link
10634 (string-match "^id:" link)
10635 (or (featurep 'org-id) (require 'org-id))
10636 (progn
10637 (funcall (nth 1 (assoc "id" org-link-protocols))
10638 (substring path 3))
10639 t)))))
10641 ((string= type "thisfile")
10642 (if arg
10643 (switch-to-buffer-other-window
10644 (org-get-buffer-for-internal-link (current-buffer)))
10645 (org-mark-ring-push))
10646 (let ((cmd `(org-link-search
10647 ,path
10648 ,(cond ((equal arg '(4)) ''occur)
10649 ((equal arg '(16)) ''org-occur))
10650 ,pos)))
10651 (condition-case nil (let ((org-link-search-inhibit-query t))
10652 (eval cmd))
10653 (error (progn (widen) (eval cmd))))))
10655 (t (browse-url-at-point)))))))
10656 (move-marker org-open-link-marker nil)
10657 (run-hook-with-args 'org-follow-link-hook)))
10659 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10660 "Offer links in the current entry and return the selected link.
10661 If there is only one link, return it.
10662 If NTH is an integer, return the NTH link found.
10663 If ZERO is a string, check also this string for a link, and if
10664 there is one, return it."
10665 (with-current-buffer buffer
10666 (save-excursion
10667 (save-restriction
10668 (widen)
10669 (goto-char marker)
10670 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10671 "\\(" org-angle-link-re "\\)\\|"
10672 "\\(" org-plain-link-re "\\)"))
10673 (cnt ?0)
10674 (in-emacs (if (integerp nth) nil nth))
10675 have-zero end links link c)
10676 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10677 (push (match-string 0 zero) links)
10678 (setq cnt (1- cnt) have-zero t))
10679 (save-excursion
10680 (org-back-to-heading t)
10681 (setq end (save-excursion (outline-next-heading) (point)))
10682 (while (re-search-forward re end t)
10683 (push (match-string 0) links))
10684 (setq links (org-uniquify (reverse links))))
10685 (cond
10686 ((null links)
10687 (message "No links"))
10688 ((equal (length links) 1)
10689 (setq link (car links)))
10690 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10691 (setq link (nth (if have-zero nth (1- nth)) links)))
10692 (t ; we have to select a link
10693 (save-excursion
10694 (save-window-excursion
10695 (delete-other-windows)
10696 (with-output-to-temp-buffer "*Select Link*"
10697 (mapc (lambda (l)
10698 (if (not (string-match org-bracket-link-regexp l))
10699 (princ (format "[%c] %s\n" (incf cnt)
10700 (org-remove-angle-brackets l)))
10701 (if (match-end 3)
10702 (princ (format "[%c] %s (%s)\n" (incf cnt)
10703 (match-string 3 l) (match-string 1 l)))
10704 (princ (format "[%c] %s\n" (incf cnt)
10705 (match-string 1 l))))))
10706 links))
10707 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10708 (message "Select link to open, RET to open all:")
10709 (setq c (read-char-exclusive))
10710 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10711 (when (equal c ?q) (error "Abort"))
10712 (if (equal c ?\C-m)
10713 (setq link links)
10714 (setq nth (- c ?0))
10715 (if have-zero (setq nth (1+ nth)))
10716 (unless (and (integerp nth) (>= (length links) nth))
10717 (user-error "Invalid link selection"))
10718 (setq link (nth (1- nth) links)))))
10719 (cons link end))))))
10721 ;; Add special file links that specify the way of opening
10723 (org-add-link-type "file+sys" 'org-open-file-with-system)
10724 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10725 (defun org-open-file-with-system (path)
10726 "Open file at PATH using the system way of opening it."
10727 (org-open-file path 'system))
10728 (defun org-open-file-with-emacs (path)
10729 "Open file at PATH in Emacs."
10730 (org-open-file path 'emacs))
10733 ;;; File search
10735 (defvar org-create-file-search-functions nil
10736 "List of functions to construct the right search string for a file link.
10737 These functions are called in turn with point at the location to
10738 which the link should point.
10740 A function in the hook should first test if it would like to
10741 handle this file type, for example by checking the `major-mode'
10742 or the file extension. If it decides not to handle this file, it
10743 should just return nil to give other functions a chance. If it
10744 does handle the file, it must return the search string to be used
10745 when following the link. The search string will be part of the
10746 file link, given after a double colon, and `org-open-at-point'
10747 will automatically search for it. If special measures must be
10748 taken to make the search successful, another function should be
10749 added to the companion hook `org-execute-file-search-functions',
10750 which see.
10752 A function in this hook may also use `setq' to set the variable
10753 `description' to provide a suggestion for the descriptive text to
10754 be used for this link when it gets inserted into an Org-mode
10755 buffer with \\[org-insert-link].")
10757 (defvar org-execute-file-search-functions nil
10758 "List of functions to execute a file search triggered by a link.
10760 Functions added to this hook must accept a single argument, the
10761 search string that was part of the file link, the part after the
10762 double colon. The function must first check if it would like to
10763 handle this search, for example by checking the `major-mode' or
10764 the file extension. If it decides not to handle this search, it
10765 should just return nil to give other functions a chance. If it
10766 does handle the search, it must return a non-nil value to keep
10767 other functions from trying.
10769 Each function can access the current prefix argument through the
10770 variable `current-prefix-arg'. Note that a single prefix is used
10771 to force opening a link in Emacs, so it may be good to only use a
10772 numeric or double prefix to guide the search function.
10774 In case this is needed, a function in this hook can also restore
10775 the window configuration before `org-open-at-point' was called using:
10777 (set-window-configuration org-window-config-before-follow-link)")
10779 (defun org-link-search (s &optional type avoid-pos stealth)
10780 "Search for a link search option.
10781 If S is surrounded by forward slashes, it is interpreted as a
10782 regular expression. In org-mode files, this will create an `org-occur'
10783 sparse tree. In ordinary files, `occur' will be used to list matches.
10784 If the current buffer is in `dired-mode', grep will be used to search
10785 in all files. If AVOID-POS is given, ignore matches near that position.
10787 When optional argument STEALTH is non-nil, do not modify
10788 visibility around point, thus ignoring
10789 `org-show-hierarchy-above', `org-show-following-heading' and
10790 `org-show-siblings' variables."
10791 (let ((case-fold-search t)
10792 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10793 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10794 (append '(("") (" ") ("\t") ("\n"))
10795 org-emphasis-alist)
10796 "\\|") "\\)"))
10797 (pos (point))
10798 (pre nil) (post nil)
10799 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10800 (cond
10801 ;; First check if there are any special search functions
10802 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10803 ;; Now try the builtin stuff
10804 ((and (equal (string-to-char s0) ?#)
10805 (> (length s0) 1)
10806 (save-excursion
10807 (goto-char (point-min))
10808 (and
10809 (re-search-forward
10810 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10811 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10812 (setq type 'dedicated
10813 pos (match-beginning 0))))
10814 ;; There is an exact target for this
10815 (goto-char pos)
10816 (org-back-to-heading t)))
10817 ((save-excursion
10818 (goto-char (point-min))
10819 (and
10820 (re-search-forward
10821 (concat "<<" (regexp-quote s0) ">>") nil t)
10822 (setq type 'dedicated
10823 pos (match-beginning 0))))
10824 ;; There is an exact target for this
10825 (goto-char pos))
10826 ((save-excursion
10827 (goto-char (point-min))
10828 (and
10829 (re-search-forward
10830 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10831 (setq type 'dedicated pos (match-beginning 0))))
10832 ;; Found an element with a matching #+name affiliated keyword.
10833 (goto-char pos))
10834 ((and (string-match "^(\\(.*\\))$" s0)
10835 (save-excursion
10836 (goto-char (point-min))
10837 (and
10838 (re-search-forward
10839 (concat "[^[]" (regexp-quote
10840 (format org-coderef-label-format
10841 (match-string 1 s0))))
10842 nil t)
10843 (setq type 'dedicated
10844 pos (1+ (match-beginning 0))))))
10845 ;; There is a coderef target for this
10846 (goto-char pos))
10847 ((string-match "^/\\(.*\\)/$" s)
10848 ;; A regular expression
10849 (cond
10850 ((derived-mode-p 'org-mode)
10851 (org-occur (match-string 1 s)))
10852 (t (org-do-occur (match-string 1 s)))))
10853 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10854 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10855 (goto-char (point-min))
10856 (cond
10857 ((let (case-fold-search)
10858 (re-search-forward (format org-complex-heading-regexp-format
10859 (regexp-quote s))
10860 nil t))
10861 ;; OK, found a match
10862 (setq type 'dedicated)
10863 (goto-char (match-beginning 0)))
10864 ((and (not org-link-search-inhibit-query)
10865 (eq org-link-search-must-match-exact-headline 'query-to-create)
10866 (y-or-n-p "No match - create this as a new heading? "))
10867 (goto-char (point-max))
10868 (or (bolp) (newline))
10869 (insert "* " s "\n")
10870 (beginning-of-line 0))
10872 (goto-char pos)
10873 (error "No match"))))
10875 ;; A normal search string
10876 (when (equal (string-to-char s) ?*)
10877 ;; Anchor on headlines, post may include tags.
10878 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10879 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10880 s (substring s 1)))
10881 (remove-text-properties
10882 0 (length s)
10883 '(face nil mouse-face nil keymap nil fontified nil) s)
10884 ;; Make a series of regular expressions to find a match
10885 (setq words (org-split-string s "[ \n\r\t]+")
10887 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10888 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10889 "\\)" markers)
10890 re2a_ (concat "\\(" (mapconcat 'downcase words
10891 "[ \t\r\n]+") "\\)[ \t\r\n]")
10892 re2a (concat "[ \t\r\n]" re2a_)
10893 re4_ (concat "\\(" (mapconcat 'downcase words
10894 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10895 re4 (concat "[^a-zA-Z_]" re4_)
10897 re1 (concat pre re2 post)
10898 re3 (concat pre (if pre re4_ re4) post)
10899 re5 (concat pre ".*" re4)
10900 re2 (concat pre re2)
10901 re2a (concat pre (if pre re2a_ re2a))
10902 re4 (concat pre (if pre re4_ re4))
10903 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10904 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10905 re5 "\\)"))
10906 (cond
10907 ((eq type 'org-occur) (org-occur reall))
10908 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10909 (t (goto-char (point-min))
10910 (setq type 'fuzzy)
10911 (if (or (and (org-search-not-self 1 re0 nil t)
10912 (setq type 'dedicated))
10913 (org-search-not-self 1 re1 nil t)
10914 (org-search-not-self 1 re2 nil t)
10915 (org-search-not-self 1 re2a nil t)
10916 (org-search-not-self 1 re3 nil t)
10917 (org-search-not-self 1 re4 nil t)
10918 (org-search-not-self 1 re5 nil t))
10919 (goto-char (match-beginning 1))
10920 (goto-char pos)
10921 (error "No match"))))))
10922 (and (derived-mode-p 'org-mode)
10923 (not stealth)
10924 (org-show-context 'link-search))
10925 type))
10927 (defun org-search-not-self (group &rest args)
10928 "Execute `re-search-forward', but only accept matches that do not
10929 enclose the position of `org-open-link-marker'."
10930 (let ((m org-open-link-marker))
10931 (catch 'exit
10932 (while (apply 're-search-forward args)
10933 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10934 (goto-char (match-end group))
10935 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10936 (> (match-beginning 0) (marker-position m))
10937 (< (match-end 0) (marker-position m)))
10938 (save-match-data
10939 (or (not (org-in-regexp
10940 org-bracket-link-analytic-regexp 1))
10941 (not (match-end 4)) ; no description
10942 (and (<= (match-beginning 4) (point))
10943 (>= (match-end 4) (point))))))
10944 (throw 'exit (point))))))))
10946 (defun org-get-buffer-for-internal-link (buffer)
10947 "Return a buffer to be used for displaying the link target of internal links."
10948 (cond
10949 ((not org-display-internal-link-with-indirect-buffer)
10950 buffer)
10951 ((string-match "(Clone)$" (buffer-name buffer))
10952 (message "Buffer is already a clone, not making another one")
10953 ;; we also do not modify visibility in this case
10954 buffer)
10955 (t ; make a new indirect buffer for displaying the link
10956 (let* ((bn (buffer-name buffer))
10957 (ibn (concat bn "(Clone)"))
10958 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10959 (with-current-buffer ib (org-overview))
10960 ib))))
10962 (defun org-do-occur (regexp &optional cleanup)
10963 "Call the Emacs command `occur'.
10964 If CLEANUP is non-nil, remove the printout of the regular expression
10965 in the *Occur* buffer. This is useful if the regex is long and not useful
10966 to read."
10967 (occur regexp)
10968 (when cleanup
10969 (let ((cwin (selected-window)) win beg end)
10970 (when (setq win (get-buffer-window "*Occur*"))
10971 (select-window win))
10972 (goto-char (point-min))
10973 (when (re-search-forward "match[a-z]+" nil t)
10974 (setq beg (match-end 0))
10975 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10976 (setq end (1- (match-beginning 0)))))
10977 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10978 (goto-char (point-min))
10979 (select-window cwin))))
10981 ;;; The mark ring for links jumps
10983 (defvar org-mark-ring nil
10984 "Mark ring for positions before jumps in Org-mode.")
10985 (defvar org-mark-ring-last-goto nil
10986 "Last position in the mark ring used to go back.")
10987 ;; Fill and close the ring
10988 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10989 (loop for i from 1 to org-mark-ring-length do
10990 (push (make-marker) org-mark-ring))
10991 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10992 org-mark-ring)
10994 (defun org-mark-ring-push (&optional pos buffer)
10995 "Put the current position or POS into the mark ring and rotate it."
10996 (interactive)
10997 (setq pos (or pos (point)))
10998 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10999 (move-marker (car org-mark-ring)
11000 (or pos (point))
11001 (or buffer (current-buffer)))
11002 (message "%s"
11003 (substitute-command-keys
11004 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
11006 (defun org-mark-ring-goto (&optional n)
11007 "Jump to the previous position in the mark ring.
11008 With prefix arg N, jump back that many stored positions. When
11009 called several times in succession, walk through the entire ring.
11010 Org-mode commands jumping to a different position in the current file,
11011 or to another Org-mode file, automatically push the old position
11012 onto the ring."
11013 (interactive "p")
11014 (let (p m)
11015 (if (eq last-command this-command)
11016 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11017 (setq p org-mark-ring))
11018 (setq org-mark-ring-last-goto p)
11019 (setq m (car p))
11020 (org-pop-to-buffer-same-window (marker-buffer m))
11021 (goto-char m)
11022 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11024 (defun org-remove-angle-brackets (s)
11025 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
11026 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
11028 (defun org-add-angle-brackets (s)
11029 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
11030 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
11032 (defun org-remove-double-quotes (s)
11033 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
11034 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
11037 ;;; Following specific links
11039 (defun org-follow-timestamp-link ()
11040 "Open an agenda view for the time-stamp date/range at point."
11041 (cond
11042 ((org-at-date-range-p t)
11043 (let ((org-agenda-start-on-weekday)
11044 (t1 (match-string 1))
11045 (t2 (match-string 2)) tt1 tt2)
11046 (setq tt1 (time-to-days (org-time-string-to-time t1))
11047 tt2 (time-to-days (org-time-string-to-time t2)))
11048 (let ((org-agenda-buffer-tmp-name
11049 (format "*Org Agenda(a:%s)"
11050 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11051 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11052 ((org-at-timestamp-p t)
11053 (let ((org-agenda-buffer-tmp-name
11054 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11055 (org-agenda-list nil (time-to-days (org-time-string-to-time
11056 (substring (match-string 1) 0 10)))
11057 1)))
11058 (t (error "This should not happen"))))
11061 ;;; Following file links
11062 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11063 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11064 (declare-function mailcap-mime-info
11065 "mailcap" (string &optional request no-decode))
11066 (defvar org-wait nil)
11067 (defun org-open-file (path &optional in-emacs line search)
11068 "Open the file at PATH.
11069 First, this expands any special file name abbreviations. Then the
11070 configuration variable `org-file-apps' is checked if it contains an
11071 entry for this file type, and if yes, the corresponding command is launched.
11073 If no application is found, Emacs simply visits the file.
11075 With optional prefix argument IN-EMACS, Emacs will visit the file.
11076 With a double \\[universal-argument] \\[universal-argument] \
11077 prefix arg, Org tries to avoid opening in Emacs
11078 and to use an external application to visit the file.
11080 Optional LINE specifies a line to go to, optional SEARCH a string
11081 to search for. If LINE or SEARCH is given, the file will be
11082 opened in Emacs, unless an entry from org-file-apps that makes
11083 use of groups in a regexp matches.
11085 If you want to change the way frames are used when following a
11086 link, please customize `org-link-frame-setup'.
11088 If the file does not exist, an error is thrown."
11089 (let* ((file (if (equal path "")
11090 buffer-file-name
11091 (substitute-in-file-name (expand-file-name path))))
11092 (file-apps (append org-file-apps (org-default-apps)))
11093 (apps (org-remove-if
11094 'org-file-apps-entry-match-against-dlink-p file-apps))
11095 (apps-dlink (org-remove-if-not
11096 'org-file-apps-entry-match-against-dlink-p file-apps))
11097 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11098 (dirp (if remp nil (file-directory-p file)))
11099 (file (if (and dirp org-open-directory-means-index-dot-org)
11100 (concat (file-name-as-directory file) "index.org")
11101 file))
11102 (a-m-a-p (assq 'auto-mode apps))
11103 (dfile (downcase file))
11104 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
11105 (link (cond ((and (eq line nil)
11106 (eq search nil))
11107 file)
11108 (line
11109 (concat file "::" (number-to-string line)))
11110 (search
11111 (concat file "::" search))))
11112 (dlink (downcase link))
11113 (old-buffer (current-buffer))
11114 (old-pos (point))
11115 (old-mode major-mode)
11116 ext cmd link-match-data)
11117 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11118 (setq ext (match-string 1 dfile))
11119 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11120 (setq ext (match-string 1 dfile))))
11121 (cond
11122 ((member in-emacs '((16) system))
11123 (setq cmd (cdr (assoc 'system apps))))
11124 (in-emacs (setq cmd 'emacs))
11126 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11127 (and dirp (cdr (assoc 'directory apps)))
11128 ; first, try matching against apps-dlink
11129 ; if we get a match here, store the match data for later
11130 (let ((match (assoc-default dlink apps-dlink
11131 'string-match)))
11132 (if match
11133 (progn (setq link-match-data (match-data))
11134 match)
11135 (progn (setq in-emacs (or in-emacs line search))
11136 nil))) ; if we have no match in apps-dlink,
11137 ; always open the file in emacs if line or search
11138 ; is given (for backwards compatibility)
11139 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11140 'string-match)
11141 (cdr (assoc ext apps))
11142 (cdr (assoc t apps))))))
11143 (when (eq cmd 'system)
11144 (setq cmd (cdr (assoc 'system apps))))
11145 (when (eq cmd 'default)
11146 (setq cmd (cdr (assoc t apps))))
11147 (when (eq cmd 'mailcap)
11148 (require 'mailcap)
11149 (mailcap-parse-mailcaps)
11150 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11151 (command (mailcap-mime-info mime-type)))
11152 (if (stringp command)
11153 (setq cmd command)
11154 (setq cmd 'emacs))))
11155 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11156 (not (file-exists-p file))
11157 (not org-open-non-existing-files))
11158 (user-error "No such file: %s" file))
11159 (cond
11160 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11161 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11162 (while (string-match "['\"]%s['\"]" cmd)
11163 (setq cmd (replace-match "%s" t t cmd)))
11164 (while (string-match "%s" cmd)
11165 (setq cmd (replace-match
11166 (save-match-data
11167 (shell-quote-argument
11168 (convert-standard-filename file)))
11169 t t cmd)))
11171 ;; Replace "%1", "%2" etc. in command with group matches from regex
11172 (save-match-data
11173 (let ((match-index 1)
11174 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11175 (set-match-data link-match-data)
11176 (while (<= match-index number-of-groups)
11177 (let ((regex (concat "%" (number-to-string match-index)))
11178 (replace-with (match-string match-index dlink)))
11179 (while (string-match regex cmd)
11180 (setq cmd (replace-match replace-with t t cmd))))
11181 (setq match-index (+ match-index 1)))))
11183 (save-window-excursion
11184 (message "Running %s...done" cmd)
11185 (start-process-shell-command cmd nil cmd)
11186 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11187 ((or (stringp cmd)
11188 (eq cmd 'emacs))
11189 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11190 (widen)
11191 (if line (progn (org-goto-line line)
11192 (if (derived-mode-p 'org-mode)
11193 (org-reveal)))
11194 (if search (org-link-search search))))
11195 ((consp cmd)
11196 (let ((file (convert-standard-filename file)))
11197 (save-match-data
11198 (set-match-data link-match-data)
11199 (eval cmd))))
11200 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11201 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11202 (or (not (equal old-buffer (current-buffer)))
11203 (not (equal old-pos (point))))
11204 (org-mark-ring-push old-pos old-buffer))))
11206 (defun org-file-apps-entry-match-against-dlink-p (entry)
11207 "This function returns non-nil if `entry' uses a regular
11208 expression which should be matched against the whole link by
11209 org-open-file.
11211 It assumes that is the case when the entry uses a regular
11212 expression which has at least one grouping construct and the
11213 action is either a lisp form or a command string containing
11214 '%1', i.e. using at least one subexpression match as a
11215 parameter."
11216 (let ((selector (car entry))
11217 (action (cdr entry)))
11218 (if (stringp selector)
11219 (and (> (regexp-opt-depth selector) 0)
11220 (or (and (stringp action)
11221 (string-match "%[0-9]" action))
11222 (consp action)))
11223 nil)))
11225 (defun org-default-apps ()
11226 "Return the default applications for this operating system."
11227 (cond
11228 ((eq system-type 'darwin)
11229 org-file-apps-defaults-macosx)
11230 ((eq system-type 'windows-nt)
11231 org-file-apps-defaults-windowsnt)
11232 (t org-file-apps-defaults-gnu)))
11234 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11235 "Convert extensions to regular expressions in the cars of LIST.
11236 Also, weed out any non-string entries, because the return value is used
11237 only for regexp matching.
11238 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11239 point to the symbol `emacs', indicating that the file should
11240 be opened in Emacs."
11241 (append
11242 (delq nil
11243 (mapcar (lambda (x)
11244 (if (not (stringp (car x)))
11246 (if (string-match "\\W" (car x))
11248 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11249 list))
11250 (if add-auto-mode
11251 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11253 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11254 (defun org-file-remote-p (file)
11255 "Test whether FILE specifies a location on a remote system.
11256 Return non-nil if the location is indeed remote.
11258 For example, the filename \"/user@host:/foo\" specifies a location
11259 on the system \"/user@host:\"."
11260 (cond ((fboundp 'file-remote-p)
11261 (file-remote-p file))
11262 ((fboundp 'tramp-handle-file-remote-p)
11263 (tramp-handle-file-remote-p file))
11264 ((and (boundp 'ange-ftp-name-format)
11265 (string-match (car ange-ftp-name-format) file))
11266 t)))
11269 ;;;; Refiling
11271 (defun org-get-org-file ()
11272 "Read a filename, with default directory `org-directory'."
11273 (let ((default (or org-default-notes-file remember-data-file)))
11274 (read-file-name (format "File name [%s]: " default)
11275 (file-name-as-directory org-directory)
11276 default)))
11278 (defun org-notes-order-reversed-p ()
11279 "Check if the current file should receive notes in reversed order."
11280 (cond
11281 ((not org-reverse-note-order) nil)
11282 ((eq t org-reverse-note-order) t)
11283 ((not (listp org-reverse-note-order)) nil)
11284 (t (catch 'exit
11285 (let ((all org-reverse-note-order)
11286 entry)
11287 (while (setq entry (pop all))
11288 (if (string-match (car entry) buffer-file-name)
11289 (throw 'exit (cdr entry))))
11290 nil)))))
11292 (defvar org-refile-target-table nil
11293 "The list of refile targets, created by `org-refile'.")
11295 (defvar org-agenda-new-buffers nil
11296 "Buffers created to visit agenda files.")
11298 (defvar org-refile-cache nil
11299 "Cache for refile targets.")
11301 (defvar org-refile-markers nil
11302 "All the markers used for caching refile locations.")
11304 (defun org-refile-marker (pos)
11305 "Get a new refile marker, but only if caching is in use."
11306 (if (not org-refile-use-cache)
11308 (let ((m (make-marker)))
11309 (move-marker m pos)
11310 (push m org-refile-markers)
11311 m)))
11313 (defun org-refile-cache-clear ()
11314 "Clear the refile cache and disable all the markers."
11315 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11316 (setq org-refile-markers nil)
11317 (setq org-refile-cache nil)
11318 (message "Refile cache has been cleared"))
11320 (defun org-refile-cache-check-set (set)
11321 "Check if all the markers in the cache still have live buffers."
11322 (let (marker)
11323 (catch 'exit
11324 (while (and set (setq marker (nth 3 (pop set))))
11325 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11326 (when (and marker (null (marker-buffer marker)))
11327 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11328 (sit-for 3)
11329 (throw 'exit nil)))
11330 t)))
11332 (defun org-refile-cache-put (set &rest identifiers)
11333 "Push the refile targets SET into the cache, under IDENTIFIERS."
11334 (let* ((key (sha1 (prin1-to-string identifiers)))
11335 (entry (assoc key org-refile-cache)))
11336 (if entry
11337 (setcdr entry set)
11338 (push (cons key set) org-refile-cache))))
11340 (defun org-refile-cache-get (&rest identifiers)
11341 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11342 (cond
11343 ((not org-refile-cache) nil)
11344 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11346 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11347 org-refile-cache))))
11348 (and set (org-refile-cache-check-set set) set)))))
11350 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11351 "Produce a table with refile targets."
11352 (let ((case-fold-search nil)
11353 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11354 (entries (or org-refile-targets '((nil . (:level . 1)))))
11355 targets tgs txt re files f desc descre fast-path-p level pos0)
11356 (message "Getting targets...")
11357 (with-current-buffer (or default-buffer (current-buffer))
11358 (while (setq entry (pop entries))
11359 (setq files (car entry) desc (cdr entry))
11360 (setq fast-path-p nil)
11361 (cond
11362 ((null files) (setq files (list (current-buffer))))
11363 ((eq files 'org-agenda-files)
11364 (setq files (org-agenda-files 'unrestricted)))
11365 ((and (symbolp files) (fboundp files))
11366 (setq files (funcall files)))
11367 ((and (symbolp files) (boundp files))
11368 (setq files (symbol-value files))))
11369 (if (stringp files) (setq files (list files)))
11370 (cond
11371 ((eq (car desc) :tag)
11372 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11373 ((eq (car desc) :todo)
11374 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11375 ((eq (car desc) :regexp)
11376 (setq descre (cdr desc)))
11377 ((eq (car desc) :level)
11378 (setq descre (concat "^\\*\\{" (number-to-string
11379 (if org-odd-levels-only
11380 (1- (* 2 (cdr desc)))
11381 (cdr desc)))
11382 "\\}[ \t]")))
11383 ((eq (car desc) :maxlevel)
11384 (setq fast-path-p t)
11385 (setq descre (concat "^\\*\\{1," (number-to-string
11386 (if org-odd-levels-only
11387 (1- (* 2 (cdr desc)))
11388 (cdr desc)))
11389 "\\}[ \t]")))
11390 (t (error "Bad refiling target description %s" desc)))
11391 (while (setq f (pop files))
11392 (with-current-buffer
11393 (if (bufferp f) f (org-get-agenda-file-buffer f))
11395 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11396 (progn
11397 (if (bufferp f) (setq f (buffer-file-name
11398 (buffer-base-buffer f))))
11399 (setq f (and f (expand-file-name f)))
11400 (if (eq org-refile-use-outline-path 'file)
11401 (push (list (file-name-nondirectory f) f nil nil) tgs))
11402 (save-excursion
11403 (save-restriction
11404 (widen)
11405 (goto-char (point-min))
11406 (while (re-search-forward descre nil t)
11407 (goto-char (setq pos0 (point-at-bol)))
11408 (catch 'next
11409 (when org-refile-target-verify-function
11410 (save-match-data
11411 (or (funcall org-refile-target-verify-function)
11412 (throw 'next t))))
11413 (when (and (looking-at org-complex-heading-regexp)
11414 (not (member (match-string 4) excluded-entries))
11415 (match-string 4))
11416 (setq level (org-reduced-level
11417 (- (match-end 1) (match-beginning 1)))
11418 txt (org-link-display-format (match-string 4))
11419 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11420 re (format org-complex-heading-regexp-format
11421 (regexp-quote (match-string 4))))
11422 (when org-refile-use-outline-path
11423 (setq txt (mapconcat
11424 'org-protect-slash
11425 (append
11426 (if (eq org-refile-use-outline-path
11427 'file)
11428 (list (file-name-nondirectory
11429 (buffer-file-name
11430 (buffer-base-buffer))))
11431 (if (eq org-refile-use-outline-path
11432 'full-file-path)
11433 (list (buffer-file-name
11434 (buffer-base-buffer)))))
11435 (org-get-outline-path fast-path-p
11436 level txt)
11437 (list txt))
11438 "/")))
11439 (push (list txt f re (org-refile-marker (point)))
11440 tgs)))
11441 (when (= (point) pos0)
11442 ;; verification function has not moved point
11443 (goto-char (point-at-eol))))))))
11444 (when org-refile-use-cache
11445 (org-refile-cache-put tgs (buffer-file-name) descre))
11446 (setq targets (append tgs targets))))))
11447 (message "Getting targets...done")
11448 (nreverse targets)))
11450 (defun org-protect-slash (s)
11451 (while (string-match "/" s)
11452 (setq s (replace-match "\\" t t s)))
11455 (defvar org-olpa (make-vector 20 nil))
11457 (defun org-get-outline-path (&optional fastp level heading)
11458 "Return the outline path to the current entry, as a list.
11460 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11461 routine which makes outline path derivations for an entire file,
11462 avoiding backtracing. Refile target collection makes use of that."
11463 (if fastp
11464 (progn
11465 (if (> level 19)
11466 (error "Outline path failure, more than 19 levels"))
11467 (loop for i from level upto 19 do
11468 (aset org-olpa i nil))
11469 (prog1
11470 (delq nil (append org-olpa nil))
11471 (aset org-olpa level heading)))
11472 (let (rtn case-fold-search)
11473 (save-excursion
11474 (save-restriction
11475 (widen)
11476 (while (org-up-heading-safe)
11477 (when (looking-at org-complex-heading-regexp)
11478 (push (org-trim
11479 (replace-regexp-in-string
11480 ;; Remove statistical/checkboxes cookies
11481 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11482 (org-match-string-no-properties 4)))
11483 rtn)))
11484 rtn)))))
11486 (defun org-format-outline-path (path &optional width prefix separator)
11487 "Format the outline path PATH for display.
11488 WIDTH is the maximum number of characters that is available.
11489 PREFIX is a prefix to be included in the returned string,
11490 such as the file name.
11491 SEPARATOR is inserted between the different parts of the path,
11492 the default is \"/\"."
11493 (setq width (or width 79))
11494 (if prefix (setq width (- width (length prefix))))
11495 (if (not path)
11496 (or prefix "")
11497 (let* ((nsteps (length path))
11498 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11499 (maxwidth (if (<= total-width width)
11500 10000 ;; everything fits
11501 ;; we need to shorten the level headings
11502 (/ (- width nsteps) nsteps)))
11503 (org-odd-levels-only nil)
11504 (n 0)
11505 (total (1+ (length prefix))))
11506 (setq maxwidth (max maxwidth 10))
11507 (concat prefix
11508 (if prefix (or separator "/"))
11509 (mapconcat
11510 (lambda (h)
11511 (setq n (1+ n))
11512 (if (and (= n nsteps) (< maxwidth 10000))
11513 (setq maxwidth (- total-width total)))
11514 (if (< (length h) maxwidth)
11515 (progn (setq total (+ total (length h) 1)) h)
11516 (setq h (substring h 0 (- maxwidth 2))
11517 total (+ total maxwidth 1))
11518 (if (string-match "[ \t]+\\'" h)
11519 (setq h (substring h 0 (match-beginning 0))))
11520 (setq h (concat h "..")))
11521 (org-add-props h nil 'face
11522 (nth (% (1- n) org-n-level-faces)
11523 org-level-faces))
11525 path (or separator "/"))))))
11527 (defun org-display-outline-path (&optional file current separator just-return-string)
11528 "Display the current outline path in the echo area.
11530 If FILE is non-nil, prepend the output with the file name.
11531 If CURRENT is non-nil, append the current heading to the output.
11532 SEPARATOR is passed through to `org-format-outline-path'. It separates
11533 the different parts of the path and defaults to \"/\".
11534 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11535 (interactive "P")
11536 (let* (case-fold-search
11537 (bfn (buffer-file-name (buffer-base-buffer)))
11538 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11539 res)
11540 (if current (setq path (append path
11541 (save-excursion
11542 (org-back-to-heading t)
11543 (if (looking-at org-complex-heading-regexp)
11544 (list (match-string 4)))))))
11545 (setq res
11546 (org-format-outline-path
11547 path
11548 (1- (frame-width))
11549 (and file bfn (concat (file-name-nondirectory bfn) separator))
11550 separator))
11551 (if just-return-string
11552 (org-no-properties res)
11553 (org-unlogged-message "%s" res))))
11555 (defvar org-refile-history nil
11556 "History for refiling operations.")
11558 (defvar org-after-refile-insert-hook nil
11559 "Hook run after `org-refile' has inserted its stuff at the new location.
11560 Note that this is still *before* the stuff will be removed from
11561 the *old* location.")
11563 (defvar org-capture-last-stored-marker)
11564 (defvar org-refile-keep nil
11565 "Non-nil means `org-refile' will copy instead of refile.")
11567 (defun org-copy ()
11568 "Like `org-refile', but copy."
11569 (interactive)
11570 (let ((org-refile-keep t))
11571 (funcall 'org-refile nil nil nil "Copy")))
11573 (defun org-refile (&optional goto default-buffer rfloc msg)
11574 "Move the entry or entries at point to another heading.
11575 The list of target headings is compiled using the information in
11576 `org-refile-targets', which see.
11578 At the target location, the entry is filed as a subitem of the target
11579 heading. Depending on `org-reverse-note-order', the new subitem will
11580 either be the first or the last subitem.
11582 If there is an active region, all entries in that region will be moved.
11583 However, the region must fulfill the requirement that the first heading
11584 is the first one sets the top-level of the moved text - at most siblings
11585 below it are allowed.
11587 With prefix arg GOTO, the command will only visit the target location
11588 and not actually move anything.
11590 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11591 go to the location where the last refiling operation has put the subtree.
11593 With a numeric prefix argument of `2', refile to the running clock.
11595 With a numeric prefix argument of `3', emulate `org-refile-keep'
11596 being set to `t' and copy to the target location, don't move it.
11597 Beware that keeping refiled entries may result in duplicated ID
11598 properties.
11600 RFLOC can be a refile location obtained in a different way.
11602 MSG is a string to replace \"Refile\" in the default prompt with
11603 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11605 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11607 If you are using target caching (see `org-refile-use-cache'),
11608 you have to clear the target cache in order to find new targets.
11609 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11610 prefix argument (`C-u C-u C-u C-c C-w')."
11612 (interactive "P")
11613 (if (member goto '(0 (64)))
11614 (org-refile-cache-clear)
11615 (let* ((actionmsg (or msg "Refile"))
11616 (cbuf (current-buffer))
11617 (regionp (org-region-active-p))
11618 (region-start (and regionp (region-beginning)))
11619 (region-end (and regionp (region-end)))
11620 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11621 (org-refile-keep (if (equal goto 3) t org-refile-keep))
11622 pos it nbuf file re level reversed)
11623 (setq last-command nil)
11624 (when regionp
11625 (goto-char region-start)
11626 (or (bolp) (goto-char (point-at-bol)))
11627 (setq region-start (point))
11628 (unless (or (org-kill-is-subtree-p
11629 (buffer-substring region-start region-end))
11630 (prog1 org-refile-active-region-within-subtree
11631 (let ((s (point-at-eol)))
11632 (org-toggle-heading)
11633 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11634 (user-error "The region is not a (sequence of) subtree(s)")))
11635 (if (equal goto '(16))
11636 (org-refile-goto-last-stored)
11637 (when (or
11638 (and (equal goto 2)
11639 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11640 (prog1
11641 (setq it (list (or org-clock-heading "running clock")
11642 (buffer-file-name
11643 (marker-buffer org-clock-hd-marker))
11645 (marker-position org-clock-hd-marker)))
11646 (setq goto nil)))
11647 (setq it (or rfloc
11648 (let (heading-text)
11649 (save-excursion
11650 (unless goto
11651 (org-back-to-heading t)
11652 (setq heading-text
11653 (nth 4 (org-heading-components))))
11655 (org-refile-get-location
11656 (cond (goto "Goto")
11657 (regionp (concat actionmsg " region to"))
11658 (t (concat actionmsg " subtree \""
11659 heading-text "\" to")))
11660 default-buffer
11661 (and (not (equal '(4) goto))
11662 org-refile-allow-creating-parent-nodes)
11663 goto))))))
11664 (setq file (nth 1 it)
11665 re (nth 2 it)
11666 pos (nth 3 it))
11667 (if (and (not goto)
11669 (equal (buffer-file-name) file)
11670 (if regionp
11671 (and (>= pos region-start)
11672 (<= pos region-end))
11673 (and (>= pos (point))
11674 (< pos (save-excursion
11675 (org-end-of-subtree t t))))))
11676 (error "Cannot refile to position inside the tree or region"))
11678 (setq nbuf (or (find-buffer-visiting file)
11679 (find-file-noselect file)))
11680 (if (and goto (not (equal goto 3)))
11681 (progn
11682 (org-pop-to-buffer-same-window nbuf)
11683 (goto-char pos)
11684 (org-show-context 'org-goto))
11685 (if regionp
11686 (progn
11687 (org-kill-new (buffer-substring region-start region-end))
11688 (org-save-markers-in-region region-start region-end))
11689 (org-copy-subtree 1 nil t))
11690 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11691 (find-file-noselect file)))
11692 (setq reversed (org-notes-order-reversed-p))
11693 (save-excursion
11694 (save-restriction
11695 (widen)
11696 (if pos
11697 (progn
11698 (goto-char pos)
11699 (looking-at org-outline-regexp)
11700 (setq level (org-get-valid-level (funcall outline-level) 1))
11701 (goto-char
11702 (if reversed
11703 (or (outline-next-heading) (point-max))
11704 (or (save-excursion (org-get-next-sibling))
11705 (org-end-of-subtree t t)
11706 (point-max)))))
11707 (setq level 1)
11708 (if (not reversed)
11709 (goto-char (point-max))
11710 (goto-char (point-min))
11711 (or (outline-next-heading) (goto-char (point-max)))))
11712 (if (not (bolp)) (newline))
11713 (org-paste-subtree level)
11714 (when org-log-refile
11715 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11716 (unless (eq org-log-refile 'note)
11717 (save-excursion (org-add-log-note))))
11718 (and org-auto-align-tags
11719 (let ((org-loop-over-headlines-in-active-region nil))
11720 (org-set-tags nil t)))
11721 (let ((bookmark-name (plist-get org-bookmark-names-plist
11722 :last-refile)))
11723 (when bookmark-name
11724 (with-demoted-errors
11725 (bookmark-set bookmark-name))))
11726 ;; If we are refiling for capture, make sure that the
11727 ;; last-capture pointers point here
11728 (when (org-bound-and-true-p org-refile-for-capture)
11729 (let ((bookmark-name (plist-get org-bookmark-names-plist
11730 :last-capture-marker)))
11731 (when bookmark-name
11732 (with-demoted-errors
11733 (bookmark-set bookmark-name))))
11734 (move-marker org-capture-last-stored-marker (point)))
11735 (if (fboundp 'deactivate-mark) (deactivate-mark))
11736 (run-hooks 'org-after-refile-insert-hook))))
11737 (unless org-refile-keep
11738 (if regionp
11739 (delete-region (point) (+ (point) (- region-end region-start)))
11740 (delete-region
11741 (and (org-back-to-heading t) (point))
11742 (min (buffer-size) (org-end-of-subtree t t) (point)))))
11743 (when (featurep 'org-inlinetask)
11744 (org-inlinetask-remove-END-maybe))
11745 (setq org-markers-to-move nil)
11746 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11748 (defun org-refile-goto-last-stored ()
11749 "Go to the location where the last refile was stored."
11750 (interactive)
11751 (bookmark-jump "org-refile-last-stored")
11752 (message "This is the location of the last refile"))
11754 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11755 no-exclude)
11756 "Prompt the user for a refile location, using PROMPT.
11757 PROMPT should not be suffixed with a colon and a space, because
11758 this function appends the default value from
11759 `org-refile-history' automatically, if that is not empty.
11760 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11761 this is used for the GOTO interface."
11762 (let ((org-refile-targets org-refile-targets)
11763 (org-refile-use-outline-path org-refile-use-outline-path)
11764 excluded-entries)
11765 (when (and (derived-mode-p 'org-mode)
11766 (not org-refile-use-cache)
11767 (not no-exclude))
11768 (org-map-tree
11769 (lambda()
11770 (setq excluded-entries
11771 (append excluded-entries (list (org-get-heading t t)))))))
11772 (setq org-refile-target-table
11773 (org-refile-get-targets default-buffer excluded-entries)))
11774 (unless org-refile-target-table
11775 (user-error "No refile targets"))
11776 (let* ((cbuf (current-buffer))
11777 (partial-completion-mode nil)
11778 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11779 (cfunc (if (and org-refile-use-outline-path
11780 org-outline-path-complete-in-steps)
11781 'org-olpath-completing-read
11782 'org-icompleting-read))
11783 (extra (if org-refile-use-outline-path "/" ""))
11784 (cbnex (concat (buffer-name) extra))
11785 (filename (and cfn (expand-file-name cfn)))
11786 (tbl (mapcar
11787 (lambda (x)
11788 (if (and (not (member org-refile-use-outline-path
11789 '(file full-file-path)))
11790 (not (equal filename (nth 1 x))))
11791 (cons (concat (car x) extra " ("
11792 (file-name-nondirectory (nth 1 x)) ")")
11793 (cdr x))
11794 (cons (concat (car x) extra) (cdr x))))
11795 org-refile-target-table))
11796 (completion-ignore-case t)
11797 cdef
11798 (prompt (concat prompt
11799 (or (and (car org-refile-history)
11800 (concat " (default " (car org-refile-history) ")"))
11801 (and (assoc cbnex tbl) (setq cdef cbnex)
11802 (concat " (default " cbnex ")"))) ": "))
11803 pa answ parent-target child parent old-hist)
11804 (setq old-hist org-refile-history)
11805 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11806 nil 'org-refile-history (or cdef (car org-refile-history))))
11807 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11808 (if pa
11809 (progn
11810 (org-refile-check-position pa)
11811 (when (or (not org-refile-history)
11812 (not (eq old-hist org-refile-history))
11813 (not (equal (car pa) (car org-refile-history))))
11814 (setq org-refile-history
11815 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11816 org-refile-history
11817 (cdr org-refile-history))))
11818 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11819 (pop org-refile-history)))
11821 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11822 (progn
11823 (setq parent (match-string 1 answ)
11824 child (match-string 2 answ))
11825 (setq parent-target (or (assoc parent tbl)
11826 (assoc (concat parent "/") tbl)))
11827 (when (and parent-target
11828 (or (eq new-nodes t)
11829 (and (eq new-nodes 'confirm)
11830 (y-or-n-p (format "Create new node \"%s\"? "
11831 child)))))
11832 (org-refile-new-child parent-target child)))
11833 (user-error "Invalid target location")))))
11835 (declare-function org-string-nw-p "org-macs" (s))
11836 (defun org-refile-check-position (refile-pointer)
11837 "Check if the refile pointer matches the headline to which it points."
11838 (let* ((file (nth 1 refile-pointer))
11839 (re (nth 2 refile-pointer))
11840 (pos (nth 3 refile-pointer))
11841 buffer)
11842 (if (and (not (markerp pos)) (not file))
11843 (if file
11844 (user-error "Please save the buffer to a file before refiling")
11845 (user-error "Please indicate a target file in the refile path"))
11846 (when (org-string-nw-p re)
11847 (setq buffer (if (markerp pos)
11848 (marker-buffer pos)
11849 (or (find-buffer-visiting file)
11850 (find-file-noselect file))))
11851 (with-current-buffer buffer
11852 (save-excursion
11853 (save-restriction
11854 (widen)
11855 (goto-char pos)
11856 (beginning-of-line 1)
11857 (unless (org-looking-at-p re)
11858 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11860 (defun org-refile-new-child (parent-target child)
11861 "Use refile target PARENT-TARGET to add new CHILD below it."
11862 (unless parent-target
11863 (error "Cannot find parent for new node"))
11864 (let ((file (nth 1 parent-target))
11865 (pos (nth 3 parent-target))
11866 level)
11867 (with-current-buffer (or (find-buffer-visiting file)
11868 (find-file-noselect file))
11869 (save-excursion
11870 (save-restriction
11871 (widen)
11872 (if pos
11873 (goto-char pos)
11874 (goto-char (point-max))
11875 (if (not (bolp)) (newline)))
11876 (when (looking-at org-outline-regexp)
11877 (setq level (funcall outline-level))
11878 (org-end-of-subtree t t))
11879 (org-back-over-empty-lines)
11880 (insert "\n" (make-string
11881 (if pos (org-get-valid-level level 1) 1) ?*)
11882 " " child "\n")
11883 (beginning-of-line 0)
11884 (list (concat (car parent-target) "/" child) file "" (point)))))))
11886 (defun org-olpath-completing-read (prompt collection &rest args)
11887 "Read an outline path like a file name."
11888 (let ((thetable collection)
11889 (org-completion-use-ido nil) ; does not work with ido.
11890 (org-completion-use-iswitchb nil)) ; or iswitchb
11891 (apply
11892 'org-icompleting-read prompt
11893 (lambda (string predicate &optional flag)
11894 (let (rtn r f (l (length string)))
11895 (cond
11896 ((eq flag nil)
11897 ;; try completion
11898 (try-completion string thetable))
11899 ((eq flag t)
11900 ;; all-completions
11901 (setq rtn (all-completions string thetable predicate))
11902 (mapcar
11903 (lambda (x)
11904 (setq r (substring x l))
11905 (if (string-match " ([^)]*)$" x)
11906 (setq f (match-string 0 x))
11907 (setq f ""))
11908 (if (string-match "/" r)
11909 (concat string (substring r 0 (match-end 0)) f)
11911 rtn))
11912 ((eq flag 'lambda)
11913 ;; exact match?
11914 (assoc string thetable)))))
11915 args)))
11917 ;;;; Dynamic blocks
11919 (defun org-find-dblock (name)
11920 "Find the first dynamic block with name NAME in the buffer.
11921 If not found, stay at current position and return nil."
11922 (let ((case-fold-search t) pos)
11923 (save-excursion
11924 (goto-char (point-min))
11925 (setq pos (and (re-search-forward
11926 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11927 (match-beginning 0))))
11928 (if pos (goto-char pos))
11929 pos))
11931 (defun org-create-dblock (plist)
11932 "Create a dynamic block section, with parameters taken from PLIST.
11933 PLIST must contain a :name entry which is used as name of the block."
11934 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11935 (end-of-line 1)
11936 (newline))
11937 (let ((col (current-column))
11938 (name (plist-get plist :name)))
11939 (insert "#+BEGIN: " name)
11940 (while plist
11941 (if (eq (car plist) :name)
11942 (setq plist (cddr plist))
11943 (insert " " (prin1-to-string (pop plist)))))
11944 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11945 (beginning-of-line -2)))
11947 (defun org-prepare-dblock ()
11948 "Prepare dynamic block for refresh.
11949 This empties the block, puts the cursor at the insert position and returns
11950 the property list including an extra property :name with the block name."
11951 (unless (looking-at org-dblock-start-re)
11952 (user-error "Not at a dynamic block"))
11953 (let* ((begdel (1+ (match-end 0)))
11954 (name (org-no-properties (match-string 1)))
11955 (params (append (list :name name)
11956 (read (concat "(" (match-string 3) ")")))))
11957 (save-excursion
11958 (beginning-of-line 1)
11959 (skip-chars-forward " \t")
11960 (setq params (plist-put params :indentation-column (current-column))))
11961 (unless (re-search-forward org-dblock-end-re nil t)
11962 (error "Dynamic block not terminated"))
11963 (setq params
11964 (append params
11965 (list :content (buffer-substring
11966 begdel (match-beginning 0)))))
11967 (delete-region begdel (match-beginning 0))
11968 (goto-char begdel)
11969 (open-line 1)
11970 params))
11972 (defun org-map-dblocks (&optional command)
11973 "Apply COMMAND to all dynamic blocks in the current buffer.
11974 If COMMAND is not given, use `org-update-dblock'."
11975 (let ((cmd (or command 'org-update-dblock)))
11976 (save-excursion
11977 (goto-char (point-min))
11978 (while (re-search-forward org-dblock-start-re nil t)
11979 (goto-char (match-beginning 0))
11980 (save-excursion
11981 (condition-case nil
11982 (funcall cmd)
11983 (error (message "Error during update of dynamic block"))))
11984 (unless (re-search-forward org-dblock-end-re nil t)
11985 (error "Dynamic block not terminated"))))))
11987 (defun org-dblock-update (&optional arg)
11988 "User command for updating dynamic blocks.
11989 Update the dynamic block at point. With prefix ARG, update all dynamic
11990 blocks in the buffer."
11991 (interactive "P")
11992 (if arg
11993 (org-update-all-dblocks)
11994 (or (looking-at org-dblock-start-re)
11995 (org-beginning-of-dblock))
11996 (org-update-dblock)))
11998 (defun org-update-dblock ()
11999 "Update the dynamic block at point.
12000 This means to empty the block, parse for parameters and then call
12001 the correct writing function."
12002 (interactive)
12003 (save-window-excursion
12004 (let* ((pos (point))
12005 (line (org-current-line))
12006 (params (org-prepare-dblock))
12007 (name (plist-get params :name))
12008 (indent (plist-get params :indentation-column))
12009 (cmd (intern (concat "org-dblock-write:" name))))
12010 (message "Updating dynamic block `%s' at line %d..." name line)
12011 (funcall cmd params)
12012 (message "Updating dynamic block `%s' at line %d...done" name line)
12013 (goto-char pos)
12014 (when (and indent (> indent 0))
12015 (setq indent (make-string indent ?\ ))
12016 (save-excursion
12017 (org-beginning-of-dblock)
12018 (forward-line 1)
12019 (while (not (looking-at org-dblock-end-re))
12020 (insert indent)
12021 (beginning-of-line 2))
12022 (when (looking-at org-dblock-end-re)
12023 (and (looking-at "[ \t]+")
12024 (replace-match ""))
12025 (insert indent)))))))
12027 (defun org-beginning-of-dblock ()
12028 "Find the beginning of the dynamic block at point.
12029 Error if there is no such block at point."
12030 (let ((pos (point))
12031 beg)
12032 (end-of-line 1)
12033 (if (and (re-search-backward org-dblock-start-re nil t)
12034 (setq beg (match-beginning 0))
12035 (re-search-forward org-dblock-end-re nil t)
12036 (> (match-end 0) pos))
12037 (goto-char beg)
12038 (goto-char pos)
12039 (error "Not in a dynamic block"))))
12041 (defun org-update-all-dblocks ()
12042 "Update all dynamic blocks in the buffer.
12043 This function can be used in a hook."
12044 (interactive)
12045 (when (derived-mode-p 'org-mode)
12046 (org-map-dblocks 'org-update-dblock)))
12049 ;;;; Completion
12051 (declare-function org-export-backend-name "org-export" (cl-x))
12052 (declare-function org-export-backend-options "org-export" (cl-x))
12053 (defun org-get-export-keywords ()
12054 "Return a list of all currently understood export keywords.
12055 Export keywords include options, block names, attributes and
12056 keywords relative to each registered export back-end."
12057 (let (keywords)
12058 (dolist (backend
12059 (org-bound-and-true-p org-export--registered-backends)
12060 (delq nil keywords))
12061 ;; Back-end name (for keywords, like #+LATEX:)
12062 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12063 (dolist (option-entry (org-export-backend-options backend))
12064 ;; Back-end options.
12065 (push (nth 1 option-entry) keywords)))))
12067 (defconst org-options-keywords
12068 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12069 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12070 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12071 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12072 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12074 (defcustom org-structure-template-alist
12075 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC" "<src lang=\"?\">\n\n</src>")
12076 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE" "<example>\n?\n</example>")
12077 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE" "<quote>\n?\n</quote>")
12078 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE" "<verse>\n?\n</verse>")
12079 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM" "<verbatim>\n?\n</verbatim>")
12080 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER" "<center>\n?\n</center>")
12081 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
12082 "<literal style=\"latex\">\n?\n</literal>")
12083 ("L" "#+LaTeX: " "<literal style=\"latex\">?</literal>")
12084 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
12085 "<literal style=\"html\">\n?\n</literal>")
12086 ("H" "#+HTML: " "<literal style=\"html\">?</literal>")
12087 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII" "")
12088 ("A" "#+ASCII: " "")
12089 ("i" "#+INDEX: ?" "#+INDEX: ?")
12090 ("I" "#+INCLUDE: %file ?"
12091 "<include file=%file markup=\"?\">"))
12092 "Structure completion elements.
12093 This is a list of abbreviation keys and values. The value gets inserted
12094 if you type `<' followed by the key and then press the completion key,
12095 usually `M-TAB'. %file will be replaced by a file name after prompting
12096 for the file using completion. The cursor will be placed at the position
12097 of the `?` in the template.
12098 There are two templates for each key, the first uses the original Org syntax,
12099 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12100 the default when the /org-mtags.el/ module has been loaded. See also the
12101 variable `org-mtags-prefer-muse-templates'."
12102 :group 'org-completion
12103 :type '(repeat
12104 (list
12105 (string :tag "Key")
12106 (string :tag "Template")
12107 (string :tag "Muse Template"))))
12109 (defun org-try-structure-completion ()
12110 "Try to complete a structure template before point.
12111 This looks for strings like \"<e\" on an otherwise empty line and
12112 expands them."
12113 (let ((l (buffer-substring (point-at-bol) (point)))
12115 (when (and (looking-at "[ \t]*$")
12116 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12117 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12118 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12119 (match-beginning 1)) a)
12120 t)))
12122 (defun org-complete-expand-structure-template (start cell)
12123 "Expand a structure template."
12124 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
12125 (rpl (nth (if musep 2 1) cell))
12126 (ind ""))
12127 (delete-region start (point))
12128 (when (string-match "\\`#\\+" rpl)
12129 (cond
12130 ((bolp))
12131 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12132 (setq ind (buffer-substring (point-at-bol) (point))))
12133 (t (newline))))
12134 (setq start (point))
12135 (if (string-match "%file" rpl)
12136 (setq rpl (replace-match
12137 (concat
12138 "\""
12139 (save-match-data
12140 (abbreviate-file-name (read-file-name "Include file: ")))
12141 "\"")
12142 t t rpl)))
12143 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12144 (concat "\n" ind)))
12145 (insert rpl)
12146 (if (re-search-backward "\\?" start t) (delete-char 1))))
12148 ;;;; TODO, DEADLINE, Comments
12150 (defun org-toggle-comment ()
12151 "Change the COMMENT state of an entry."
12152 (interactive)
12153 (save-excursion
12154 (org-back-to-heading)
12155 (let (case-fold-search)
12156 (cond
12157 ((looking-at (format org-heading-keyword-regexp-format
12158 org-comment-string))
12159 (goto-char (match-end 1))
12160 (looking-at (concat " +" org-comment-string))
12161 (replace-match "" t t)
12162 (when (eolp) (insert " ")))
12163 ((looking-at org-outline-regexp)
12164 (goto-char (match-end 0))
12165 (insert org-comment-string " "))))))
12167 (defvar org-last-todo-state-is-todo nil
12168 "This is non-nil when the last TODO state change led to a TODO state.
12169 If the last change removed the TODO tag or switched to DONE, then
12170 this is nil.")
12172 (defvar org-setting-tags nil) ; dynamically skipped
12174 (defvar org-todo-setup-filter-hook nil
12175 "Hook for functions that pre-filter todo specs.
12176 Each function takes a todo spec and returns either nil or the spec
12177 transformed into canonical form." )
12179 (defvar org-todo-get-default-hook nil
12180 "Hook for functions that get a default item for todo.
12181 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12182 nil or a string to be used for the todo mark." )
12184 (defvar org-agenda-headline-snapshot-before-repeat)
12186 (defun org-current-effective-time ()
12187 "Return current time adjusted for `org-extend-today-until' variable."
12188 (let* ((ct (org-current-time))
12189 (dct (decode-time ct))
12190 (ct1
12191 (cond
12192 (org-use-last-clock-out-time-as-effective-time
12193 (or (org-clock-get-last-clock-out-time) ct))
12194 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12195 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12196 (t ct))))
12197 ct1))
12199 (defun org-todo-yesterday (&optional arg)
12200 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12201 (interactive "P")
12202 (if (eq major-mode 'org-agenda-mode)
12203 (apply 'org-agenda-todo-yesterday arg)
12204 (let* ((hour (third (decode-time
12205 (org-current-time))))
12206 (org-extend-today-until (1+ hour)))
12207 (org-todo arg))))
12209 (defvar org-block-entry-blocking ""
12210 "First entry preventing the TODO state change.")
12212 (defun org-cancel-repeater ()
12213 "Cancel a repeater by setting its numeric value to zero."
12214 (interactive)
12215 (save-excursion
12216 (org-back-to-heading t)
12217 (let ((bound1 (point))
12218 (bound0 (save-excursion (outline-next-heading) (point))))
12219 (when (re-search-forward
12220 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12221 org-deadline-time-regexp "\\)\\|\\("
12222 org-ts-regexp "\\)")
12223 bound0 t)
12224 (if (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]" bound1 t)
12225 (replace-match "0" t nil nil 1))))))
12227 (defun org-todo (&optional arg)
12228 "Change the TODO state of an item.
12229 The state of an item is given by a keyword at the start of the heading,
12230 like
12231 *** TODO Write paper
12232 *** DONE Call mom
12234 The different keywords are specified in the variable `org-todo-keywords'.
12235 By default the available states are \"TODO\" and \"DONE\".
12236 So for this example: when the item starts with TODO, it is changed to DONE.
12237 When it starts with DONE, the DONE is removed. And when neither TODO nor
12238 DONE are present, add TODO at the beginning of the heading.
12240 With \\[universal-argument] prefix arg, use completion to determine the new \
12241 state.
12242 With numeric prefix arg, switch to that state.
12243 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12244 keywords (nextset).
12245 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12246 With a numeric prefix arg of 0, inhibit note taking for the change.
12247 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12249 When called through ELisp, arg is also interpreted in the following way:
12250 'none -> empty state
12251 \"\"(empty string) -> switch to empty state
12252 'done -> switch to DONE
12253 'nextset -> switch to the next set of keywords
12254 'previousset -> switch to the previous set of keywords
12255 \"WAITING\" -> switch to the specified keyword, but only if it
12256 really is a member of `org-todo-keywords'."
12257 (interactive "P")
12258 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12259 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12260 'region-start-level 'region))
12261 org-loop-over-headlines-in-active-region)
12262 (org-map-entries
12263 `(org-todo ,arg)
12264 org-loop-over-headlines-in-active-region
12265 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12266 (if (equal arg '(16)) (setq arg 'nextset))
12267 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12268 (let ((org-blocker-hook org-blocker-hook)
12269 commentp
12270 case-fold-search)
12271 (when (equal arg '(64))
12272 (setq arg nil org-blocker-hook nil))
12273 (when (and org-blocker-hook
12274 (or org-inhibit-blocking
12275 (org-entry-get nil "NOBLOCKING")))
12276 (setq org-blocker-hook nil))
12277 (save-excursion
12278 (catch 'exit
12279 (org-back-to-heading t)
12280 (when (looking-at (concat "^\\*+ " org-comment-string))
12281 (org-toggle-comment)
12282 (setq commentp t))
12283 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12284 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12285 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12286 (let* ((match-data (match-data))
12287 (startpos (point-at-bol))
12288 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12289 (org-log-done org-log-done)
12290 (org-log-repeat org-log-repeat)
12291 (org-todo-log-states org-todo-log-states)
12292 (org-inhibit-logging
12293 (if (equal arg 0)
12294 (progn (setq arg nil) 'note) org-inhibit-logging))
12295 (this (match-string 1))
12296 (hl-pos (match-beginning 0))
12297 (head (org-get-todo-sequence-head this))
12298 (ass (assoc head org-todo-kwd-alist))
12299 (interpret (nth 1 ass))
12300 (done-word (nth 3 ass))
12301 (final-done-word (nth 4 ass))
12302 (org-last-state (or this ""))
12303 (completion-ignore-case t)
12304 (member (member this org-todo-keywords-1))
12305 (tail (cdr member))
12306 (org-state (cond
12307 ((and org-todo-key-trigger
12308 (or (and (equal arg '(4))
12309 (eq org-use-fast-todo-selection 'prefix))
12310 (and (not arg) org-use-fast-todo-selection
12311 (not (eq org-use-fast-todo-selection
12312 'prefix)))))
12313 ;; Use fast selection
12314 (org-fast-todo-selection))
12315 ((and (equal arg '(4))
12316 (or (not org-use-fast-todo-selection)
12317 (not org-todo-key-trigger)))
12318 ;; Read a state with completion
12319 (org-icompleting-read
12320 "State: " (mapcar 'list org-todo-keywords-1)
12321 nil t))
12322 ((eq arg 'right)
12323 (if this
12324 (if tail (car tail) nil)
12325 (car org-todo-keywords-1)))
12326 ((eq arg 'left)
12327 (if (equal member org-todo-keywords-1)
12329 (if this
12330 (nth (- (length org-todo-keywords-1)
12331 (length tail) 2)
12332 org-todo-keywords-1)
12333 (org-last org-todo-keywords-1))))
12334 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12335 (setq arg nil))) ; hack to fall back to cycling
12336 (arg
12337 ;; user or caller requests a specific state
12338 (cond
12339 ((equal arg "") nil)
12340 ((eq arg 'none) nil)
12341 ((eq arg 'done) (or done-word (car org-done-keywords)))
12342 ((eq arg 'nextset)
12343 (or (car (cdr (member head org-todo-heads)))
12344 (car org-todo-heads)))
12345 ((eq arg 'previousset)
12346 (let ((org-todo-heads (reverse org-todo-heads)))
12347 (or (car (cdr (member head org-todo-heads)))
12348 (car org-todo-heads))))
12349 ((car (member arg org-todo-keywords-1)))
12350 ((stringp arg)
12351 (user-error "State `%s' not valid in this file" arg))
12352 ((nth (1- (prefix-numeric-value arg))
12353 org-todo-keywords-1))))
12354 ((null member) (or head (car org-todo-keywords-1)))
12355 ((equal this final-done-word) nil) ;; -> make empty
12356 ((null tail) nil) ;; -> first entry
12357 ((memq interpret '(type priority))
12358 (if (eq this-command last-command)
12359 (car tail)
12360 (if (> (length tail) 0)
12361 (or done-word (car org-done-keywords))
12362 nil)))
12364 (car tail))))
12365 (org-state (or
12366 (run-hook-with-args-until-success
12367 'org-todo-get-default-hook org-state org-last-state)
12368 org-state))
12369 (next (if org-state (concat " " org-state " ") " "))
12370 (change-plist (list :type 'todo-state-change :from this :to org-state
12371 :position startpos))
12372 dolog now-done-p)
12373 (when org-blocker-hook
12374 (setq org-last-todo-state-is-todo
12375 (not (member this org-done-keywords)))
12376 (unless (save-excursion
12377 (save-match-data
12378 (org-with-wide-buffer
12379 (run-hook-with-args-until-failure
12380 'org-blocker-hook change-plist))))
12381 (if (org-called-interactively-p 'interactive)
12382 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12383 this org-state org-block-entry-blocking)
12384 ;; fail silently
12385 (message "TODO state change from %s to %s blocked (by \"%s\")"
12386 this org-state org-block-entry-blocking)
12387 (throw 'exit nil))))
12388 (store-match-data match-data)
12389 (replace-match next t t)
12390 (unless (pos-visible-in-window-p hl-pos)
12391 (message "TODO state changed to %s" (org-trim next)))
12392 (unless head
12393 (setq head (org-get-todo-sequence-head org-state)
12394 ass (assoc head org-todo-kwd-alist)
12395 interpret (nth 1 ass)
12396 done-word (nth 3 ass)
12397 final-done-word (nth 4 ass)))
12398 (when (memq arg '(nextset previousset))
12399 (message "Keyword-Set %d/%d: %s"
12400 (- (length org-todo-sets) -1
12401 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12402 (length org-todo-sets)
12403 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12404 (setq org-last-todo-state-is-todo
12405 (not (member org-state org-done-keywords)))
12406 (setq now-done-p (and (member org-state org-done-keywords)
12407 (not (member this org-done-keywords))))
12408 (and logging (org-local-logging logging))
12409 (when (and (or org-todo-log-states org-log-done)
12410 (not (eq org-inhibit-logging t))
12411 (not (memq arg '(nextset previousset))))
12412 ;; we need to look at recording a time and note
12413 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12414 (nth 2 (assoc this org-todo-log-states))))
12415 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12416 (setq dolog 'time))
12417 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12418 (and org-state
12419 (member org-state org-not-done-keywords)
12420 (not (member this org-not-done-keywords))))
12421 ;; This is now a todo state and was not one before
12422 ;; If there was a CLOSED time stamp, get rid of it.
12423 (org-add-planning-info nil nil 'closed))
12424 (when (and now-done-p org-log-done)
12425 ;; It is now done, and it was not done before
12426 (org-add-planning-info 'closed (org-current-effective-time))
12427 (if (and (not dolog) (eq 'note org-log-done))
12428 (org-add-log-setup 'done org-state this 'findpos 'note)))
12429 (when (and org-state dolog)
12430 ;; This is a non-nil state, and we need to log it
12431 (org-add-log-setup 'state org-state this 'findpos dolog)))
12432 ;; Fixup tag positioning
12433 (org-todo-trigger-tag-changes org-state)
12434 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12435 (when org-provide-todo-statistics
12436 (org-update-parent-todo-statistics))
12437 (run-hooks 'org-after-todo-state-change-hook)
12438 (if (and arg (not (member org-state org-done-keywords)))
12439 (setq head (org-get-todo-sequence-head org-state)))
12440 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12441 ;; Do we need to trigger a repeat?
12442 (when now-done-p
12443 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12444 ;; This is for the agenda, take a snapshot of the headline.
12445 (save-match-data
12446 (setq org-agenda-headline-snapshot-before-repeat
12447 (org-get-heading))))
12448 (org-auto-repeat-maybe org-state))
12449 ;; Fixup cursor location if close to the keyword
12450 (if (and (outline-on-heading-p)
12451 (not (bolp))
12452 (save-excursion (beginning-of-line 1)
12453 (looking-at org-todo-line-regexp))
12454 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12455 (progn
12456 (goto-char (or (match-end 2) (match-end 1)))
12457 (and (looking-at " ") (just-one-space))))
12458 (when org-trigger-hook
12459 (save-excursion
12460 (run-hook-with-args 'org-trigger-hook change-plist)))
12461 (when commentp (org-toggle-comment))))))))
12463 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12464 "Block turning an entry into a TODO, using the hierarchy.
12465 This checks whether the current task should be blocked from state
12466 changes. Such blocking occurs when:
12468 1. The task has children which are not all in a completed state.
12470 2. A task has a parent with the property :ORDERED:, and there
12471 are siblings prior to the current task with incomplete
12472 status.
12474 3. The parent of the task is blocked because it has siblings that should
12475 be done first, or is child of a block grandparent TODO entry."
12477 (if (not org-enforce-todo-dependencies)
12478 t ; if locally turned off don't block
12479 (catch 'dont-block
12480 ;; If this is not a todo state change, or if this entry is already DONE,
12481 ;; do not block
12482 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12483 (member (plist-get change-plist :from)
12484 (cons 'done org-done-keywords))
12485 (member (plist-get change-plist :to)
12486 (cons 'todo org-not-done-keywords))
12487 (not (plist-get change-plist :to)))
12488 (throw 'dont-block t))
12489 ;; If this task has children, and any are undone, it's blocked
12490 (save-excursion
12491 (org-back-to-heading t)
12492 (let ((this-level (funcall outline-level)))
12493 (outline-next-heading)
12494 (let ((child-level (funcall outline-level)))
12495 (while (and (not (eobp))
12496 (> child-level this-level))
12497 ;; this todo has children, check whether they are all
12498 ;; completed
12499 (if (and (not (org-entry-is-done-p))
12500 (org-entry-is-todo-p))
12501 (progn (setq org-block-entry-blocking (org-get-heading))
12502 (throw 'dont-block nil)))
12503 (outline-next-heading)
12504 (setq child-level (funcall outline-level))))))
12505 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12506 ;; any previous siblings are undone, it's blocked
12507 (save-excursion
12508 (org-back-to-heading t)
12509 (let* ((pos (point))
12510 (parent-pos (and (org-up-heading-safe) (point))))
12511 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12512 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12513 (forward-line 1)
12514 (re-search-forward org-not-done-heading-regexp pos t))
12515 (setq org-block-entry-blocking (match-string 0))
12516 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12517 ;; Search further up the hierarchy, to see if an ancestor is blocked
12518 (while t
12519 (goto-char parent-pos)
12520 (if (not (looking-at org-not-done-heading-regexp))
12521 (throw 'dont-block t)) ; do not block, parent is not a TODO
12522 (setq pos (point))
12523 (setq parent-pos (and (org-up-heading-safe) (point)))
12524 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12525 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12526 (forward-line 1)
12527 (re-search-forward org-not-done-heading-regexp pos t)
12528 (setq org-block-entry-blocking (org-get-heading)))
12529 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12531 (defcustom org-track-ordered-property-with-tag nil
12532 "Should the ORDERED property also be shown as a tag?
12533 The ORDERED property decides if an entry should require subtasks to be
12534 completed in sequence. Since a property is not very visible, setting
12535 this option means that toggling the ORDERED property with the command
12536 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12537 not relevant for the behavior, but it makes things more visible.
12539 Note that toggling the tag with tags commands will not change the property
12540 and therefore not influence behavior!
12542 This can be t, meaning the tag ORDERED should be used, It can also be a
12543 string to select a different tag for this task."
12544 :group 'org-todo
12545 :type '(choice
12546 (const :tag "No tracking" nil)
12547 (const :tag "Track with ORDERED tag" t)
12548 (string :tag "Use other tag")))
12550 (defun org-toggle-ordered-property ()
12551 "Toggle the ORDERED property of the current entry.
12552 For better visibility, you can track the value of this property with a tag.
12553 See variable `org-track-ordered-property-with-tag'."
12554 (interactive)
12555 (let* ((t1 org-track-ordered-property-with-tag)
12556 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12557 (save-excursion
12558 (org-back-to-heading)
12559 (if (org-entry-get nil "ORDERED")
12560 (progn
12561 (org-delete-property "ORDERED")
12562 (and tag (org-toggle-tag tag 'off))
12563 (message "Subtasks can be completed in arbitrary order"))
12564 (org-entry-put nil "ORDERED" "t")
12565 (and tag (org-toggle-tag tag 'on))
12566 (message "Subtasks must be completed in sequence")))))
12568 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12569 (defun org-block-todo-from-checkboxes (change-plist)
12570 "Block turning an entry into a TODO, using checkboxes.
12571 This checks whether the current task should be blocked from state
12572 changes because there are unchecked boxes in this entry."
12573 (if (not org-enforce-todo-checkbox-dependencies)
12574 t ; if locally turned off don't block
12575 (catch 'dont-block
12576 ;; If this is not a todo state change, or if this entry is already DONE,
12577 ;; do not block
12578 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12579 (member (plist-get change-plist :from)
12580 (cons 'done org-done-keywords))
12581 (member (plist-get change-plist :to)
12582 (cons 'todo org-not-done-keywords))
12583 (not (plist-get change-plist :to)))
12584 (throw 'dont-block t))
12585 ;; If this task has checkboxes that are not checked, it's blocked
12586 (save-excursion
12587 (org-back-to-heading t)
12588 (let ((beg (point)) end)
12589 (outline-next-heading)
12590 (setq end (point))
12591 (goto-char beg)
12592 (if (org-list-search-forward
12593 (concat (org-item-beginning-re)
12594 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12595 "\\[[- ]\\]")
12596 end t)
12597 (progn
12598 (if (boundp 'org-blocked-by-checkboxes)
12599 (setq org-blocked-by-checkboxes t))
12600 (throw 'dont-block nil)))))
12601 t))) ; do not block
12603 (defun org-entry-blocked-p ()
12604 "Is the current entry blocked?"
12605 (org-with-silent-modifications
12606 (if (org-entry-get nil "NOBLOCKING")
12607 nil ;; Never block this entry
12608 (not (run-hook-with-args-until-failure
12609 'org-blocker-hook
12610 (list :type 'todo-state-change
12611 :position (point)
12612 :from 'todo
12613 :to 'done))))))
12615 (defun org-update-statistics-cookies (all)
12616 "Update the statistics cookie, either from TODO or from checkboxes.
12617 This should be called with the cursor in a line with a statistics cookie."
12618 (interactive "P")
12619 (if all
12620 (progn
12621 (org-update-checkbox-count 'all)
12622 (org-map-entries 'org-update-parent-todo-statistics))
12623 (if (not (org-at-heading-p))
12624 (org-update-checkbox-count)
12625 (let ((pos (point-marker))
12626 end l1 l2)
12627 (ignore-errors (org-back-to-heading t))
12628 (if (not (org-at-heading-p))
12629 (org-update-checkbox-count)
12630 (setq l1 (org-outline-level))
12631 (setq end (save-excursion
12632 (outline-next-heading)
12633 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12634 (point)))
12635 (if (and (save-excursion
12636 (re-search-forward
12637 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12638 (not (save-excursion (re-search-forward
12639 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12640 (org-update-checkbox-count)
12641 (if (and l2 (> l2 l1))
12642 (progn
12643 (goto-char end)
12644 (org-update-parent-todo-statistics))
12645 (goto-char pos)
12646 (beginning-of-line 1)
12647 (while (re-search-forward
12648 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12649 (point-at-eol) t)
12650 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12651 (goto-char pos)
12652 (move-marker pos nil)))))
12654 (defvar org-entry-property-inherited-from) ;; defined below
12655 (defun org-update-parent-todo-statistics ()
12656 "Update any statistics cookie in the parent of the current headline.
12657 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12658 the entire subtree and this will travel up the hierarchy and update
12659 statistics everywhere."
12660 (let* ((prop (save-excursion (org-up-heading-safe)
12661 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12662 (recursive (or (not org-hierarchical-todo-statistics)
12663 (and prop (string-match "\\<recursive\\>" prop))))
12664 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12666 (first t)
12667 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12668 level ltoggle l1 new ndel
12669 (cnt-all 0) (cnt-done 0) is-percent kwd
12670 checkbox-beg ov ovs ove cookie-present)
12671 (catch 'exit
12672 (save-excursion
12673 (beginning-of-line 1)
12674 (setq ltoggle (funcall outline-level))
12675 ;; Three situations are to consider:
12677 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12678 ;; to the top-level ancestor on the headline;
12680 ;; 2. If parent has "recursive" property, repeat up to the
12681 ;; headline setting that property, taking inheritance into
12682 ;; account;
12684 ;; 3. Else, move up to direct parent and proceed only once.
12685 (while (and (setq level (org-up-heading-safe))
12686 (or recursive first)
12687 (>= (point) lim))
12688 (setq first nil cookie-present nil)
12689 (unless (and level
12690 (not (string-match
12691 "\\<checkbox\\>"
12692 (downcase (or (org-entry-get nil "COOKIE_DATA")
12693 "")))))
12694 (throw 'exit nil))
12695 (while (re-search-forward box-re (point-at-eol) t)
12696 (setq cnt-all 0 cnt-done 0 cookie-present t)
12697 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12698 (save-match-data
12699 (unless (outline-next-heading) (throw 'exit nil))
12700 (while (and (looking-at org-complex-heading-regexp)
12701 (> (setq l1 (length (match-string 1))) level))
12702 (setq kwd (and (or recursive (= l1 ltoggle))
12703 (match-string 2)))
12704 (if (or (eq org-provide-todo-statistics 'all-headlines)
12705 (and (listp org-provide-todo-statistics)
12706 (or (member kwd org-provide-todo-statistics)
12707 (member kwd org-done-keywords))))
12708 (setq cnt-all (1+ cnt-all))
12709 (if (eq org-provide-todo-statistics t)
12710 (and kwd (setq cnt-all (1+ cnt-all)))))
12711 (and (member kwd org-done-keywords)
12712 (setq cnt-done (1+ cnt-done)))
12713 (outline-next-heading)))
12714 (setq new
12715 (if is-percent
12716 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12717 (format "[%d/%d]" cnt-done cnt-all))
12718 ndel (- (match-end 0) checkbox-beg))
12719 ;; handle overlays when updating cookie from column view
12720 (when (setq ov (car (overlays-at checkbox-beg)))
12721 (setq ovs (overlay-start ov) ove (overlay-end ov))
12722 (delete-overlay ov))
12723 (goto-char checkbox-beg)
12724 (insert new)
12725 (delete-region (point) (+ (point) ndel))
12726 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12727 (when ov (move-overlay ov ovs ove)))
12728 (when cookie-present
12729 (run-hook-with-args 'org-after-todo-statistics-hook
12730 cnt-done (- cnt-all cnt-done))))))
12731 (run-hooks 'org-todo-statistics-hook)))
12733 (defvar org-after-todo-statistics-hook nil
12734 "Hook that is called after a TODO statistics cookie has been updated.
12735 Each function is called with two arguments: the number of not-done entries
12736 and the number of done entries.
12738 For example, the following function, when added to this hook, will switch
12739 an entry to DONE when all children are done, and back to TODO when new
12740 entries are set to a TODO status. Note that this hook is only called
12741 when there is a statistics cookie in the headline!
12743 (defun org-summary-todo (n-done n-not-done)
12744 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12745 (let (org-log-done org-log-states) ; turn off logging
12746 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12749 (defvar org-todo-statistics-hook nil
12750 "Hook that is run whenever Org thinks TODO statistics should be updated.
12751 This hook runs even if there is no statistics cookie present, in which case
12752 `org-after-todo-statistics-hook' would not run.")
12754 (defun org-todo-trigger-tag-changes (state)
12755 "Apply the changes defined in `org-todo-state-tags-triggers'."
12756 (let ((l org-todo-state-tags-triggers)
12757 changes)
12758 (when (or (not state) (equal state ""))
12759 (setq changes (append changes (cdr (assoc "" l)))))
12760 (when (and (stringp state) (> (length state) 0))
12761 (setq changes (append changes (cdr (assoc state l)))))
12762 (when (member state org-not-done-keywords)
12763 (setq changes (append changes (cdr (assoc 'todo l)))))
12764 (when (member state org-done-keywords)
12765 (setq changes (append changes (cdr (assoc 'done l)))))
12766 (dolist (c changes)
12767 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12769 (defun org-local-logging (value)
12770 "Get logging settings from a property VALUE."
12771 (let* (words w a)
12772 ;; directly set the variables, they are already local.
12773 (setq org-log-done nil
12774 org-log-repeat nil
12775 org-todo-log-states nil)
12776 (setq words (org-split-string value))
12777 (while (setq w (pop words))
12778 (cond
12779 ((setq a (assoc w org-startup-options))
12780 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12781 (set (nth 1 a) (nth 2 a))))
12782 ((setq a (org-extract-log-state-settings w))
12783 (and (member (car a) org-todo-keywords-1)
12784 (push a org-todo-log-states)))))))
12786 (defun org-get-todo-sequence-head (kwd)
12787 "Return the head of the TODO sequence to which KWD belongs.
12788 If KWD is not set, check if there is a text property remembering the
12789 right sequence."
12790 (let (p)
12791 (cond
12792 ((not kwd)
12793 (or (get-text-property (point-at-bol) 'org-todo-head)
12794 (progn
12795 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12796 nil (point-at-eol)))
12797 (get-text-property p 'org-todo-head))))
12798 ((not (member kwd org-todo-keywords-1))
12799 (car org-todo-keywords-1))
12800 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12802 (defun org-fast-todo-selection ()
12803 "Fast TODO keyword selection with single keys.
12804 Returns the new TODO keyword, or nil if no state change should occur."
12805 (let* ((fulltable org-todo-key-alist)
12806 (done-keywords org-done-keywords) ;; needed for the faces.
12807 (maxlen (apply 'max (mapcar
12808 (lambda (x)
12809 (if (stringp (car x)) (string-width (car x)) 0))
12810 fulltable)))
12811 (expert nil)
12812 (fwidth (+ maxlen 3 1 3))
12813 (ncol (/ (- (window-width) 4) fwidth))
12814 tg cnt e c tbl
12815 groups ingroup)
12816 (save-excursion
12817 (save-window-excursion
12818 (if expert
12819 (set-buffer (get-buffer-create " *Org todo*"))
12820 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12821 (erase-buffer)
12822 (org-set-local 'org-done-keywords done-keywords)
12823 (setq tbl fulltable cnt 0)
12824 (while (setq e (pop tbl))
12825 (cond
12826 ((equal e '(:startgroup))
12827 (push '() groups) (setq ingroup t)
12828 (when (not (= cnt 0))
12829 (setq cnt 0)
12830 (insert "\n"))
12831 (insert "{ "))
12832 ((equal e '(:endgroup))
12833 (setq ingroup nil cnt 0)
12834 (insert "}\n"))
12835 ((equal e '(:newline))
12836 (when (not (= cnt 0))
12837 (setq cnt 0)
12838 (insert "\n")
12839 (setq e (car tbl))
12840 (while (equal (car tbl) '(:newline))
12841 (insert "\n")
12842 (setq tbl (cdr tbl)))))
12844 (setq tg (car e) c (cdr e))
12845 (if ingroup (push tg (car groups)))
12846 (setq tg (org-add-props tg nil 'face
12847 (org-get-todo-face tg)))
12848 (if (and (= cnt 0) (not ingroup)) (insert " "))
12849 (insert "[" c "] " tg (make-string
12850 (- fwidth 4 (length tg)) ?\ ))
12851 (when (= (setq cnt (1+ cnt)) ncol)
12852 (insert "\n")
12853 (if ingroup (insert " "))
12854 (setq cnt 0)))))
12855 (insert "\n")
12856 (goto-char (point-min))
12857 (if (not expert) (org-fit-window-to-buffer))
12858 (message "[a-z..]:Set [SPC]:clear")
12859 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12860 (cond
12861 ((or (= c ?\C-g)
12862 (and (= c ?q) (not (rassoc c fulltable))))
12863 (setq quit-flag t))
12864 ((= c ?\ ) nil)
12865 ((setq e (rassoc c fulltable) tg (car e))
12867 (t (setq quit-flag t)))))))
12869 (defun org-entry-is-todo-p ()
12870 (member (org-get-todo-state) org-not-done-keywords))
12872 (defun org-entry-is-done-p ()
12873 (member (org-get-todo-state) org-done-keywords))
12875 (defun org-get-todo-state ()
12876 "Return the TODO keyword of the current subtree."
12877 (save-excursion
12878 (org-back-to-heading t)
12879 (and (looking-at org-todo-line-regexp)
12880 (match-end 2)
12881 (match-string 2))))
12883 (defun org-at-date-range-p (&optional inactive-ok)
12884 "Is the cursor inside a date range?"
12885 (interactive)
12886 (save-excursion
12887 (catch 'exit
12888 (let ((pos (point)))
12889 (skip-chars-backward "^[<\r\n")
12890 (skip-chars-backward "<[")
12891 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12892 (>= (match-end 0) pos)
12893 (throw 'exit t))
12894 (skip-chars-backward "^<[\r\n")
12895 (skip-chars-backward "<[")
12896 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12897 (>= (match-end 0) pos)
12898 (throw 'exit t)))
12899 nil)))
12901 (defun org-get-repeat (&optional tagline)
12902 "Check if there is a deadline/schedule with repeater in this entry."
12903 (save-match-data
12904 (save-excursion
12905 (org-back-to-heading t)
12906 (and (re-search-forward (if tagline
12907 (concat tagline "\\s-*" org-repeat-re)
12908 org-repeat-re)
12909 (org-entry-end-position) t)
12910 (match-string-no-properties 1)))))
12912 (defvar org-last-changed-timestamp)
12913 (defvar org-last-inserted-timestamp)
12914 (defvar org-log-post-message)
12915 (defvar org-log-note-purpose)
12916 (defvar org-log-note-how)
12917 (defvar org-log-note-extra)
12918 (defun org-auto-repeat-maybe (done-word)
12919 "Check if the current headline contains a repeated deadline/schedule.
12920 If yes, set TODO state back to what it was and change the base date
12921 of repeating deadline/scheduled time stamps to new date.
12922 This function is run automatically after each state change to a DONE state."
12923 ;; last-state is dynamically scoped into this function
12924 (let* ((repeat (org-get-repeat))
12925 (aa (assoc org-last-state org-todo-kwd-alist))
12926 (interpret (nth 1 aa))
12927 (head (nth 2 aa))
12928 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12929 (msg "Entry repeats: ")
12930 (org-log-done nil)
12931 (org-todo-log-states nil)
12932 re type n what ts time to-state)
12933 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
12934 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12935 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12936 org-todo-repeat-to-state))
12937 (unless (and to-state (member to-state org-todo-keywords-1))
12938 (setq to-state (if (eq interpret 'type) org-last-state head)))
12939 (org-todo to-state)
12940 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12941 (org-entry-put nil "LAST_REPEAT" (format-time-string
12942 (org-time-stamp-format t t))))
12943 (when org-log-repeat
12944 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12945 (memq 'org-add-log-note post-command-hook))
12946 ;; OK, we are already setup for some record
12947 (if (eq org-log-repeat 'note)
12948 ;; make sure we take a note, not only a time stamp
12949 (setq org-log-note-how 'note))
12950 ;; Set up for taking a record
12951 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12952 org-last-state
12953 'findpos org-log-repeat)))
12954 (org-back-to-heading t)
12955 (org-add-planning-info nil nil 'closed)
12956 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12957 org-deadline-time-regexp "\\)\\|\\("
12958 org-ts-regexp "\\)"))
12959 (while (re-search-forward
12960 re (save-excursion (outline-next-heading) (point)) t)
12961 (setq type (if (match-end 1) org-scheduled-string
12962 (if (match-end 3) org-deadline-string "Plain:"))
12963 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12964 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12965 (setq n (string-to-number (match-string 2 ts))
12966 what (match-string 3 ts))
12967 (if (equal what "w") (setq n (* n 7) what "d"))
12968 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12969 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12970 ;; Preparation, see if we need to modify the start date for the change
12971 (when (match-end 1)
12972 (setq time (save-match-data (org-time-string-to-time ts)))
12973 (cond
12974 ((equal (match-string 1 ts) ".")
12975 ;; Shift starting date to today
12976 (org-timestamp-change
12977 (- (org-today) (time-to-days time))
12978 'day))
12979 ((equal (match-string 1 ts) "+")
12980 (let ((nshiftmax 10) (nshift 0))
12981 (while (or (= nshift 0)
12982 (<= (time-to-days time)
12983 (time-to-days (current-time))))
12984 (when (= (incf nshift) nshiftmax)
12985 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12986 (error "Abort")))
12987 (org-timestamp-change n (cdr (assoc what whata)))
12988 (org-at-timestamp-p t)
12989 (setq ts (match-string 1))
12990 (setq time (save-match-data (org-time-string-to-time ts)))))
12991 (org-timestamp-change (- n) (cdr (assoc what whata)))
12992 ;; rematch, so that we have everything in place for the real shift
12993 (org-at-timestamp-p t)
12994 (setq ts (match-string 1))
12995 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12996 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12997 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12998 (setq org-log-post-message msg)
12999 (message "%s" msg))))
13001 (defun org-show-todo-tree (arg)
13002 "Make a compact tree which shows all headlines marked with TODO.
13003 The tree will show the lines where the regexp matches, and all higher
13004 headlines above the match.
13005 With a \\[universal-argument] prefix, prompt for a regexp to match.
13006 With a numeric prefix N, construct a sparse tree for the Nth element
13007 of `org-todo-keywords-1'."
13008 (interactive "P")
13009 (let ((case-fold-search nil)
13010 (kwd-re
13011 (cond ((null arg) org-not-done-regexp)
13012 ((equal arg '(4))
13013 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
13014 (mapcar 'list org-todo-keywords-1))))
13015 (concat "\\("
13016 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13017 "\\)\\>")))
13018 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13019 (regexp-quote (nth (1- (prefix-numeric-value arg))
13020 org-todo-keywords-1)))
13021 (t (user-error "Invalid prefix argument: %s" arg)))))
13022 (message "%d TODO entries found"
13023 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13025 (defun org-deadline (arg &optional time)
13026 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13027 With one universal prefix argument, remove any deadline from the item.
13028 With two universal prefix arguments, prompt for a warning delay.
13029 With argument TIME, set the deadline at the corresponding date. TIME
13030 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13031 (interactive "P")
13032 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13033 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13034 'region-start-level 'region))
13035 org-loop-over-headlines-in-active-region)
13036 (org-map-entries
13037 `(org-deadline ',arg ,time)
13038 org-loop-over-headlines-in-active-region
13039 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13040 (let* ((old-date (org-entry-get nil "DEADLINE"))
13041 (old-date-time (if old-date (org-time-string-to-time old-date)))
13042 (repeater (and old-date
13043 (string-match
13044 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13045 old-date)
13046 (match-string 1 old-date))))
13047 (cond
13048 ((equal arg '(4))
13049 (when (and old-date org-log-redeadline)
13050 (org-add-log-setup 'deldeadline nil old-date 'findpos
13051 org-log-redeadline))
13052 (org-remove-timestamp-with-keyword org-deadline-string)
13053 (message "Item no longer has a deadline."))
13054 ((equal arg '(16))
13055 (save-excursion
13056 (org-back-to-heading t)
13057 (if (re-search-forward
13058 org-deadline-time-regexp
13059 (save-excursion (outline-next-heading) (point)) t)
13060 (let* ((rpl0 (match-string 1))
13061 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13062 (replace-match
13063 (concat org-deadline-string
13064 " <" rpl
13065 (format " -%dd"
13066 (abs
13067 (- (time-to-days
13068 (save-match-data
13069 (org-read-date nil t nil "Warn starting from" old-date-time)))
13070 (time-to-days old-date-time))))
13071 ">") t t))
13072 (user-error "No deadline information to update"))))
13074 (org-add-planning-info 'deadline time 'closed)
13075 (when (and old-date org-log-redeadline
13076 (not (equal old-date
13077 (substring org-last-inserted-timestamp 1 -1))))
13078 (org-add-log-setup 'redeadline nil old-date 'findpos
13079 org-log-redeadline))
13080 (when repeater
13081 (save-excursion
13082 (org-back-to-heading t)
13083 (when (re-search-forward (concat org-deadline-string " "
13084 org-last-inserted-timestamp)
13085 (save-excursion
13086 (outline-next-heading) (point)) t)
13087 (goto-char (1- (match-end 0)))
13088 (insert " " repeater)
13089 (setq org-last-inserted-timestamp
13090 (concat (substring org-last-inserted-timestamp 0 -1)
13091 " " repeater
13092 (substring org-last-inserted-timestamp -1))))))
13093 (message "Deadline on %s" org-last-inserted-timestamp))))))
13095 (defun org-schedule (arg &optional time)
13096 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13097 With one universal prefix argument, remove any scheduling date from the item.
13098 With two universal prefix arguments, prompt for a delay cookie.
13099 With argument TIME, scheduled at the corresponding date. TIME can
13100 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13101 (interactive "P")
13102 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13103 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13104 'region-start-level 'region))
13105 org-loop-over-headlines-in-active-region)
13106 (org-map-entries
13107 `(org-schedule ',arg ,time)
13108 org-loop-over-headlines-in-active-region
13109 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13110 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13111 (old-date-time (if old-date (org-time-string-to-time old-date)))
13112 (repeater (and old-date
13113 (string-match
13114 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13115 old-date)
13116 (match-string 1 old-date))))
13117 (cond
13118 ((equal arg '(4))
13119 (progn
13120 (when (and old-date org-log-reschedule)
13121 (org-add-log-setup 'delschedule nil old-date 'findpos
13122 org-log-reschedule))
13123 (org-remove-timestamp-with-keyword org-scheduled-string)
13124 (message "Item is no longer scheduled.")))
13125 ((equal arg '(16))
13126 (save-excursion
13127 (org-back-to-heading t)
13128 (if (re-search-forward
13129 org-scheduled-time-regexp
13130 (save-excursion (outline-next-heading) (point)) t)
13131 (let* ((rpl0 (match-string 1))
13132 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13133 (replace-match
13134 (concat org-scheduled-string
13135 " <" rpl
13136 (format " -%dd"
13137 (abs
13138 (- (time-to-days
13139 (save-match-data
13140 (org-read-date nil t nil "Delay until" old-date-time)))
13141 (time-to-days old-date-time))))
13142 ">") t t))
13143 (user-error "No scheduled information to update"))))
13145 (org-add-planning-info 'scheduled time 'closed)
13146 (when (and old-date org-log-reschedule
13147 (not (equal old-date
13148 (substring org-last-inserted-timestamp 1 -1))))
13149 (org-add-log-setup 'reschedule nil old-date 'findpos
13150 org-log-reschedule))
13151 (when repeater
13152 (save-excursion
13153 (org-back-to-heading t)
13154 (when (re-search-forward (concat org-scheduled-string " "
13155 org-last-inserted-timestamp)
13156 (save-excursion
13157 (outline-next-heading) (point)) t)
13158 (goto-char (1- (match-end 0)))
13159 (insert " " repeater)
13160 (setq org-last-inserted-timestamp
13161 (concat (substring org-last-inserted-timestamp 0 -1)
13162 " " repeater
13163 (substring org-last-inserted-timestamp -1))))))
13164 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13166 (defun org-get-scheduled-time (pom &optional inherit)
13167 "Get the scheduled time as a time tuple, of a format suitable
13168 for calling org-schedule with, or if there is no scheduling,
13169 returns nil."
13170 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13171 (when time
13172 (apply 'encode-time (org-parse-time-string time)))))
13174 (defun org-get-deadline-time (pom &optional inherit)
13175 "Get the deadline as a time tuple, of a format suitable for
13176 calling org-deadline with, or if there is no scheduling, returns
13177 nil."
13178 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13179 (when time
13180 (apply 'encode-time (org-parse-time-string time)))))
13182 (defun org-remove-timestamp-with-keyword (keyword)
13183 "Remove all time stamps with KEYWORD in the current entry."
13184 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13185 beg)
13186 (save-excursion
13187 (org-back-to-heading t)
13188 (setq beg (point))
13189 (outline-next-heading)
13190 (while (re-search-backward re beg t)
13191 (replace-match "")
13192 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13193 (equal (char-before) ?\ ))
13194 (backward-delete-char 1)
13195 (if (string-match "^[ \t]*$" (buffer-substring
13196 (point-at-bol) (point-at-eol)))
13197 (delete-region (point-at-bol)
13198 (min (point-max) (1+ (point-at-eol))))))))))
13200 (defvar org-time-was-given) ; dynamically scoped parameter
13201 (defvar org-end-time-was-given) ; dynamically scoped parameter
13203 (defun org-add-planning-info (what &optional time &rest remove)
13204 "Insert new timestamp with keyword in the line directly after the headline.
13205 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13206 If non is given, the user is prompted for a date.
13207 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13208 be removed."
13209 (interactive)
13210 (let (org-time-was-given org-end-time-was-given ts
13211 end default-time default-input)
13213 (catch 'exit
13214 (when (and (memq what '(scheduled deadline))
13215 (or (not time)
13216 (and (stringp time)
13217 (string-match "^[-+]+[0-9]" time))))
13218 ;; Try to get a default date/time from existing timestamp
13219 (save-excursion
13220 (org-back-to-heading t)
13221 (setq end (save-excursion (outline-next-heading) (point)))
13222 (when (re-search-forward (if (eq what 'scheduled)
13223 org-scheduled-time-regexp
13224 org-deadline-time-regexp)
13225 end t)
13226 (setq ts (match-string 1)
13227 default-time
13228 (apply 'encode-time (org-parse-time-string ts))
13229 default-input (and ts (org-get-compact-tod ts))))))
13230 (when what
13231 (setq time
13232 (if (stringp time)
13233 ;; This is a string (relative or absolute), set proper date
13234 (apply 'encode-time
13235 (org-read-date-analyze
13236 time default-time (decode-time default-time)))
13237 ;; If necessary, get the time from the user
13238 (or time (org-read-date nil 'to-time nil nil
13239 default-time default-input)))))
13241 (when (and org-insert-labeled-timestamps-at-point
13242 (member what '(scheduled deadline)))
13243 (insert
13244 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13245 (org-insert-time-stamp time org-time-was-given
13246 nil nil nil (list org-end-time-was-given))
13247 (setq what nil))
13248 (save-excursion
13249 (save-restriction
13250 (let (col list elt ts buffer-invisibility-spec)
13251 (org-back-to-heading t)
13252 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13253 (goto-char (match-end 1))
13254 (setq col (current-column))
13255 (goto-char (match-end 0))
13256 (if (eobp) (insert "\n") (forward-char 1))
13257 (when (and (not what)
13258 (not (looking-at
13259 (concat "[ \t]*"
13260 org-keyword-time-not-clock-regexp))))
13261 ;; Nothing to add, nothing to remove...... :-)
13262 (throw 'exit nil))
13263 (if (and (not (looking-at org-outline-regexp))
13264 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13265 "[^\r\n]*"))
13266 (not (equal (match-string 1) org-clock-string)))
13267 (narrow-to-region (match-beginning 0) (match-end 0))
13268 (insert-before-markers "\n")
13269 (backward-char 1)
13270 (narrow-to-region (point) (point))
13271 (and org-adapt-indentation (org-indent-to-column col)))
13272 ;; Check if we have to remove something.
13273 (setq list (cons what remove))
13274 (while list
13275 (setq elt (pop list))
13276 (when (or (and (eq elt 'scheduled)
13277 (re-search-forward org-scheduled-time-regexp nil t))
13278 (and (eq elt 'deadline)
13279 (re-search-forward org-deadline-time-regexp nil t))
13280 (and (eq elt 'closed)
13281 (re-search-forward org-closed-time-regexp nil t)))
13282 (replace-match "")
13283 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13284 (and (looking-at "[ \t]+") (replace-match ""))
13285 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13286 (when what
13287 (insert
13288 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13289 (cond ((eq what 'scheduled) org-scheduled-string)
13290 ((eq what 'deadline) org-deadline-string)
13291 ((eq what 'closed) org-closed-string))
13292 " ")
13293 (setq ts (org-insert-time-stamp
13294 time
13295 (or org-time-was-given
13296 (and (eq what 'closed) org-log-done-with-time))
13297 (eq what 'closed)
13298 nil nil (list org-end-time-was-given)))
13299 (insert
13300 (if (not (or (bolp) (eq (char-before) ?\ )
13301 (memq (char-after) '(32 10))
13302 (eobp))) " " ""))
13303 (end-of-line 1))
13304 (goto-char (point-min))
13305 (widen)
13306 (if (and (looking-at "[ \t]*\n")
13307 (equal (char-before) ?\n))
13308 (delete-region (1- (point)) (point-at-eol)))
13309 ts))))))
13311 (defvar org-log-note-marker (make-marker))
13312 (defvar org-log-note-purpose nil)
13313 (defvar org-log-note-state nil)
13314 (defvar org-log-note-previous-state nil)
13315 (defvar org-log-note-how nil)
13316 (defvar org-log-note-extra nil)
13317 (defvar org-log-note-window-configuration nil)
13318 (defvar org-log-note-return-to (make-marker))
13319 (defvar org-log-note-effective-time nil
13320 "Remembered current time so that dynamically scoped
13321 `org-extend-today-until' affects tha timestamps in state change
13322 log")
13324 (defvar org-log-post-message nil
13325 "Message to be displayed after a log note has been stored.
13326 The auto-repeater uses this.")
13328 (defun org-add-note ()
13329 "Add a note to the current entry.
13330 This is done in the same way as adding a state change note."
13331 (interactive)
13332 (org-add-log-setup 'note nil nil 'findpos nil))
13334 (defvar org-property-end-re)
13335 (defun org-add-log-setup (&optional purpose state prev-state
13336 findpos how extra)
13337 "Set up the post command hook to take a note.
13338 If this is about to TODO state change, the new state is expected in STATE.
13339 When FINDPOS is non-nil, find the correct position for the note in
13340 the current entry. If not, assume that it can be inserted at point.
13341 HOW is an indicator what kind of note should be created.
13342 EXTRA is additional text that will be inserted into the notes buffer."
13343 (let* ((org-log-into-drawer (org-log-into-drawer))
13344 (drawer (cond ((stringp org-log-into-drawer)
13345 org-log-into-drawer)
13346 (org-log-into-drawer "LOGBOOK"))))
13347 (save-restriction
13348 (save-excursion
13349 (when findpos
13350 (org-back-to-heading t)
13351 (narrow-to-region (point) (save-excursion
13352 (outline-next-heading) (point)))
13353 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13354 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13355 "[^\r\n]*\\)?"))
13356 (goto-char (match-end 0))
13357 (cond
13358 (drawer
13359 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13360 nil t)
13361 (progn
13362 (goto-char (match-end 0))
13363 (or org-log-states-order-reversed
13364 (and (re-search-forward org-property-end-re nil t)
13365 (goto-char (1- (match-beginning 0))))))
13366 (insert "\n:" drawer ":\n:END:")
13367 (beginning-of-line 0)
13368 (org-indent-line)
13369 (beginning-of-line 2)
13370 (org-indent-line)
13371 (end-of-line 0)))
13372 ((and org-log-state-notes-insert-after-drawers
13373 (save-excursion
13374 (forward-line) (looking-at org-drawer-regexp)))
13375 (forward-line)
13376 (while (looking-at org-drawer-regexp)
13377 (goto-char (match-end 0))
13378 (re-search-forward org-property-end-re (point-max) t)
13379 (forward-line))
13380 (forward-line -1)))
13381 (unless org-log-states-order-reversed
13382 (and (= (char-after) ?\n) (forward-char 1))
13383 (org-skip-over-state-notes)
13384 (skip-chars-backward " \t\n\r")))
13385 (move-marker org-log-note-marker (point))
13386 (setq org-log-note-purpose purpose
13387 org-log-note-state state
13388 org-log-note-previous-state prev-state
13389 org-log-note-how how
13390 org-log-note-extra extra
13391 org-log-note-effective-time (org-current-effective-time))
13392 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13394 (defun org-skip-over-state-notes ()
13395 "Skip past the list of State notes in an entry."
13396 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13397 (when (ignore-errors (goto-char (org-in-item-p)))
13398 (let* ((struct (org-list-struct))
13399 (prevs (org-list-prevs-alist struct)))
13400 (while (looking-at "[ \t]*- State")
13401 (goto-char (or (org-list-get-next-item (point) struct prevs)
13402 (org-list-get-item-end (point) struct)))))))
13404 (defun org-add-log-note (&optional purpose)
13405 "Pop up a window for taking a note, and add this note later at point."
13406 (remove-hook 'post-command-hook 'org-add-log-note)
13407 (setq org-log-note-window-configuration (current-window-configuration))
13408 (delete-other-windows)
13409 (move-marker org-log-note-return-to (point))
13410 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13411 (goto-char org-log-note-marker)
13412 (org-switch-to-buffer-other-window "*Org Note*")
13413 (erase-buffer)
13414 (if (memq org-log-note-how '(time state))
13415 (let (current-prefix-arg) (org-store-log-note))
13416 (let ((org-inhibit-startup t)) (org-mode))
13417 (insert (format "# Insert note for %s.
13418 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13419 (cond
13420 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13421 ((eq org-log-note-purpose 'done) "closed todo item")
13422 ((eq org-log-note-purpose 'state)
13423 (format "state change from \"%s\" to \"%s\""
13424 (or org-log-note-previous-state "")
13425 (or org-log-note-state "")))
13426 ((eq org-log-note-purpose 'reschedule)
13427 "rescheduling")
13428 ((eq org-log-note-purpose 'delschedule)
13429 "no longer scheduled")
13430 ((eq org-log-note-purpose 'redeadline)
13431 "changing deadline")
13432 ((eq org-log-note-purpose 'deldeadline)
13433 "removing deadline")
13434 ((eq org-log-note-purpose 'refile)
13435 "refiling")
13436 ((eq org-log-note-purpose 'note)
13437 "this entry")
13438 (t (error "This should not happen")))))
13439 (if org-log-note-extra (insert org-log-note-extra))
13440 (org-set-local 'org-finish-function 'org-store-log-note)
13441 (run-hooks 'org-log-buffer-setup-hook)))
13443 (defvar org-note-abort nil) ; dynamically scoped
13444 (defun org-store-log-note ()
13445 "Finish taking a log note, and insert it to where it belongs."
13446 (let ((txt (buffer-string)))
13447 (kill-buffer (current-buffer))
13448 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13449 lines ind bul)
13450 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13451 (setq txt (replace-match "" t t txt)))
13452 (if (string-match "\\s-+\\'" txt)
13453 (setq txt (replace-match "" t t txt)))
13454 (setq lines (org-split-string txt "\n"))
13455 (when (and note (string-match "\\S-" note))
13456 (setq note
13457 (org-replace-escapes
13458 note
13459 (list (cons "%u" (user-login-name))
13460 (cons "%U" user-full-name)
13461 (cons "%t" (format-time-string
13462 (org-time-stamp-format 'long 'inactive)
13463 org-log-note-effective-time))
13464 (cons "%T" (format-time-string
13465 (org-time-stamp-format 'long nil)
13466 org-log-note-effective-time))
13467 (cons "%d" (format-time-string
13468 (org-time-stamp-format nil 'inactive)
13469 org-log-note-effective-time))
13470 (cons "%D" (format-time-string
13471 (org-time-stamp-format nil nil)
13472 org-log-note-effective-time))
13473 (cons "%s" (if org-log-note-state
13474 (concat "\"" org-log-note-state "\"")
13475 ""))
13476 (cons "%S" (if org-log-note-previous-state
13477 (concat "\"" org-log-note-previous-state "\"")
13478 "\"\"")))))
13479 (if lines (setq note (concat note " \\\\")))
13480 (push note lines))
13481 (when (or current-prefix-arg org-note-abort)
13482 (when org-log-into-drawer
13483 (org-remove-empty-drawer-at org-log-note-marker))
13484 (setq lines nil))
13485 (when lines
13486 (with-current-buffer (marker-buffer org-log-note-marker)
13487 (save-excursion
13488 (goto-char org-log-note-marker)
13489 (move-marker org-log-note-marker nil)
13490 (end-of-line 1)
13491 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13492 (setq ind (save-excursion
13493 (if (ignore-errors (goto-char (org-in-item-p)))
13494 (let ((struct (org-list-struct)))
13495 (org-list-get-ind
13496 (org-list-get-top-point struct) struct))
13497 (skip-chars-backward " \r\t\n")
13498 (cond
13499 ((and (org-at-heading-p)
13500 org-adapt-indentation)
13501 (1+ (org-current-level)))
13502 ((org-at-heading-p) 0)
13503 (t (org-get-indentation))))))
13504 (setq bul (org-list-bullet-string "-"))
13505 (org-indent-line-to ind)
13506 (insert bul (pop lines))
13507 (let ((ind-body (+ (length bul) ind)))
13508 (while lines
13509 (insert "\n")
13510 (org-indent-line-to ind-body)
13511 (insert (pop lines))))
13512 (message "Note stored")
13513 (org-back-to-heading t)
13514 (org-cycle-hide-drawers 'children))
13515 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13516 ;; from within `org-add-log-note' because `buffer-undo-list'
13517 ;; is then modified outside of `org-with-remote-undo'.
13518 (when (eq this-command 'org-agenda-todo)
13519 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13520 ;; Don't add undo information when called from `org-agenda-todo'
13521 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13522 (set-window-configuration org-log-note-window-configuration)
13523 (with-current-buffer (marker-buffer org-log-note-return-to)
13524 (goto-char org-log-note-return-to))
13525 (move-marker org-log-note-return-to nil)
13526 (and org-log-post-message (message "%s" org-log-post-message))))
13528 (defun org-remove-empty-drawer-at (pos)
13529 "Remove an empty drawer at position POS.
13530 POS may also be a marker."
13531 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13532 (org-with-wide-buffer
13533 (goto-char pos)
13534 (let ((drawer (org-element-at-point)))
13535 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13536 (not (org-element-property :contents-begin drawer)))
13537 (delete-region (org-element-property :begin drawer)
13538 (progn (goto-char (org-element-property :end drawer))
13539 (skip-chars-backward " \r\t\n")
13540 (forward-line)
13541 (point))))))))
13543 (defvar org-ts-type nil)
13544 (defun org-sparse-tree (&optional arg type)
13545 "Create a sparse tree, prompt for the details.
13546 This command can create sparse trees. You first need to select the type
13547 of match used to create the tree:
13549 t Show all TODO entries.
13550 T Show entries with a specific TODO keyword.
13551 m Show entries selected by a tags/property match.
13552 p Enter a property name and its value (both with completion on existing
13553 names/values) and show entries with that property.
13554 r Show entries matching a regular expression (`/' can be used as well).
13555 b Show deadlines and scheduled items before a date.
13556 a Show deadlines and scheduled items after a date.
13557 d Show deadlines due within `org-deadline-warning-days'.
13558 D Show deadlines and scheduled items between a date range."
13559 (interactive "P")
13560 (let (ans kwd value ts-type)
13561 (setq type (or type org-sparse-tree-default-date-type))
13562 (setq org-ts-type type)
13563 (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"
13564 (cond ((eq type 'all) "all timestamps")
13565 ((eq type 'scheduled) "only scheduled")
13566 ((eq type 'deadline) "only deadline")
13567 ((eq type 'active) "only active timestamps")
13568 ((eq type 'inactive) "only inactive timestamps")
13569 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13570 ((eq type 'closed) "with a closed time-stamp")
13571 (t "scheduled/deadline")))
13572 (setq ans (read-char-exclusive))
13573 (cond
13574 ((equal ans ?c)
13575 (org-sparse-tree
13576 arg (cadr (member type '(scheduled-or-deadline
13577 all scheduled deadline active inactive closed)))))
13578 ((equal ans ?d)
13579 (call-interactively 'org-check-deadlines))
13580 ((equal ans ?b)
13581 (call-interactively 'org-check-before-date))
13582 ((equal ans ?a)
13583 (call-interactively 'org-check-after-date))
13584 ((equal ans ?D)
13585 (call-interactively 'org-check-dates-range))
13586 ((equal ans ?t)
13587 (call-interactively 'org-show-todo-tree))
13588 ((equal ans ?T)
13589 (org-show-todo-tree '(4)))
13590 ((member ans '(?T ?m))
13591 (call-interactively 'org-match-sparse-tree))
13592 ((member ans '(?p ?P))
13593 (setq kwd (org-icompleting-read "Property: "
13594 (mapcar 'list (org-buffer-property-keys))))
13595 (setq value (org-icompleting-read "Value: "
13596 (mapcar 'list (org-property-values kwd))))
13597 (unless (string-match "\\`{.*}\\'" value)
13598 (setq value (concat "\"" value "\"")))
13599 (org-match-sparse-tree arg (concat kwd "=" value)))
13600 ((member ans '(?r ?R ?/))
13601 (call-interactively 'org-occur))
13602 (t (user-error "No such sparse tree command \"%c\"" ans)))))
13604 (defvar org-occur-highlights nil
13605 "List of overlays used for occur matches.")
13606 (make-variable-buffer-local 'org-occur-highlights)
13607 (defvar org-occur-parameters nil
13608 "Parameters of the active org-occur calls.
13609 This is a list, each call to org-occur pushes as cons cell,
13610 containing the regular expression and the callback, onto the list.
13611 The list can contain several entries if `org-occur' has been called
13612 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13613 will only contain one set of parameters. When the highlights are
13614 removed (for example with `C-c C-c', or with the next edit (depending
13615 on `org-remove-highlights-with-change'), this variable is emptied
13616 as well.")
13617 (make-variable-buffer-local 'org-occur-parameters)
13619 (defun org-occur (regexp &optional keep-previous callback)
13620 "Make a compact tree which shows all matches of REGEXP.
13621 The tree will show the lines where the regexp matches, and all higher
13622 headlines above the match. It will also show the heading after the match,
13623 to make sure editing the matching entry is easy.
13624 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13625 call to `org-occur' will be kept, to allow stacking of calls to this
13626 command.
13627 If CALLBACK is non-nil, it is a function which is called to confirm
13628 that the match should indeed be shown."
13629 (interactive "sRegexp: \nP")
13630 (when (equal regexp "")
13631 (user-error "Regexp cannot be empty"))
13632 (unless keep-previous
13633 (org-remove-occur-highlights nil nil t))
13634 (push (cons regexp callback) org-occur-parameters)
13635 (let ((cnt 0))
13636 (save-excursion
13637 (goto-char (point-min))
13638 (if (or (not keep-previous) ; do not want to keep
13639 (not org-occur-highlights)) ; no previous matches
13640 ;; hide everything
13641 (org-overview))
13642 (while (re-search-forward regexp nil t)
13643 (when (or (not callback)
13644 (save-match-data (funcall callback)))
13645 (setq cnt (1+ cnt))
13646 (when org-highlight-sparse-tree-matches
13647 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13648 (org-show-context 'occur-tree))))
13649 (when org-remove-highlights-with-change
13650 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13651 nil 'local))
13652 (unless org-sparse-tree-open-archived-trees
13653 (org-hide-archived-subtrees (point-min) (point-max)))
13654 (run-hooks 'org-occur-hook)
13655 (if (org-called-interactively-p 'interactive)
13656 (message "%d match(es) for regexp %s" cnt regexp))
13657 cnt))
13659 (defun org-occur-next-match (&optional n reset)
13660 "Function for `next-error-function' to find sparse tree matches.
13661 N is the number of matches to move, when negative move backwards.
13662 RESET is entirely ignored - this function always goes back to the
13663 starting point when no match is found."
13664 (let* ((limit (if (< n 0) (point-min) (point-max)))
13665 (search-func (if (< n 0)
13666 'previous-single-char-property-change
13667 'next-single-char-property-change))
13668 (n (abs n))
13669 (pos (point))
13671 (catch 'exit
13672 (while (setq p1 (funcall search-func (point) 'org-type))
13673 (when (equal p1 limit)
13674 (goto-char pos)
13675 (error "No more matches"))
13676 (when (equal (get-char-property p1 'org-type) 'org-occur)
13677 (setq n (1- n))
13678 (when (= n 0)
13679 (goto-char p1)
13680 (throw 'exit (point))))
13681 (goto-char p1))
13682 (goto-char p1)
13683 (error "No more matches"))))
13685 (defun org-show-context (&optional key)
13686 "Make sure point and context are visible.
13687 How much context is shown depends upon the variables
13688 `org-show-hierarchy-above', `org-show-following-heading',
13689 `org-show-entry-below' and `org-show-siblings'."
13690 (let ((heading-p (org-at-heading-p t))
13691 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13692 (following-p (org-get-alist-option org-show-following-heading key))
13693 (entry-p (org-get-alist-option org-show-entry-below key))
13694 (siblings-p (org-get-alist-option org-show-siblings key)))
13695 ;; Show heading or entry text
13696 (if (and heading-p (not entry-p))
13697 (org-flag-heading nil) ; only show the heading
13698 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13699 (org-show-hidden-entry))) ; show entire entry
13700 (when following-p
13701 ;; Show next sibling, or heading below text
13702 (save-excursion
13703 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13704 (org-flag-heading nil))))
13705 (when siblings-p (org-show-siblings))
13706 (when hierarchy-p
13707 ;; show all higher headings, possibly with siblings
13708 (save-excursion
13709 (while (and (condition-case nil
13710 (progn (org-up-heading-all 1) t)
13711 (error nil))
13712 (not (bobp)))
13713 (org-flag-heading nil)
13714 (when siblings-p (org-show-siblings)))))
13715 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13717 (defvar org-reveal-start-hook nil
13718 "Hook run before revealing a location.")
13720 (defun org-reveal (&optional siblings)
13721 "Show current entry, hierarchy above it, and the following headline.
13722 This can be used to show a consistent set of context around locations
13723 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13724 not t for the search context.
13726 With optional argument SIBLINGS, on each level of the hierarchy all
13727 siblings are shown. This repairs the tree structure to what it would
13728 look like when opened with hierarchical calls to `org-cycle'.
13729 With double optional argument \\[universal-argument] \\[universal-argument], \
13730 go to the parent and show the
13731 entire tree."
13732 (interactive "P")
13733 (run-hooks 'org-reveal-start-hook)
13734 (let ((org-show-hierarchy-above t)
13735 (org-show-following-heading t)
13736 (org-show-siblings (if siblings t org-show-siblings)))
13737 (org-show-context nil))
13738 (when (equal siblings '(16))
13739 (save-excursion
13740 (when (org-up-heading-safe)
13741 (org-show-subtree)
13742 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13744 (defun org-highlight-new-match (beg end)
13745 "Highlight from BEG to END and mark the highlight is an occur headline."
13746 (let ((ov (make-overlay beg end)))
13747 (overlay-put ov 'face 'secondary-selection)
13748 (overlay-put ov 'org-type 'org-occur)
13749 (push ov org-occur-highlights)))
13751 (defun org-remove-occur-highlights (&optional beg end noremove)
13752 "Remove the occur highlights from the buffer.
13753 BEG and END are ignored. If NOREMOVE is nil, remove this function
13754 from the `before-change-functions' in the current buffer."
13755 (interactive)
13756 (unless org-inhibit-highlight-removal
13757 (mapc 'delete-overlay org-occur-highlights)
13758 (setq org-occur-highlights nil)
13759 (setq org-occur-parameters nil)
13760 (unless noremove
13761 (remove-hook 'before-change-functions
13762 'org-remove-occur-highlights 'local))))
13764 ;;;; Priorities
13766 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13767 "Regular expression matching the priority indicator.")
13769 (defvar org-remove-priority-next-time nil)
13771 (defun org-priority-up ()
13772 "Increase the priority of the current item."
13773 (interactive)
13774 (org-priority 'up))
13776 (defun org-priority-down ()
13777 "Decrease the priority of the current item."
13778 (interactive)
13779 (org-priority 'down))
13781 (defun org-priority (&optional action show)
13782 "Change the priority of an item.
13783 ACTION can be `set', `up', `down', or a character."
13784 (interactive "P")
13785 (if (equal action '(4))
13786 (org-show-priority)
13787 (unless org-enable-priority-commands
13788 (user-error "Priority commands are disabled"))
13789 (setq action (or action 'set))
13790 (let (current new news have remove)
13791 (save-excursion
13792 (org-back-to-heading t)
13793 (if (looking-at org-priority-regexp)
13794 (setq current (string-to-char (match-string 2))
13795 have t))
13796 (cond
13797 ((eq action 'remove)
13798 (setq remove t new ?\ ))
13799 ((or (eq action 'set)
13800 (if (featurep 'xemacs) (characterp action) (integerp action)))
13801 (if (not (eq action 'set))
13802 (setq new action)
13803 (message "Priority %c-%c, SPC to remove: "
13804 org-highest-priority org-lowest-priority)
13805 (save-match-data
13806 (setq new (read-char-exclusive))))
13807 (if (and (= (upcase org-highest-priority) org-highest-priority)
13808 (= (upcase org-lowest-priority) org-lowest-priority))
13809 (setq new (upcase new)))
13810 (cond ((equal new ?\ ) (setq remove t))
13811 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13812 (user-error "Priority must be between `%c' and `%c'"
13813 org-highest-priority org-lowest-priority))))
13814 ((eq action 'up)
13815 (setq new (if have
13816 (1- current) ; normal cycling
13817 ;; last priority was empty
13818 (if (eq last-command this-command)
13819 org-lowest-priority ; wrap around empty to lowest
13820 ;; default
13821 (if org-priority-start-cycle-with-default
13822 org-default-priority
13823 (1- org-default-priority))))))
13824 ((eq action 'down)
13825 (setq new (if have
13826 (1+ current) ; normal cycling
13827 ;; last priority was empty
13828 (if (eq last-command this-command)
13829 org-highest-priority ; wrap around empty to highest
13830 ;; default
13831 (if org-priority-start-cycle-with-default
13832 org-default-priority
13833 (1+ org-default-priority))))))
13834 (t (user-error "Invalid action")))
13835 (if (or (< (upcase new) org-highest-priority)
13836 (> (upcase new) org-lowest-priority))
13837 (if (and (memq action '(up down))
13838 (not have) (not (eq last-command this-command)))
13839 ;; `new' is from default priority
13840 (error
13841 "The default can not be set, see `org-default-priority' why")
13842 ;; normal cycling: `new' is beyond highest/lowest priority
13843 ;; and is wrapped around to the empty priority
13844 (setq remove t)))
13845 (setq news (format "%c" new))
13846 (if have
13847 (if remove
13848 (replace-match "" t t nil 1)
13849 (replace-match news t t nil 2))
13850 (if remove
13851 (user-error "No priority cookie found in line")
13852 (let ((case-fold-search nil))
13853 (looking-at org-todo-line-regexp))
13854 (if (match-end 2)
13855 (progn
13856 (goto-char (match-end 2))
13857 (insert " [#" news "]"))
13858 (goto-char (match-beginning 3))
13859 (insert "[#" news "] "))))
13860 (org-preserve-lc (org-set-tags nil 'align)))
13861 (if remove
13862 (message "Priority removed")
13863 (message "Priority of current item set to %s" news)))))
13865 (defun org-show-priority ()
13866 "Show the priority of the current item.
13867 This priority is composed of the main priority given with the [#A] cookies,
13868 and by additional input from the age of a schedules or deadline entry."
13869 (interactive)
13870 (let ((pri (if (eq major-mode 'org-agenda-mode)
13871 (org-get-at-bol 'priority)
13872 (save-excursion
13873 (save-match-data
13874 (beginning-of-line)
13875 (and (looking-at org-heading-regexp)
13876 (org-get-priority (match-string 0))))))))
13877 (message "Priority is %d" (if pri pri -1000))))
13879 (defun org-get-priority (s)
13880 "Find priority cookie and return priority."
13881 (save-match-data
13882 (if (functionp org-get-priority-function)
13883 (funcall org-get-priority-function)
13884 (if (not (string-match org-priority-regexp s))
13885 (* 1000 (- org-lowest-priority org-default-priority))
13886 (* 1000 (- org-lowest-priority
13887 (string-to-char (match-string 2 s))))))))
13889 ;;;; Tags
13891 (defvar org-agenda-archives-mode)
13892 (defvar org-map-continue-from nil
13893 "Position from where mapping should continue.
13894 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13896 (defvar org-scanner-tags nil
13897 "The current tag list while the tags scanner is running.")
13898 (defvar org-trust-scanner-tags nil
13899 "Should `org-get-tags-at' use the tags for the scanner.
13900 This is for internal dynamical scoping only.
13901 When this is non-nil, the function `org-get-tags-at' will return the value
13902 of `org-scanner-tags' instead of building the list by itself. This
13903 can lead to large speed-ups when the tags scanner is used in a file with
13904 many entries, and when the list of tags is retrieved, for example to
13905 obtain a list of properties. Building the tags list for each entry in such
13906 a file becomes an N^2 operation - but with this variable set, it scales
13907 as N.")
13909 (defun org-scan-tags (action matcher todo-only &optional start-level)
13910 "Sca headline tags with inheritance and produce output ACTION.
13912 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13913 or `agenda' to produce an entry list for an agenda view. It can also be
13914 a Lisp form or a function that should be called at each matched headline, in
13915 this case the return value is a list of all return values from these calls.
13917 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13918 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13919 only lines with a not-done TODO keyword are included in the output.
13920 This should be the same variable that was scoped into
13921 and set by `org-make-tags-matcher' when it constructed MATCHER.
13923 START-LEVEL can be a string with asterisks, reducing the scope to
13924 headlines matching this string."
13925 (require 'org-agenda)
13926 (let* ((re (concat "^"
13927 (if start-level
13928 ;; Get the correct level to match
13929 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13930 org-outline-regexp)
13931 " *\\(\\<\\("
13932 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13933 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13934 (props (list 'face 'default
13935 'done-face 'org-agenda-done
13936 'undone-face 'default
13937 'mouse-face 'highlight
13938 'org-not-done-regexp org-not-done-regexp
13939 'org-todo-regexp org-todo-regexp
13940 'org-complex-heading-regexp org-complex-heading-regexp
13941 'help-echo
13942 (format "mouse-2 or RET jump to org file %s"
13943 (abbreviate-file-name
13944 (or (buffer-file-name (buffer-base-buffer))
13945 (buffer-name (buffer-base-buffer)))))))
13946 (org-map-continue-from nil)
13947 lspos tags tags-list
13948 (tags-alist (list (cons 0 org-file-tags)))
13949 (llast 0) rtn rtn1 level category i txt
13950 todo marker entry priority)
13951 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13952 (setq action (list 'lambda nil action)))
13953 (save-excursion
13954 (goto-char (point-min))
13955 (when (eq action 'sparse-tree)
13956 (org-overview)
13957 (org-remove-occur-highlights))
13958 (while (let (case-fold-search)
13959 (re-search-forward re nil t))
13960 (setq org-map-continue-from nil)
13961 (catch :skip
13962 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13963 tags (if (match-end 4) (org-match-string-no-properties 4)))
13964 (goto-char (setq lspos (match-beginning 0)))
13965 (setq level (org-reduced-level (org-outline-level))
13966 category (org-get-category))
13967 (setq i llast llast level)
13968 ;; remove tag lists from same and sublevels
13969 (while (>= i level)
13970 (when (setq entry (assoc i tags-alist))
13971 (setq tags-alist (delete entry tags-alist)))
13972 (setq i (1- i)))
13973 ;; add the next tags
13974 (when tags
13975 (setq tags (org-split-string tags ":")
13976 tags-alist
13977 (cons (cons level tags) tags-alist)))
13978 ;; compile tags for current headline
13979 (setq tags-list
13980 (if org-use-tag-inheritance
13981 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13982 tags)
13983 org-scanner-tags tags-list)
13984 (when org-use-tag-inheritance
13985 (setcdr (car tags-alist)
13986 (mapcar (lambda (x)
13987 (setq x (copy-sequence x))
13988 (org-add-prop-inherited x))
13989 (cdar tags-alist))))
13990 (when (and tags org-use-tag-inheritance
13991 (or (not (eq t org-use-tag-inheritance))
13992 org-tags-exclude-from-inheritance))
13993 ;; selective inheritance, remove uninherited ones
13994 (setcdr (car tags-alist)
13995 (org-remove-uninherited-tags (cdar tags-alist))))
13996 (when (and
13998 ;; eval matcher only when the todo condition is OK
13999 (and (or (not todo-only) (member todo org-not-done-keywords))
14000 (let ((case-fold-search t) (org-trust-scanner-tags t))
14001 (eval matcher)))
14003 ;; Call the skipper, but return t if it does not skip,
14004 ;; so that the `and' form continues evaluating
14005 (progn
14006 (unless (eq action 'sparse-tree) (org-agenda-skip))
14009 ;; Check if timestamps are deselecting this entry
14010 (or (not todo-only)
14011 (and (member todo org-not-done-keywords)
14012 (or (not org-agenda-tags-todo-honor-ignore-options)
14013 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14015 ;; select this headline
14016 (cond
14017 ((eq action 'sparse-tree)
14018 (and org-highlight-sparse-tree-matches
14019 (org-get-heading) (match-end 0)
14020 (org-highlight-new-match
14021 (match-beginning 1) (match-end 1)))
14022 (org-show-context 'tags-tree))
14023 ((eq action 'agenda)
14024 (setq txt (org-agenda-format-item
14026 (concat
14027 (if (eq org-tags-match-list-sublevels 'indented)
14028 (make-string (1- level) ?.) "")
14029 (org-get-heading))
14030 level category
14031 tags-list)
14032 priority (org-get-priority txt))
14033 (goto-char lspos)
14034 (setq marker (org-agenda-new-marker))
14035 (org-add-props txt props
14036 'org-marker marker 'org-hd-marker marker 'org-category category
14037 'todo-state todo
14038 'priority priority 'type "tagsmatch")
14039 (push txt rtn))
14040 ((functionp action)
14041 (setq org-map-continue-from nil)
14042 (save-excursion
14043 (setq rtn1 (funcall action))
14044 (push rtn1 rtn)))
14045 (t (user-error "Invalid action")))
14047 ;; if we are to skip sublevels, jump to end of subtree
14048 (unless org-tags-match-list-sublevels
14049 (org-end-of-subtree t)
14050 (backward-char 1))))
14051 ;; Get the correct position from where to continue
14052 (if org-map-continue-from
14053 (goto-char org-map-continue-from)
14054 (and (= (point) lspos) (end-of-line 1)))))
14055 (when (and (eq action 'sparse-tree)
14056 (not org-sparse-tree-open-archived-trees))
14057 (org-hide-archived-subtrees (point-min) (point-max)))
14058 (nreverse rtn)))
14060 (defun org-remove-uninherited-tags (tags)
14061 "Remove all tags that are not inherited from the list TAGS."
14062 (cond
14063 ((eq org-use-tag-inheritance t)
14064 (if org-tags-exclude-from-inheritance
14065 (org-delete-all org-tags-exclude-from-inheritance tags)
14066 tags))
14067 ((not org-use-tag-inheritance) nil)
14068 ((stringp org-use-tag-inheritance)
14069 (delq nil (mapcar
14070 (lambda (x)
14071 (if (and (string-match org-use-tag-inheritance x)
14072 (not (member x org-tags-exclude-from-inheritance)))
14073 x nil))
14074 tags)))
14075 ((listp org-use-tag-inheritance)
14076 (delq nil (mapcar
14077 (lambda (x)
14078 (if (member x org-use-tag-inheritance) x nil))
14079 tags)))))
14081 (defun org-match-sparse-tree (&optional todo-only match)
14082 "Create a sparse tree according to tags string MATCH.
14083 MATCH can contain positive and negative selection of tags, like
14084 \"+WORK+URGENT-WITHBOSS\".
14085 If optional argument TODO-ONLY is non-nil, only select lines that are
14086 also TODO lines."
14087 (interactive "P")
14088 (org-agenda-prepare-buffers (list (current-buffer)))
14089 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
14091 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14093 (defvar org-cached-props nil)
14094 (defun org-cached-entry-get (pom property)
14095 (if (or (eq t org-use-property-inheritance)
14096 (and (stringp org-use-property-inheritance)
14097 (string-match org-use-property-inheritance property))
14098 (and (listp org-use-property-inheritance)
14099 (member property org-use-property-inheritance)))
14100 ;; Caching is not possible, check it directly
14101 (org-entry-get pom property 'inherit)
14102 ;; Get all properties, so that we can do complicated checks easily
14103 (cdr (assoc property (or org-cached-props
14104 (setq org-cached-props
14105 (org-entry-properties pom)))))))
14107 (defun org-global-tags-completion-table (&optional files)
14108 "Return the list of all tags in all agenda buffer/files.
14109 Optional FILES argument is a list of files which can be used
14110 instead of the agenda files."
14111 (save-excursion
14112 (org-uniquify
14113 (delq nil
14114 (apply 'append
14115 (mapcar
14116 (lambda (file)
14117 (set-buffer (find-file-noselect file))
14118 (append (org-get-buffer-tags)
14119 (mapcar (lambda (x) (if (stringp (car-safe x))
14120 (list (car-safe x)) nil))
14121 org-tag-alist)))
14122 (if (and files (car files))
14123 files
14124 (org-agenda-files))))))))
14126 (defun org-make-tags-matcher (match)
14127 "Create the TAGS/TODO matcher form for the selection string MATCH.
14129 The variable `todo-only' is scoped dynamically into this function.
14130 It will be set to t if the matcher restricts matching to TODO entries,
14131 otherwise will not be touched.
14133 Returns a cons of the selection string MATCH and the constructed
14134 lisp form implementing the matcher. The matcher is to be evaluated
14135 at an Org entry, with point on the headline, and returns t if the
14136 entry matches the selection string MATCH. The returned lisp form
14137 references two variables with information about the entry, which
14138 must be bound around the form's evaluation: todo, the TODO keyword
14139 at the entry (or nil of none); and tags-list, the list of all tags
14140 at the entry including inherited ones. Additionally, the category
14141 of the entry (if any) must be specified as the text property
14142 'org-category on the headline.
14144 See also `org-scan-tags'.
14146 (declare (special todo-only))
14147 (unless (boundp 'todo-only)
14148 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14149 (unless match
14150 ;; Get a new match request, with completion against the global
14151 ;; tags table and the local tags in current buffer
14152 (let ((org-last-tags-completion-table
14153 (org-uniquify
14154 (delq nil (append (org-get-buffer-tags)
14155 (org-global-tags-completion-table))))))
14156 (setq match (org-completing-read-no-i
14157 "Match: " 'org-tags-completion-function nil nil nil
14158 'org-tags-history))))
14160 ;; Parse the string and create a lisp form
14161 (let ((match0 match)
14162 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14163 minus tag mm
14164 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14165 orterms term orlist re-p str-p level-p level-op time-p
14166 prop-p pn pv po gv rest (start 0) (ss 0))
14167 ;; Expand group tags
14168 (setq match (org-tags-expand match))
14170 ;; Check if there is a TODO part of this match, which would be the
14171 ;; part after a "/". TO make sure that this slash is not part of
14172 ;; a property value to be matched against, we also check that there
14173 ;; is no " after that slash.
14174 ;; First, find the last slash
14175 (while (string-match "/+" match ss)
14176 (setq start (match-beginning 0) ss (match-end 0)))
14177 (if (and (string-match "/+" match start)
14178 (not (save-match-data (string-match "\"" match start))))
14179 ;; match contains also a todo-matching request
14180 (progn
14181 (setq tagsmatch (substring match 0 (match-beginning 0))
14182 todomatch (substring match (match-end 0)))
14183 (if (string-match "^!" todomatch)
14184 (setq todo-only t todomatch (substring todomatch 1)))
14185 (if (string-match "^\\s-*$" todomatch)
14186 (setq todomatch nil)))
14187 ;; only matching tags
14188 (setq tagsmatch match todomatch nil))
14190 ;; Make the tags matcher
14191 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14192 (setq tagsmatcher t)
14193 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14194 (while (setq term (pop orterms))
14195 (while (and (equal (substring term -1) "\\") orterms)
14196 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14197 (while (string-match re term)
14198 (setq rest (substring term (match-end 0))
14199 minus (and (match-end 1)
14200 (equal (match-string 1 term) "-"))
14201 tag (save-match-data (replace-regexp-in-string
14202 "\\\\-" "-"
14203 (match-string 2 term)))
14204 re-p (equal (string-to-char tag) ?{)
14205 level-p (match-end 4)
14206 prop-p (match-end 5)
14207 mm (cond
14208 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14209 (level-p
14210 (setq level-op (org-op-to-function (match-string 3 term)))
14211 `(,level-op level ,(string-to-number
14212 (match-string 4 term))))
14213 (prop-p
14214 (setq pn (match-string 5 term)
14215 po (match-string 6 term)
14216 pv (match-string 7 term)
14217 re-p (equal (string-to-char pv) ?{)
14218 str-p (equal (string-to-char pv) ?\")
14219 time-p (save-match-data
14220 (string-match "^\"[[<].*[]>]\"$" pv))
14221 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14222 (if time-p (setq pv (org-matcher-time pv)))
14223 (setq po (org-op-to-function po (if time-p 'time str-p)))
14224 (cond
14225 ((equal pn "CATEGORY")
14226 (setq gv '(get-text-property (point) 'org-category)))
14227 ((equal pn "TODO")
14228 (setq gv 'todo))
14230 (setq gv `(org-cached-entry-get nil ,pn))))
14231 (if re-p
14232 (if (eq po 'org<>)
14233 `(not (string-match ,pv (or ,gv "")))
14234 `(string-match ,pv (or ,gv "")))
14235 (if str-p
14236 `(,po (or ,gv "") ,pv)
14237 `(,po (string-to-number (or ,gv ""))
14238 ,(string-to-number pv) ))))
14239 (t `(member ,tag tags-list)))
14240 mm (if minus (list 'not mm) mm)
14241 term rest)
14242 (push mm tagsmatcher))
14243 (push (if (> (length tagsmatcher) 1)
14244 (cons 'and tagsmatcher)
14245 (car tagsmatcher))
14246 orlist)
14247 (setq tagsmatcher nil))
14248 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14249 (setq tagsmatcher
14250 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14251 ;; Make the todo matcher
14252 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14253 (setq todomatcher t)
14254 (setq orterms (org-split-string todomatch "|") orlist nil)
14255 (while (setq term (pop orterms))
14256 (while (string-match re term)
14257 (setq minus (and (match-end 1)
14258 (equal (match-string 1 term) "-"))
14259 kwd (match-string 2 term)
14260 re-p (equal (string-to-char kwd) ?{)
14261 term (substring term (match-end 0))
14262 mm (if re-p
14263 `(string-match ,(substring kwd 1 -1) todo)
14264 (list 'equal 'todo kwd))
14265 mm (if minus (list 'not mm) mm))
14266 (push mm todomatcher))
14267 (push (if (> (length todomatcher) 1)
14268 (cons 'and todomatcher)
14269 (car todomatcher))
14270 orlist)
14271 (setq todomatcher nil))
14272 (setq todomatcher (if (> (length orlist) 1)
14273 (cons 'or orlist) (car orlist))))
14275 ;; Return the string and lisp forms of the matcher
14276 (setq matcher (if todomatcher
14277 (list 'and tagsmatcher todomatcher)
14278 tagsmatcher))
14279 (when todo-only
14280 (setq matcher (list 'and '(member todo org-not-done-keywords)
14281 matcher)))
14282 (cons match0 matcher)))
14284 (defun org-tags-expand (match &optional single-as-list downcased)
14285 "Expand group tags in MATCH.
14287 This replaces every group tag in MATCH with a regexp tag search.
14288 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14289 will be replaced like this:
14291 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14292 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14293 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14295 Replacing by a regexp preserves the structure of the match.
14296 E.g., this expansion
14298 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14300 will match anything tagged with \"Lab\" and \"Home\", or tagged
14301 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14303 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14304 assumed to be a single group tag, and the function will return
14305 the list of tags in this group.
14307 When DOWNCASE is non-nil, expand downcased TAGS."
14308 (if org-group-tags
14309 (let* ((case-fold-search t)
14310 (stable org-mode-syntax-table)
14311 (tal (or org-tag-groups-alist-for-agenda
14312 org-tag-groups-alist))
14313 (tal (if downcased
14314 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14315 (tml (mapcar 'car tal))
14316 (rtnmatch match) rpl)
14317 ;; @ and _ are allowed as word-components in tags
14318 (modify-syntax-entry ?@ "w" stable)
14319 (modify-syntax-entry ?_ "w" stable)
14320 (while (and tml
14321 (with-syntax-table stable
14322 (string-match
14323 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14324 (regexp-opt tml) "\\>\\)") rtnmatch)))
14325 (let* ((dir (match-string 1 rtnmatch))
14326 (tag (match-string 2 rtnmatch))
14327 (tag (if downcased (downcase tag) tag)))
14328 (setq tml (delete tag tml))
14329 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14330 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14331 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14332 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14333 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14334 (if single-as-list
14335 (or (reverse rpl) (list rtnmatch))
14336 rtnmatch))
14337 (if single-as-list (list (if downcased (downcase match) match))
14338 match)))
14340 (defun org-op-to-function (op &optional stringp)
14341 "Turn an operator into the appropriate function."
14342 (setq op
14343 (cond
14344 ((equal op "<" ) '(< string< org-time<))
14345 ((equal op ">" ) '(> org-string> org-time>))
14346 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14347 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14348 ((member op '("=" "==")) '(= string= org-time=))
14349 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14350 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14352 (defun org<> (a b) (not (= a b)))
14353 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14354 (defun org-string>= (a b) (not (string< a b)))
14355 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14356 (defun org-string<> (a b) (not (string= a b)))
14357 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14358 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14359 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14360 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14361 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14362 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14363 (defun org-2ft (s)
14364 "Convert S to a floating point time.
14365 If S is already a number, just return it. If it is a string, parse
14366 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14367 (cond
14368 ((numberp s) s)
14369 ((stringp s)
14370 (condition-case nil
14371 (float-time (apply 'encode-time (org-parse-time-string s)))
14372 (error 0.)))
14373 (t 0.)))
14375 (defun org-time-today ()
14376 "Time in seconds today at 0:00.
14377 Returns the float number of seconds since the beginning of the
14378 epoch to the beginning of today (00:00)."
14379 (float-time (apply 'encode-time
14380 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14382 (defun org-matcher-time (s)
14383 "Interpret a time comparison value."
14384 (save-match-data
14385 (cond
14386 ((string= s "<now>") (float-time))
14387 ((string= s "<today>") (org-time-today))
14388 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14389 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14390 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14391 (+ (org-time-today)
14392 (* (string-to-number (match-string 1 s))
14393 (cdr (assoc (match-string 2 s)
14394 '(("d" . 86400.0) ("w" . 604800.0)
14395 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14396 (t (org-2ft s)))))
14398 (defun org-match-any-p (re list)
14399 "Does re match any element of list?"
14400 (setq list (mapcar (lambda (x) (string-match re x)) list))
14401 (delq nil list))
14403 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14404 (defvar org-tags-overlay (make-overlay 1 1))
14405 (org-detach-overlay org-tags-overlay)
14407 (defun org-get-local-tags-at (&optional pos)
14408 "Get a list of tags defined in the current headline."
14409 (org-get-tags-at pos 'local))
14411 (defun org-get-local-tags ()
14412 "Get a list of tags defined in the current headline."
14413 (org-get-tags-at nil 'local))
14415 (defun org-get-tags-at (&optional pos local)
14416 "Get a list of all headline tags applicable at POS.
14417 POS defaults to point. If tags are inherited, the list contains
14418 the targets in the same sequence as the headlines appear, i.e.
14419 the tags of the current headline come last.
14420 When LOCAL is non-nil, only return tags from the current headline,
14421 ignore inherited ones."
14422 (interactive)
14423 (if (and org-trust-scanner-tags
14424 (or (not pos) (equal pos (point)))
14425 (not local))
14426 org-scanner-tags
14427 (let (tags ltags lastpos parent)
14428 (save-excursion
14429 (save-restriction
14430 (widen)
14431 (goto-char (or pos (point)))
14432 (save-match-data
14433 (catch 'done
14434 (condition-case nil
14435 (progn
14436 (org-back-to-heading t)
14437 (while (not (equal lastpos (point)))
14438 (setq lastpos (point))
14439 (when (looking-at
14440 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14441 (setq ltags (org-split-string
14442 (org-match-string-no-properties 1) ":"))
14443 (when parent
14444 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14445 (setq tags (append
14446 (if parent
14447 (org-remove-uninherited-tags ltags)
14448 ltags)
14449 tags)))
14450 (or org-use-tag-inheritance (throw 'done t))
14451 (if local (throw 'done t))
14452 (or (org-up-heading-safe) (error nil))
14453 (setq parent t)))
14454 (error nil)))))
14455 (if local
14456 tags
14457 (reverse (delete-dups
14458 (reverse (append
14459 (org-remove-uninherited-tags
14460 org-file-tags) tags)))))))))
14462 (defun org-add-prop-inherited (s)
14463 (add-text-properties 0 (length s) '(inherited t) s)
14466 (defun org-toggle-tag (tag &optional onoff)
14467 "Toggle the tag TAG for the current line.
14468 If ONOFF is `on' or `off', don't toggle but set to this state."
14469 (let (res current)
14470 (save-excursion
14471 (org-back-to-heading t)
14472 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14473 (point-at-eol) t)
14474 (progn
14475 (setq current (match-string 1))
14476 (replace-match ""))
14477 (setq current ""))
14478 (setq current (nreverse (org-split-string current ":")))
14479 (cond
14480 ((eq onoff 'on)
14481 (setq res t)
14482 (or (member tag current) (push tag current)))
14483 ((eq onoff 'off)
14484 (or (not (member tag current)) (setq current (delete tag current))))
14485 (t (if (member tag current)
14486 (setq current (delete tag current))
14487 (setq res t)
14488 (push tag current))))
14489 (end-of-line 1)
14490 (if current
14491 (progn
14492 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14493 (org-set-tags nil t))
14494 (delete-horizontal-space))
14495 (run-hooks 'org-after-tags-change-hook))
14496 res))
14498 (defun org-align-tags-here (to-col)
14499 ;; Assumes that this is a headline
14500 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14501 (beginning-of-line 1)
14502 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14503 (< pos (match-beginning 2)))
14504 (progn
14505 (setq tags-l (- (match-end 2) (match-beginning 2)))
14506 (goto-char (match-beginning 1))
14507 (insert " ")
14508 (delete-region (point) (1+ (match-beginning 2)))
14509 (setq ncol (max (current-column)
14510 (1+ col)
14511 (if (> to-col 0)
14512 to-col
14513 (- (abs to-col) tags-l))))
14514 (setq p (point))
14515 (insert (make-string (- ncol (current-column)) ?\ ))
14516 (setq ncol (current-column))
14517 (when indent-tabs-mode (tabify p (point-at-eol)))
14518 (org-move-to-column (min ncol col) t nil t))
14519 (goto-char pos))))
14521 (defun org-set-tags-command (&optional arg just-align)
14522 "Call the set-tags command for the current entry."
14523 (interactive "P")
14524 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14525 (org-set-tags arg just-align)
14526 (save-excursion
14527 (unless (and (org-region-active-p)
14528 org-loop-over-headlines-in-active-region)
14529 (org-back-to-heading t))
14530 (org-set-tags arg just-align))))
14532 (defun org-set-tags-to (data)
14533 "Set the tags of the current entry to DATA, replacing the current tags.
14534 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14535 If DATA is nil or the empty string, any tags will be removed."
14536 (interactive "sTags: ")
14537 (setq data
14538 (cond
14539 ((eq data nil) "")
14540 ((equal data "") "")
14541 ((stringp data)
14542 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14543 ":"))
14544 ((listp data)
14545 (concat ":" (mapconcat 'identity data ":") ":"))))
14546 (when data
14547 (save-excursion
14548 (org-back-to-heading t)
14549 (when (looking-at org-complex-heading-regexp)
14550 (if (match-end 5)
14551 (progn
14552 (goto-char (match-beginning 5))
14553 (insert data)
14554 (delete-region (point) (point-at-eol))
14555 (org-set-tags nil 'align))
14556 (goto-char (point-at-eol))
14557 (insert " " data)
14558 (org-set-tags nil 'align)))
14559 (beginning-of-line 1)
14560 (if (looking-at ".*?\\([ \t]+\\)$")
14561 (delete-region (match-beginning 1) (match-end 1))))))
14563 (defun org-align-all-tags ()
14564 "Align the tags i all headings."
14565 (interactive)
14566 (save-excursion
14567 (or (ignore-errors (org-back-to-heading t))
14568 (outline-next-heading))
14569 (if (org-at-heading-p)
14570 (org-set-tags t)
14571 (message "No headings"))))
14573 (defvar org-indent-indentation-per-level)
14574 (defun org-set-tags (&optional arg just-align)
14575 "Set the tags for the current headline.
14576 With prefix ARG, realign all tags in headings in the current buffer."
14577 (interactive "P")
14578 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14579 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14580 'region-start-level 'region))
14581 org-loop-over-headlines-in-active-region)
14582 (org-map-entries
14583 ;; We don't use ARG and JUST-ALIGN here these args are not
14584 ;; useful when looping over headlines
14585 `(org-set-tags)
14586 org-loop-over-headlines-in-active-region
14587 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14588 (let* ((re org-outline-regexp-bol)
14589 (current (unless arg (org-get-tags-string)))
14590 (col (current-column))
14591 (org-setting-tags t)
14592 table current-tags inherited-tags ; computed below when needed
14593 tags p0 c0 c1 rpl di tc level)
14594 (if arg
14595 (save-excursion
14596 (goto-char (point-min))
14597 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14598 (while (re-search-forward re nil t)
14599 (org-set-tags nil t)
14600 (end-of-line 1)))
14601 (message "All tags realigned to column %d" org-tags-column))
14602 (if just-align
14603 (setq tags current)
14604 ;; Get a new set of tags from the user
14605 (save-excursion
14606 (setq table (append org-tag-persistent-alist
14607 (or org-tag-alist (org-get-buffer-tags))
14608 (and
14609 org-complete-tags-always-offer-all-agenda-tags
14610 (org-global-tags-completion-table
14611 (org-agenda-files))))
14612 org-last-tags-completion-table table
14613 current-tags (org-split-string current ":")
14614 inherited-tags (nreverse
14615 (nthcdr (length current-tags)
14616 (nreverse (org-get-tags-at))))
14617 tags
14618 (if (or (eq t org-use-fast-tag-selection)
14619 (and org-use-fast-tag-selection
14620 (delq nil (mapcar 'cdr table))))
14621 (org-fast-tag-selection
14622 current-tags inherited-tags table
14623 (if org-fast-tag-selection-include-todo
14624 org-todo-key-alist))
14625 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14626 (org-trim
14627 (org-icompleting-read "Tags: "
14628 'org-tags-completion-function
14629 nil nil current 'org-tags-history))))))
14630 (while (string-match "[-+&]+" tags)
14631 ;; No boolean logic, just a list
14632 (setq tags (replace-match ":" t t tags))))
14634 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14636 (if org-tags-sort-function
14637 (setq tags (mapconcat 'identity
14638 (sort (org-split-string
14639 tags (org-re "[^[:alnum:]_@#%]+"))
14640 org-tags-sort-function) ":")))
14642 (if (string-match "\\`[\t ]*\\'" tags)
14643 (setq tags "")
14644 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14645 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14647 ;; Insert new tags at the correct column
14648 (beginning-of-line 1)
14649 (setq level (or (and (looking-at org-outline-regexp)
14650 (- (match-end 0) (point) 1))
14652 (cond
14653 ((and (equal current "") (equal tags "")))
14654 ((re-search-forward
14655 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14656 (point-at-eol) t)
14657 (if (equal tags "")
14658 (setq rpl "")
14659 (goto-char (match-beginning 0))
14660 (setq c0 (current-column)
14661 ;; compute offset for the case of org-indent-mode active
14662 di (if org-indent-mode
14663 (* (1- org-indent-indentation-per-level) (1- level))
14665 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14666 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14667 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (string-width tags))))
14668 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14669 (replace-match rpl t t)
14670 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14671 tags)
14672 (t (error "Tags alignment failed")))
14673 (org-move-to-column col nil nil t)
14674 (unless just-align
14675 (run-hooks 'org-after-tags-change-hook))))))
14677 (defun org-change-tag-in-region (beg end tag off)
14678 "Add or remove TAG for each entry in the region.
14679 This works in the agenda, and also in an org-mode buffer."
14680 (interactive
14681 (list (region-beginning) (region-end)
14682 (let ((org-last-tags-completion-table
14683 (if (derived-mode-p 'org-mode)
14684 (org-uniquify
14685 (delq nil (append (org-get-buffer-tags)
14686 (org-global-tags-completion-table))))
14687 (org-global-tags-completion-table))))
14688 (org-icompleting-read
14689 "Tag: " 'org-tags-completion-function nil nil nil
14690 'org-tags-history))
14691 (progn
14692 (message "[s]et or [r]emove? ")
14693 (equal (read-char-exclusive) ?r))))
14694 (if (fboundp 'deactivate-mark) (deactivate-mark))
14695 (let ((agendap (equal major-mode 'org-agenda-mode))
14696 l1 l2 m buf pos newhead (cnt 0))
14697 (goto-char end)
14698 (setq l2 (1- (org-current-line)))
14699 (goto-char beg)
14700 (setq l1 (org-current-line))
14701 (loop for l from l1 to l2 do
14702 (org-goto-line l)
14703 (setq m (get-text-property (point) 'org-hd-marker))
14704 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14705 (and agendap m))
14706 (setq buf (if agendap (marker-buffer m) (current-buffer))
14707 pos (if agendap m (point)))
14708 (with-current-buffer buf
14709 (save-excursion
14710 (save-restriction
14711 (goto-char pos)
14712 (setq cnt (1+ cnt))
14713 (org-toggle-tag tag (if off 'off 'on))
14714 (setq newhead (org-get-heading)))))
14715 (and agendap (org-agenda-change-all-lines newhead m))))
14716 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14718 (defun org-tags-completion-function (string predicate &optional flag)
14719 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14720 (confirm (lambda (x) (stringp (car x)))))
14721 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14722 (setq s1 (match-string 1 string)
14723 s2 (match-string 2 string))
14724 (setq s1 "" s2 string))
14725 (cond
14726 ((eq flag nil)
14727 ;; try completion
14728 (setq rtn (try-completion s2 ctable confirm))
14729 (if (stringp rtn)
14730 (setq rtn
14731 (concat s1 s2 (substring rtn (length s2))
14732 (if (and org-add-colon-after-tag-completion
14733 (assoc rtn ctable))
14734 ":" ""))))
14735 rtn)
14736 ((eq flag t)
14737 ;; all-completions
14738 (all-completions s2 ctable confirm))
14739 ((eq flag 'lambda)
14740 ;; exact match?
14741 (assoc s2 ctable)))))
14743 (defun org-fast-tag-insert (kwd tags face &optional end)
14744 "Insert KDW, and the TAGS, the latter with face FACE.
14745 Also insert END."
14746 (insert (format "%-12s" (concat kwd ":"))
14747 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14748 (or end "")))
14750 (defun org-fast-tag-show-exit (flag)
14751 (save-excursion
14752 (org-goto-line 3)
14753 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14754 (replace-match ""))
14755 (when flag
14756 (end-of-line 1)
14757 (org-move-to-column (- (window-width) 19) t)
14758 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14760 (defun org-set-current-tags-overlay (current prefix)
14761 "Add an overlay to CURRENT tag with PREFIX."
14762 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14763 (if (featurep 'xemacs)
14764 (org-overlay-display org-tags-overlay (concat prefix s)
14765 'secondary-selection)
14766 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14767 (org-overlay-display org-tags-overlay (concat prefix s)))))
14769 (defvar org-last-tag-selection-key nil)
14770 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14771 "Fast tag selection with single keys.
14772 CURRENT is the current list of tags in the headline, INHERITED is the
14773 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14774 possibly with grouping information. TODO-TABLE is a similar table with
14775 TODO keywords, should these have keys assigned to them.
14776 If the keys are nil, a-z are automatically assigned.
14777 Returns the new tags string, or nil to not change the current settings."
14778 (let* ((fulltable (append table todo-table))
14779 (maxlen (apply 'max (mapcar
14780 (lambda (x)
14781 (if (stringp (car x)) (string-width (car x)) 0))
14782 fulltable)))
14783 (buf (current-buffer))
14784 (expert (eq org-fast-tag-selection-single-key 'expert))
14785 (buffer-tags nil)
14786 (fwidth (+ maxlen 3 1 3))
14787 (ncol (/ (- (window-width) 4) fwidth))
14788 (i-face 'org-done)
14789 (c-face 'org-todo)
14790 tg cnt e c char c1 c2 ntable tbl rtn
14791 ov-start ov-end ov-prefix
14792 (exit-after-next org-fast-tag-selection-single-key)
14793 (done-keywords org-done-keywords)
14794 groups ingroup)
14795 (save-excursion
14796 (beginning-of-line 1)
14797 (if (looking-at
14798 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14799 (setq ov-start (match-beginning 1)
14800 ov-end (match-end 1)
14801 ov-prefix "")
14802 (setq ov-start (1- (point-at-eol))
14803 ov-end (1+ ov-start))
14804 (skip-chars-forward "^\n\r")
14805 (setq ov-prefix
14806 (concat
14807 (buffer-substring (1- (point)) (point))
14808 (if (> (current-column) org-tags-column)
14810 (make-string (- org-tags-column (current-column)) ?\ ))))))
14811 (move-overlay org-tags-overlay ov-start ov-end)
14812 (save-window-excursion
14813 (if expert
14814 (set-buffer (get-buffer-create " *Org tags*"))
14815 (delete-other-windows)
14816 (split-window-vertically)
14817 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14818 (erase-buffer)
14819 (org-set-local 'org-done-keywords done-keywords)
14820 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14821 (org-fast-tag-insert "Current" current c-face "\n\n")
14822 (org-fast-tag-show-exit exit-after-next)
14823 (org-set-current-tags-overlay current ov-prefix)
14824 (setq tbl fulltable char ?a cnt 0)
14825 (while (setq e (pop tbl))
14826 (cond
14827 ((equal (car e) :startgroup)
14828 (push '() groups) (setq ingroup t)
14829 (when (not (= cnt 0))
14830 (setq cnt 0)
14831 (insert "\n"))
14832 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14833 ((equal (car e) :endgroup)
14834 (setq ingroup nil cnt 0)
14835 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14836 ((equal e '(:newline))
14837 (when (not (= cnt 0))
14838 (setq cnt 0)
14839 (insert "\n")
14840 (setq e (car tbl))
14841 (while (equal (car tbl) '(:newline))
14842 (insert "\n")
14843 (setq tbl (cdr tbl)))))
14844 ((equal e '(:grouptags)) nil)
14846 (setq tg (copy-sequence (car e)) c2 nil)
14847 (if (cdr e)
14848 (setq c (cdr e))
14849 ;; automatically assign a character.
14850 (setq c1 (string-to-char
14851 (downcase (substring
14852 tg (if (= (string-to-char tg) ?@) 1 0)))))
14853 (if (or (rassoc c1 ntable) (rassoc c1 table))
14854 (while (or (rassoc char ntable) (rassoc char table))
14855 (setq char (1+ char)))
14856 (setq c2 c1))
14857 (setq c (or c2 char)))
14858 (if ingroup (push tg (car groups)))
14859 (setq tg (org-add-props tg nil 'face
14860 (cond
14861 ((not (assoc tg table))
14862 (org-get-todo-face tg))
14863 ((member tg current) c-face)
14864 ((member tg inherited) i-face))))
14865 (if (equal (caar tbl) :grouptags)
14866 (org-add-props tg nil 'face 'org-tag-group))
14867 (if (and (= cnt 0) (not ingroup)) (insert " "))
14868 (insert "[" c "] " tg (make-string
14869 (- fwidth 4 (length tg)) ?\ ))
14870 (push (cons tg c) ntable)
14871 (when (= (setq cnt (1+ cnt)) ncol)
14872 (insert "\n")
14873 (if ingroup (insert " "))
14874 (setq cnt 0)))))
14875 (setq ntable (nreverse ntable))
14876 (insert "\n")
14877 (goto-char (point-min))
14878 (if (not expert) (org-fit-window-to-buffer))
14879 (setq rtn
14880 (catch 'exit
14881 (while t
14882 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14883 (if (not groups) "no " "")
14884 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14885 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14886 (setq org-last-tag-selection-key c)
14887 (cond
14888 ((= c ?\r) (throw 'exit t))
14889 ((= c ?!)
14890 (setq groups (not groups))
14891 (goto-char (point-min))
14892 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14893 ((= c ?\C-c)
14894 (if (not expert)
14895 (org-fast-tag-show-exit
14896 (setq exit-after-next (not exit-after-next)))
14897 (setq expert nil)
14898 (delete-other-windows)
14899 (set-window-buffer (split-window-vertically) " *Org tags*")
14900 (org-switch-to-buffer-other-window " *Org tags*")
14901 (org-fit-window-to-buffer)))
14902 ((or (= c ?\C-g)
14903 (and (= c ?q) (not (rassoc c ntable))))
14904 (org-detach-overlay org-tags-overlay)
14905 (setq quit-flag t))
14906 ((= c ?\ )
14907 (setq current nil)
14908 (if exit-after-next (setq exit-after-next 'now)))
14909 ((= c ?\t)
14910 (condition-case nil
14911 (setq tg (org-icompleting-read
14912 "Tag: "
14913 (or buffer-tags
14914 (with-current-buffer buf
14915 (org-get-buffer-tags)))))
14916 (quit (setq tg "")))
14917 (when (string-match "\\S-" tg)
14918 (add-to-list 'buffer-tags (list tg))
14919 (if (member tg current)
14920 (setq current (delete tg current))
14921 (push tg current)))
14922 (if exit-after-next (setq exit-after-next 'now)))
14923 ((setq e (rassoc c todo-table) tg (car e))
14924 (with-current-buffer buf
14925 (save-excursion (org-todo tg)))
14926 (if exit-after-next (setq exit-after-next 'now)))
14927 ((setq e (rassoc c ntable) tg (car e))
14928 (if (member tg current)
14929 (setq current (delete tg current))
14930 (loop for g in groups do
14931 (if (member tg g)
14932 (mapc (lambda (x)
14933 (setq current (delete x current)))
14934 g)))
14935 (push tg current))
14936 (if exit-after-next (setq exit-after-next 'now))))
14938 ;; Create a sorted list
14939 (setq current
14940 (sort current
14941 (lambda (a b)
14942 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14943 (if (eq exit-after-next 'now) (throw 'exit t))
14944 (goto-char (point-min))
14945 (beginning-of-line 2)
14946 (delete-region (point) (point-at-eol))
14947 (org-fast-tag-insert "Current" current c-face)
14948 (org-set-current-tags-overlay current ov-prefix)
14949 (while (re-search-forward
14950 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14951 (setq tg (match-string 1))
14952 (add-text-properties
14953 (match-beginning 1) (match-end 1)
14954 (list 'face
14955 (cond
14956 ((member tg current) c-face)
14957 ((member tg inherited) i-face)
14958 (t (get-text-property (match-beginning 1) 'face))))))
14959 (goto-char (point-min)))))
14960 (org-detach-overlay org-tags-overlay)
14961 (if rtn
14962 (mapconcat 'identity current ":")
14963 nil))))
14965 (defun org-get-tags-string ()
14966 "Get the TAGS string in the current headline."
14967 (unless (org-at-heading-p t)
14968 (user-error "Not on a heading"))
14969 (save-excursion
14970 (beginning-of-line 1)
14971 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14972 (org-match-string-no-properties 1)
14973 "")))
14975 (defun org-get-tags ()
14976 "Get the list of tags specified in the current headline."
14977 (org-split-string (org-get-tags-string) ":"))
14979 (defun org-get-buffer-tags ()
14980 "Get a table of all tags used in the buffer, for completion."
14981 (let (tags)
14982 (save-excursion
14983 (goto-char (point-min))
14984 (while (re-search-forward
14985 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14986 (when (equal (char-after (point-at-bol 0)) ?*)
14987 (mapc (lambda (x) (add-to-list 'tags x))
14988 (org-split-string (org-match-string-no-properties 1) ":")))))
14989 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14990 (mapcar 'list tags)))
14992 ;;;; The mapping API
14994 (defun org-map-entries (func &optional match scope &rest skip)
14995 "Call FUNC at each headline selected by MATCH in SCOPE.
14997 FUNC is a function or a lisp form. The function will be called without
14998 arguments, with the cursor positioned at the beginning of the headline.
14999 The return values of all calls to the function will be collected and
15000 returned as a list.
15002 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15003 does not need to preserve point. After evaluation, the cursor will be
15004 moved to the end of the line (presumably of the headline of the
15005 processed entry) and search continues from there. Under some
15006 circumstances, this may not produce the wanted results. For example,
15007 if you have removed (e.g. archived) the current (sub)tree it could
15008 mean that the next entry will be skipped entirely. In such cases, you
15009 can specify the position from where search should continue by making
15010 FUNC set the variable `org-map-continue-from' to the desired buffer
15011 position.
15013 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15014 Only headlines that are matched by this query will be considered during
15015 the iteration. When MATCH is nil or t, all headlines will be
15016 visited by the iteration.
15018 SCOPE determines the scope of this command. It can be any of:
15020 nil The current buffer, respecting the restriction if any
15021 tree The subtree started with the entry at point
15022 region The entries within the active region, if any
15023 region-start-level
15024 The entries within the active region, but only those at
15025 the same level than the first one.
15026 file The current buffer, without restriction
15027 file-with-archives
15028 The current buffer, and any archives associated with it
15029 agenda All agenda files
15030 agenda-with-archives
15031 All agenda files with any archive files associated with them
15032 \(file1 file2 ...)
15033 If this is a list, all files in the list will be scanned
15035 The remaining args are treated as settings for the skipping facilities of
15036 the scanner. The following items can be given here:
15038 archive skip trees with the archive tag
15039 comment skip trees with the COMMENT keyword
15040 function or Emacs Lisp form:
15041 will be used as value for `org-agenda-skip-function', so
15042 whenever the function returns a position, FUNC will not be
15043 called for that entry and search will continue from the
15044 position returned
15046 If your function needs to retrieve the tags including inherited tags
15047 at the *current* entry, you can use the value of the variable
15048 `org-scanner-tags' which will be much faster than getting the value
15049 with `org-get-tags-at'. If your function gets properties with
15050 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15051 to t around the call to `org-entry-properties' to get the same speedup.
15052 Note that if your function moves around to retrieve tags and properties at
15053 a *different* entry, you cannot use these techniques."
15054 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15055 (not (org-region-active-p)))
15056 (let* ((org-agenda-archives-mode nil) ; just to make sure
15057 (org-agenda-skip-archived-trees (memq 'archive skip))
15058 (org-agenda-skip-comment-trees (memq 'comment skip))
15059 (org-agenda-skip-function
15060 (car (org-delete-all '(comment archive) skip)))
15061 (org-tags-match-list-sublevels t)
15062 (start-level (eq scope 'region-start-level))
15063 matcher file res
15064 org-todo-keywords-for-agenda
15065 org-done-keywords-for-agenda
15066 org-todo-keyword-alist-for-agenda
15067 org-tag-alist-for-agenda
15068 todo-only)
15070 (cond
15071 ((eq match t) (setq matcher t))
15072 ((eq match nil) (setq matcher t))
15073 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15075 (save-window-excursion
15076 (save-restriction
15077 (cond ((eq scope 'tree)
15078 (org-back-to-heading t)
15079 (org-narrow-to-subtree)
15080 (setq scope nil))
15081 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15082 (org-region-active-p))
15083 ;; If needed, set start-level to a string like "2"
15084 (when start-level
15085 (save-excursion
15086 (goto-char (region-beginning))
15087 (unless (org-at-heading-p) (outline-next-heading))
15088 (setq start-level (org-current-level))))
15089 (narrow-to-region (region-beginning)
15090 (save-excursion
15091 (goto-char (region-end))
15092 (unless (and (bolp) (org-at-heading-p))
15093 (outline-next-heading))
15094 (point)))
15095 (setq scope nil)))
15097 (if (not scope)
15098 (progn
15099 (org-agenda-prepare-buffers
15100 (list (buffer-file-name (current-buffer))))
15101 (setq res (org-scan-tags func matcher todo-only start-level)))
15102 ;; Get the right scope
15103 (cond
15104 ((and scope (listp scope) (symbolp (car scope)))
15105 (setq scope (eval scope)))
15106 ((eq scope 'agenda)
15107 (setq scope (org-agenda-files t)))
15108 ((eq scope 'agenda-with-archives)
15109 (setq scope (org-agenda-files t))
15110 (setq scope (org-add-archive-files scope)))
15111 ((eq scope 'file)
15112 (setq scope (list (buffer-file-name))))
15113 ((eq scope 'file-with-archives)
15114 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15115 (org-agenda-prepare-buffers scope)
15116 (while (setq file (pop scope))
15117 (with-current-buffer (org-find-base-buffer-visiting file)
15118 (save-excursion
15119 (save-restriction
15120 (widen)
15121 (goto-char (point-min))
15122 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
15123 res)))
15125 ;;;; Properties
15127 ;;; Setting and retrieving properties
15129 (defconst org-special-properties
15130 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
15131 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
15132 "The special properties valid in Org-mode.
15134 These are properties that are not defined in the property drawer,
15135 but in some other way.")
15137 (defconst org-default-properties
15138 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15139 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15140 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15141 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15142 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
15143 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15144 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15145 "Some properties that are used by Org-mode for various purposes.
15146 Being in this list makes sure that they are offered for completion.")
15148 (defun org-property-action ()
15149 "Do an action on properties."
15150 (interactive)
15151 (let (c)
15152 (org-at-property-p)
15153 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15154 (setq c (read-char-exclusive))
15155 (cond
15156 ((equal c ?s)
15157 (call-interactively 'org-set-property))
15158 ((equal c ?d)
15159 (call-interactively 'org-delete-property))
15160 ((equal c ?D)
15161 (call-interactively 'org-delete-property-globally))
15162 ((equal c ?c)
15163 (call-interactively 'org-compute-property-at-point))
15164 (t (user-error "No such property action %c" c)))))
15166 (defun org-inc-effort ()
15167 "Increment the value of the effort property in the current entry."
15168 (interactive)
15169 (org-set-effort nil t))
15171 (defvar org-clock-effort) ;; Defined in org-clock.el
15172 (defvar org-clock-current-task) ;; Defined in org-clock.el
15173 (defun org-set-effort (&optional value increment)
15174 "Set the effort property of the current entry.
15175 With numerical prefix arg, use the nth allowed value, 0 stands for the
15176 10th allowed value.
15178 When INCREMENT is non-nil, set the property to the next allowed value."
15179 (interactive "P")
15180 (if (equal value 0) (setq value 10))
15181 (let* ((completion-ignore-case t)
15182 (prop org-effort-property)
15183 (cur (org-entry-get nil prop))
15184 (allowed (org-property-get-allowed-values nil prop 'table))
15185 (existing (mapcar 'list (org-property-values prop)))
15186 (heading (nth 4 (org-heading-components)))
15188 (val (cond
15189 ((stringp value) value)
15190 ((and allowed (integerp value))
15191 (or (car (nth (1- value) allowed))
15192 (car (org-last allowed))))
15193 ((and allowed increment)
15194 (or (caadr (member (list cur) allowed))
15195 (user-error "Allowed effort values are not set")))
15196 (allowed
15197 (message "Select 1-9,0, [RET%s]: %s"
15198 (if cur (concat "=" cur) "")
15199 (mapconcat 'car allowed " "))
15200 (setq rpl (read-char-exclusive))
15201 (if (equal rpl ?\r)
15203 (setq rpl (- rpl ?0))
15204 (if (equal rpl 0) (setq rpl 10))
15205 (if (and (> rpl 0) (<= rpl (length allowed)))
15206 (car (nth (1- rpl) allowed))
15207 (org-completing-read "Effort: " allowed nil))))
15209 (let (org-completion-use-ido org-completion-use-iswitchb)
15210 (org-completing-read
15211 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15212 (concat "[" cur "]") "")
15213 ": ")
15214 existing nil nil "" nil cur))))))
15215 (unless (equal (org-entry-get nil prop) val)
15216 (org-entry-put nil prop val))
15217 (save-excursion
15218 (org-back-to-heading t)
15219 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
15220 (when (string= heading org-clock-current-task)
15221 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
15222 (org-clock-update-mode-line))
15223 (message "%s is now %s" prop val)))
15225 (defun org-at-property-p ()
15226 "Is cursor inside a property drawer?"
15227 (save-excursion
15228 (when (equal 'node-property (car (org-element-at-point)))
15229 (beginning-of-line 1)
15230 (looking-at org-property-re))))
15232 (defun org-get-property-block (&optional beg end force)
15233 "Return the (beg . end) range of the body of the property drawer.
15234 BEG and END are the beginning and end of the current subtree, or of
15235 the part before the first headline. If they are not given, they will
15236 be found. If the drawer does not exist and FORCE is non-nil, create
15237 the drawer."
15238 (catch 'exit
15239 (save-excursion
15240 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15241 (progn (org-back-to-heading t) (point))))
15242 (end (or end (and (not (outline-next-heading)) (point-max))
15243 (point))))
15244 (goto-char beg)
15245 (if (re-search-forward org-property-start-re end t)
15246 (setq beg (1+ (match-end 0)))
15247 (if force
15248 (save-excursion
15249 (org-insert-property-drawer)
15250 (setq end (progn (outline-next-heading) (point))))
15251 (throw 'exit nil))
15252 (goto-char beg)
15253 (if (re-search-forward org-property-start-re end t)
15254 (setq beg (1+ (match-end 0)))))
15255 (if (re-search-forward org-property-end-re end t)
15256 (setq end (match-beginning 0))
15257 (or force (throw 'exit nil))
15258 (goto-char beg)
15259 (setq end beg)
15260 (org-indent-line)
15261 (insert ":END:\n"))
15262 (cons beg end)))))
15264 (defun org-entry-properties (&optional pom which specific)
15265 "Get all properties of the entry at point-or-marker POM.
15266 This includes the TODO keyword, the tags, time strings for deadline,
15267 scheduled, and clocking, and any additional properties defined in the
15268 entry. The return value is an alist, keys may occur multiple times
15269 if the property key was used several times.
15270 POM may also be nil, in which case the current entry is used.
15271 If WHICH is nil or `all', get all properties. If WHICH is
15272 `special' or `standard', only get that subclass. If WHICH
15273 is a string only get exactly this property. SPECIFIC can be a string, the
15274 specific property we are interested in. Specifying it can speed
15275 things up because then unnecessary parsing is avoided."
15276 (setq which (or which 'all))
15277 (org-with-wide-buffer
15278 (org-with-point-at pom
15279 (let ((clockstr (substring org-clock-string 0 -1))
15280 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15281 (case-fold-search nil)
15282 beg end range props sum-props key key1 value string clocksum clocksumt)
15283 (when (and (derived-mode-p 'org-mode)
15284 (ignore-errors (org-back-to-heading t)))
15285 (setq beg (point))
15286 (setq sum-props (get-text-property (point) 'org-summaries))
15287 (setq clocksum (get-text-property (point) :org-clock-minutes)
15288 clocksumt (get-text-property (point) :org-clock-minutes-today))
15289 (outline-next-heading)
15290 (setq end (point))
15291 (when (memq which '(all special))
15292 ;; Get the special properties, like TODO and tags
15293 (goto-char beg)
15294 (when (and (or (not specific) (string= specific "TODO"))
15295 (looking-at org-todo-line-regexp) (match-end 2))
15296 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15297 (when (and (or (not specific) (string= specific "PRIORITY"))
15298 (looking-at org-priority-regexp))
15299 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15300 (when (or (not specific) (string= specific "FILE"))
15301 (push (cons "FILE" buffer-file-name) props))
15302 (when (and (or (not specific) (string= specific "TAGS"))
15303 (setq value (org-get-tags-string))
15304 (string-match "\\S-" value))
15305 (push (cons "TAGS" value) props))
15306 (when (and (or (not specific) (string= specific "ALLTAGS"))
15307 (setq value (org-get-tags-at)))
15308 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15309 ":"))
15310 props))
15311 (when (or (not specific) (string= specific "BLOCKED"))
15312 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15313 (when (or (not specific)
15314 (member specific
15315 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15316 "TIMESTAMP" "TIMESTAMP_IA")))
15317 (catch 'match
15318 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15319 (setq key (if (match-end 1)
15320 (substring (org-match-string-no-properties 1)
15321 0 -1))
15322 string (if (equal key clockstr)
15323 (org-trim
15324 (buffer-substring-no-properties
15325 (match-beginning 3) (goto-char
15326 (point-at-eol))))
15327 (substring (org-match-string-no-properties 3)
15328 1 -1)))
15329 ;; Get the correct property name from the key. This is
15330 ;; necessary if the user has configured time keywords.
15331 (setq key1 (concat key ":"))
15332 (cond
15333 ((not key)
15334 (setq key
15335 (if (= (char-after (match-beginning 3)) ?\[)
15336 "TIMESTAMP_IA" "TIMESTAMP")))
15337 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15338 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15339 ((equal key1 org-closed-string) (setq key "CLOSED"))
15340 ((equal key1 org-clock-string) (setq key "CLOCK")))
15341 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15342 (progn
15343 (push (cons key string) props)
15344 ;; no need to search further if match is found
15345 (throw 'match t))
15346 (when (or (equal key "CLOCK") (not (assoc key props)))
15347 (push (cons key string) props)))))))
15349 (when (memq which '(all standard))
15350 ;; Get the standard properties, like :PROP: ...
15351 (setq range (org-get-property-block beg end))
15352 (when range
15353 (goto-char (car range))
15354 (while (re-search-forward org-property-re
15355 (cdr range) t)
15356 (setq key (org-match-string-no-properties 2)
15357 value (org-trim (or (org-match-string-no-properties 3) "")))
15358 (unless (member key excluded)
15359 (push (cons key (or value "")) props)))))
15360 (if clocksum
15361 (push (cons "CLOCKSUM"
15362 (org-columns-number-to-string (/ (float clocksum) 60.)
15363 'add_times))
15364 props))
15365 (if clocksumt
15366 (push (cons "CLOCKSUM_T"
15367 (org-columns-number-to-string (/ (float clocksumt) 60.)
15368 'add_times))
15369 props))
15370 (unless (assoc "CATEGORY" props)
15371 (push (cons "CATEGORY" (org-get-category)) props))
15372 (append sum-props (nreverse props)))))))
15374 (defun org-entry-get (pom property &optional inherit literal-nil)
15375 "Get value of PROPERTY for entry or content at point-or-marker POM.
15376 If INHERIT is non-nil and the entry does not have the property,
15377 then also check higher levels of the hierarchy.
15378 If INHERIT is the symbol `selective', use inheritance only if the setting
15379 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15380 If the property is present but empty, the return value is the empty string.
15381 If the property is not present at all, nil is returned.
15383 Return the value as a string.
15385 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15386 do not interpret it as the list atom nil. This is used for inheritance
15387 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15388 (org-with-point-at pom
15389 (if (and inherit (if (eq inherit 'selective)
15390 (org-property-inherit-p property)
15392 (org-entry-get-with-inheritance property literal-nil)
15393 (if (member property org-special-properties)
15394 ;; We need a special property. Use `org-entry-properties'
15395 ;; to retrieve it, but specify the wanted property
15396 (cdr (assoc property (org-entry-properties nil 'special property)))
15397 (org-with-wide-buffer
15398 (let ((range (org-get-property-block)))
15399 (when (and range (not (eq (car range) (cdr range))))
15400 (let* ((props
15401 (list (or (assoc property org-file-properties)
15402 (assoc property org-global-properties)
15403 (assoc property org-global-properties-fixed))))
15404 (ap (lambda (key)
15405 (when (re-search-forward
15406 (org-re-property key) (cdr range) t)
15407 (setq props
15408 (org-update-property-plist
15410 (if (match-end 3)
15411 (org-match-string-no-properties 3) "")
15412 props)))))
15413 val)
15414 (goto-char (car range))
15415 (funcall ap property)
15416 (goto-char (car range))
15417 (while (funcall ap (concat property "+")))
15418 (setq val (cdr (assoc property props)))
15419 (when val (if literal-nil val (org-not-nil val)))))))))))
15421 (defun org-property-or-variable-value (var &optional inherit)
15422 "Check if there is a property fixing the value of VAR.
15423 If yes, return this value. If not, return the current value of the variable."
15424 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15425 (if (and prop (stringp prop) (string-match "\\S-" prop))
15426 (read prop)
15427 (symbol-value var))))
15429 (defun org-entry-delete (pom property)
15430 "Delete the property PROPERTY from entry at point-or-marker POM."
15431 (unless (member property org-special-properties)
15432 (org-with-point-at pom
15433 (let ((range (org-get-property-block)))
15434 (if (and range
15435 (goto-char (car range))
15436 (re-search-forward
15437 (org-re-property property)
15438 (cdr range) t))
15439 (progn
15440 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15441 (org-remove-empty-drawer-at (car range))
15443 nil)))))
15445 ;; Multi-values properties are properties that contain multiple values
15446 ;; These values are assumed to be single words, separated by whitespace.
15447 (defun org-entry-add-to-multivalued-property (pom property value)
15448 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15449 (let* ((old (org-entry-get pom property))
15450 (values (and old (org-split-string old "[ \t]"))))
15451 (setq value (org-entry-protect-space value))
15452 (unless (member value values)
15453 (setq values (append values (list value)))
15454 (org-entry-put pom property
15455 (mapconcat 'identity values " ")))))
15457 (defun org-entry-remove-from-multivalued-property (pom property value)
15458 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15459 (let* ((old (org-entry-get pom property))
15460 (values (and old (org-split-string old "[ \t]"))))
15461 (setq value (org-entry-protect-space value))
15462 (when (member value values)
15463 (setq values (delete value values))
15464 (org-entry-put pom property
15465 (mapconcat 'identity values " ")))))
15467 (defun org-entry-member-in-multivalued-property (pom property value)
15468 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15469 (let* ((old (org-entry-get pom property))
15470 (values (and old (org-split-string old "[ \t]"))))
15471 (setq value (org-entry-protect-space value))
15472 (member value values)))
15474 (defun org-entry-get-multivalued-property (pom property)
15475 "Return a list of values in a multivalued property."
15476 (let* ((value (org-entry-get pom property))
15477 (values (and value (org-split-string value "[ \t]"))))
15478 (mapcar 'org-entry-restore-space values)))
15480 (defun org-entry-put-multivalued-property (pom property &rest values)
15481 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15482 VALUES should be a list of strings. Spaces will be protected."
15483 (org-entry-put pom property
15484 (mapconcat 'org-entry-protect-space values " "))
15485 (let* ((value (org-entry-get pom property))
15486 (values (and value (org-split-string value "[ \t]"))))
15487 (mapcar 'org-entry-restore-space values)))
15489 (defun org-entry-protect-space (s)
15490 "Protect spaces and newline in string S."
15491 (while (string-match " " s)
15492 (setq s (replace-match "%20" t t s)))
15493 (while (string-match "\n" s)
15494 (setq s (replace-match "%0A" t t s)))
15497 (defun org-entry-restore-space (s)
15498 "Restore spaces and newline in string S."
15499 (while (string-match "%20" s)
15500 (setq s (replace-match " " t t s)))
15501 (while (string-match "%0A" s)
15502 (setq s (replace-match "\n" t t s)))
15505 (defvar org-entry-property-inherited-from (make-marker)
15506 "Marker pointing to the entry from where a property was inherited.
15507 Each call to `org-entry-get-with-inheritance' will set this marker to the
15508 location of the entry where the inheritance search matched. If there was
15509 no match, the marker will point nowhere.
15510 Note that also `org-entry-get' calls this function, if the INHERIT flag
15511 is set.")
15513 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15514 "Get PROPERTY of entry or content at point, search higher levels if needed.
15515 The search will stop at the first ancestor which has the property defined.
15516 If the value found is \"nil\", return nil to show that the property
15517 should be considered as undefined (this is the meaning of nil here).
15518 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15519 (move-marker org-entry-property-inherited-from nil)
15520 (let (tmp)
15521 (save-excursion
15522 (save-restriction
15523 (widen)
15524 (catch 'ex
15525 (while t
15526 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
15527 (or (ignore-errors (org-back-to-heading t))
15528 (goto-char (point-min)))
15529 (move-marker org-entry-property-inherited-from (point))
15530 (throw 'ex tmp))
15531 (or (ignore-errors (org-up-heading-safe))
15532 (throw 'ex nil))))))
15533 (setq tmp (or tmp
15534 (cdr (assoc property org-file-properties))
15535 (cdr (assoc property org-global-properties))
15536 (cdr (assoc property org-global-properties-fixed))))
15537 (if literal-nil tmp (org-not-nil tmp))))
15539 (defvar org-property-changed-functions nil
15540 "Hook called when the value of a property has changed.
15541 Each hook function should accept two arguments, the name of the property
15542 and the new value.")
15544 (defun org-entry-put (pom property value)
15545 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15546 If the value is `nil', it is converted to the empty string.
15547 If it is not a string, an error is raised."
15548 (cond ((null value) (setq value ""))
15549 ((not (stringp value))
15550 (error "Properties values should be strings.")))
15551 (org-with-point-at pom
15552 (org-back-to-heading t)
15553 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15554 range)
15555 (cond
15556 ((equal property "TODO")
15557 (when (and (string-match "\\S-" value)
15558 (not (member value org-todo-keywords-1)))
15559 (user-error "\"%s\" is not a valid TODO state" value))
15560 (if (or (not value)
15561 (not (string-match "\\S-" value)))
15562 (setq value 'none))
15563 (org-todo value)
15564 (org-set-tags nil 'align))
15565 ((equal property "PRIORITY")
15566 (org-priority (if (and value (string-match "\\S-" value))
15567 (string-to-char value) ?\ ))
15568 (org-set-tags nil 'align))
15569 ((equal property "CLOCKSUM")
15570 (if (not (re-search-forward
15571 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15572 (error "Cannot find a clock log")
15573 (goto-char (- (match-end 1) 2))
15574 (cond
15575 ((eq value 'earlier) (org-timestamp-down))
15576 ((eq value 'later) (org-timestamp-up)))
15577 (org-clock-sum-current-item)))
15578 ((equal property "SCHEDULED")
15579 (if (re-search-forward org-scheduled-time-regexp end t)
15580 (cond
15581 ((eq value 'earlier) (org-timestamp-change -1 'day))
15582 ((eq value 'later) (org-timestamp-change 1 'day))
15583 (t (call-interactively 'org-schedule)))
15584 (call-interactively 'org-schedule)))
15585 ((equal property "DEADLINE")
15586 (if (re-search-forward org-deadline-time-regexp end t)
15587 (cond
15588 ((eq value 'earlier) (org-timestamp-change -1 'day))
15589 ((eq value 'later) (org-timestamp-change 1 'day))
15590 (t (call-interactively 'org-deadline)))
15591 (call-interactively 'org-deadline)))
15592 ((member property org-special-properties)
15593 (error "The %s property can not yet be set with `org-entry-put'"
15594 property))
15595 (t ; a non-special property
15596 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15597 (setq range (org-get-property-block beg end 'force))
15598 (goto-char (car range))
15599 (if (re-search-forward
15600 (org-re-property property) (cdr range) t)
15601 (progn
15602 (delete-region (match-beginning 0) (match-end 0))
15603 (goto-char (match-beginning 0)))
15604 (goto-char (cdr range))
15605 (insert "\n")
15606 (backward-char 1)
15607 (org-indent-line))
15608 (insert ":" property ":")
15609 (and value (insert " " value))
15610 (org-indent-line)))))
15611 (run-hook-with-args 'org-property-changed-functions property value)))
15613 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15614 "Get all property keys in the current buffer.
15615 With INCLUDE-SPECIALS, also list the special properties that reflect things
15616 like tags and TODO state.
15617 With INCLUDE-DEFAULTS, also include properties that has special meaning
15618 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15619 and others.
15620 With INCLUDE-COLUMNS, also include property names given in COLUMN
15621 formats in the current buffer."
15622 (let (rtn range cfmt s p)
15623 (save-excursion
15624 (save-restriction
15625 (widen)
15626 (goto-char (point-min))
15627 (while (re-search-forward org-property-start-re nil t)
15628 (setq range (org-get-property-block))
15629 (goto-char (car range))
15630 (while (re-search-forward org-property-re
15631 (cdr range) t)
15632 (add-to-list 'rtn (org-match-string-no-properties 2)))
15633 (outline-next-heading))))
15635 (when include-specials
15636 (setq rtn (append org-special-properties rtn)))
15638 (when include-defaults
15639 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15640 (add-to-list 'rtn org-effort-property))
15642 (when include-columns
15643 (save-excursion
15644 (save-restriction
15645 (widen)
15646 (goto-char (point-min))
15647 (while (re-search-forward
15648 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15649 nil t)
15650 (setq cfmt (match-string 2) s 0)
15651 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15652 cfmt s)
15653 (setq s (match-end 0)
15654 p (match-string 1 cfmt))
15655 (unless (or (equal p "ITEM")
15656 (member p org-special-properties))
15657 (add-to-list 'rtn (match-string 1 cfmt))))))))
15659 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15661 (defun org-property-values (key)
15662 "Return a list of all values of property KEY in the current buffer."
15663 (save-excursion
15664 (save-restriction
15665 (widen)
15666 (goto-char (point-min))
15667 (let ((re (org-re-property key))
15668 values)
15669 (while (re-search-forward re nil t)
15670 (add-to-list 'values (org-trim (match-string 3))))
15671 (delete "" values)))))
15673 (defun org-insert-property-drawer ()
15674 "Insert a property drawer into the current entry."
15675 (org-back-to-heading t)
15676 (looking-at org-outline-regexp)
15677 (let ((indent (if org-adapt-indentation
15678 (- (match-end 0) (match-beginning 0))
15680 (beg (point))
15681 (re (concat "^[ \t]*" org-keyword-time-regexp))
15682 end hiddenp)
15683 (outline-next-heading)
15684 (setq end (point))
15685 (goto-char beg)
15686 (while (re-search-forward re end t))
15687 (setq hiddenp (outline-invisible-p))
15688 (end-of-line 1)
15689 (and (equal (char-after) ?\n) (forward-char 1))
15690 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15691 (if (member (match-string 1) '("CLOCK:" ":END:"))
15692 ;; just skip this line
15693 (beginning-of-line 2)
15694 ;; Drawer start, find the end
15695 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15696 (beginning-of-line 1)))
15697 (org-skip-over-state-notes)
15698 (skip-chars-backward " \t\n\r")
15699 (if (and (eq (char-before) ?*) (not (eq (char-after) ?\n)))
15700 (forward-char 1))
15701 (goto-char (point-at-eol))
15702 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15703 (beginning-of-line 0)
15704 (org-indent-to-column indent)
15705 (beginning-of-line 2)
15706 (org-indent-to-column indent)
15707 (beginning-of-line 0)
15708 (if hiddenp
15709 (save-excursion
15710 (org-back-to-heading t)
15711 (hide-entry))
15712 (org-flag-drawer t))))
15714 (defun org-insert-drawer (&optional arg drawer)
15715 "Insert a drawer at point.
15717 Optional argument DRAWER, when non-nil, is a string representing
15718 drawer's name. Otherwise, the user is prompted for a name.
15720 If a region is active, insert the drawer around that region
15721 instead.
15723 Point is left between drawer's boundaries."
15724 (interactive "P")
15725 (let* ((drawer (if arg "PROPERTIES"
15726 (or drawer (read-from-minibuffer "Drawer: ")))))
15727 (cond
15728 ;; With C-u, fall back on `org-insert-property-drawer'
15729 (arg (org-insert-property-drawer))
15731 ((not (org-string-match-p org-drawer-regexp (format ":%s:" drawer)))
15732 (user-error "Invalid drawer name"))
15733 ;; With an active region, insert a drawer at point.
15734 ((not (org-region-active-p))
15735 (progn
15736 (unless (bolp) (insert "\n"))
15737 (insert (format ":%s:\n\n:END:\n" drawer))
15738 (forward-line -2)))
15739 ;; Otherwise, insert the drawer at point
15741 (let ((rbeg (region-beginning))
15742 (rend (copy-marker (region-end))))
15743 (unwind-protect
15744 (progn
15745 (goto-char rbeg)
15746 (beginning-of-line)
15747 (when (save-excursion
15748 (re-search-forward org-outline-regexp-bol rend t))
15749 (user-error "Drawers cannot contain headlines"))
15750 ;; Position point at the beginning of the first
15751 ;; non-blank line in region. Insert drawer's opening
15752 ;; there, then indent it.
15753 (org-skip-whitespace)
15754 (beginning-of-line)
15755 (insert ":" drawer ":\n")
15756 (forward-line -1)
15757 (indent-for-tab-command)
15758 ;; Move point to the beginning of the first blank line
15759 ;; after the last non-blank line in region. Insert
15760 ;; drawer's closing, then indent it.
15761 (goto-char rend)
15762 (skip-chars-backward " \r\t\n")
15763 (insert "\n:END:")
15764 (deactivate-mark t)
15765 (indent-for-tab-command)
15766 (unless (eolp) (insert "\n")))
15767 ;; Clear marker, whatever the outcome of insertion is.
15768 (set-marker rend nil)))))))
15770 (defvar org-property-set-functions-alist nil
15771 "Property set function alist.
15772 Each entry should have the following format:
15774 (PROPERTY . READ-FUNCTION)
15776 The read function will be called with the same argument as
15777 `org-completing-read'.")
15779 (defun org-set-property-function (property)
15780 "Get the function that should be used to set PROPERTY.
15781 This is computed according to `org-property-set-functions-alist'."
15782 (or (cdr (assoc property org-property-set-functions-alist))
15783 'org-completing-read))
15785 (defun org-read-property-value (property)
15786 "Read PROPERTY value from user."
15787 (let* ((completion-ignore-case t)
15788 (allowed (org-property-get-allowed-values nil property 'table))
15789 (cur (org-entry-get nil property))
15790 (prompt (concat property " value"
15791 (if (and cur (string-match "\\S-" cur))
15792 (concat " [" cur "]") "") ": "))
15793 (set-function (org-set-property-function property))
15794 (val (if allowed
15795 (funcall set-function prompt allowed nil
15796 (not (get-text-property 0 'org-unrestricted
15797 (caar allowed))))
15798 (let (org-completion-use-ido org-completion-use-iswitchb)
15799 (funcall set-function prompt
15800 (mapcar 'list (org-property-values property))
15801 nil nil "" nil cur)))))
15802 (if (equal val "")
15804 val)))
15806 (defvar org-last-set-property nil)
15807 (defvar org-last-set-property-value nil)
15808 (defun org-read-property-name ()
15809 "Read a property name."
15810 (let* ((completion-ignore-case t)
15811 (keys (org-buffer-property-keys nil t t))
15812 (default-prop (or (save-excursion
15813 (save-match-data
15814 (beginning-of-line)
15815 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15816 (null (string= (match-string 1) "END"))
15817 (match-string 1))))
15818 org-last-set-property))
15819 (property (org-icompleting-read
15820 (concat "Property"
15821 (if default-prop (concat " [" default-prop "]") "")
15822 ": ")
15823 (mapcar 'list keys)
15824 nil nil nil nil
15825 default-prop)))
15826 (if (member property keys)
15827 property
15828 (or (cdr (assoc (downcase property)
15829 (mapcar (lambda (x) (cons (downcase x) x))
15830 keys)))
15831 property))))
15833 (defun org-set-property-and-value (use-last)
15834 "Allow to set [PROPERTY]: [value] direction from prompt.
15835 When use-default, don't even ask, just use the last
15836 \"[PROPERTY]: [value]\" string from the history."
15837 (interactive "P")
15838 (let* ((completion-ignore-case t)
15839 (pv (or (and use-last org-last-set-property-value)
15840 (org-completing-read
15841 "Enter a \"[Property]: [value]\" pair: "
15842 nil nil nil nil nil
15843 org-last-set-property-value)))
15844 prop val)
15845 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15846 (setq prop (match-string 1 pv)
15847 val (match-string 2 pv))
15848 (org-set-property prop val))))
15850 (defun org-set-property (property value)
15851 "In the current entry, set PROPERTY to VALUE.
15852 When called interactively, this will prompt for a property name, offering
15853 completion on existing and default properties. And then it will prompt
15854 for a value, offering completion either on allowed values (via an inherited
15855 xxx_ALL property) or on existing values in other instances of this property
15856 in the current file."
15857 (interactive (list nil nil))
15858 (let* ((property (or property (org-read-property-name)))
15859 (value (or value (org-read-property-value property)))
15860 (fn (cdr (assoc property org-properties-postprocess-alist))))
15861 (setq org-last-set-property property)
15862 (setq org-last-set-property-value (concat property ": " value))
15863 ;; Possibly postprocess the inserted value:
15864 (when fn (setq value (funcall fn value)))
15865 (unless (equal (org-entry-get nil property) value)
15866 (org-entry-put nil property value))))
15868 (defun org-delete-property (property)
15869 "In the current entry, delete PROPERTY."
15870 (interactive
15871 (let* ((completion-ignore-case t)
15872 (prop (org-icompleting-read "Property: "
15873 (org-entry-properties nil 'standard))))
15874 (list prop)))
15875 (message "Property %s %s" property
15876 (if (org-entry-delete nil property)
15877 "deleted"
15878 "was not present in the entry")))
15880 (defun org-delete-property-globally (property)
15881 "Remove PROPERTY globally, from all entries."
15882 (interactive
15883 (let* ((completion-ignore-case t)
15884 (prop (org-icompleting-read
15885 "Globally remove property: "
15886 (mapcar 'list (org-buffer-property-keys)))))
15887 (list prop)))
15888 (save-excursion
15889 (save-restriction
15890 (widen)
15891 (goto-char (point-min))
15892 (let ((cnt 0))
15893 (while (re-search-forward
15894 (org-re-property property)
15895 nil t)
15896 (setq cnt (1+ cnt))
15897 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15898 (message "Property \"%s\" removed from %d entries" property cnt)))))
15900 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15902 (defun org-compute-property-at-point ()
15903 "Compute the property at point.
15904 This looks for an enclosing column format, extracts the operator and
15905 then applies it to the property in the column format's scope."
15906 (interactive)
15907 (unless (org-at-property-p)
15908 (user-error "Not at a property"))
15909 (let ((prop (org-match-string-no-properties 2)))
15910 (org-columns-get-format-and-top-level)
15911 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15912 (user-error "No operator defined for property %s" prop))
15913 (org-columns-compute prop)))
15915 (defvar org-property-allowed-value-functions nil
15916 "Hook for functions supplying allowed values for a specific property.
15917 The functions must take a single argument, the name of the property, and
15918 return a flat list of allowed values. If \":ETC\" is one of
15919 the values, this means that these values are intended as defaults for
15920 completion, but that other values should be allowed too.
15921 The functions must return nil if they are not responsible for this
15922 property.")
15924 (defun org-property-get-allowed-values (pom property &optional table)
15925 "Get allowed values for the property PROPERTY.
15926 When TABLE is non-nil, return an alist that can directly be used for
15927 completion."
15928 (let (vals)
15929 (cond
15930 ((equal property "TODO")
15931 (setq vals (org-with-point-at pom
15932 (append org-todo-keywords-1 '("")))))
15933 ((equal property "PRIORITY")
15934 (let ((n org-lowest-priority))
15935 (while (>= n org-highest-priority)
15936 (push (char-to-string n) vals)
15937 (setq n (1- n)))))
15938 ((member property org-special-properties))
15939 ((setq vals (run-hook-with-args-until-success
15940 'org-property-allowed-value-functions property)))
15942 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15943 (when (and vals (string-match "\\S-" vals))
15944 (setq vals (car (read-from-string (concat "(" vals ")"))))
15945 (setq vals (mapcar (lambda (x)
15946 (cond ((stringp x) x)
15947 ((numberp x) (number-to-string x))
15948 ((symbolp x) (symbol-name x))
15949 (t "???")))
15950 vals)))))
15951 (when (member ":ETC" vals)
15952 (setq vals (remove ":ETC" vals))
15953 (org-add-props (car vals) '(org-unrestricted t)))
15954 (if table (mapcar 'list vals) vals)))
15956 (defun org-property-previous-allowed-value (&optional previous)
15957 "Switch to the next allowed value for this property."
15958 (interactive)
15959 (org-property-next-allowed-value t))
15961 (defun org-property-next-allowed-value (&optional previous)
15962 "Switch to the next allowed value for this property."
15963 (interactive)
15964 (unless (org-at-property-p)
15965 (user-error "Not at a property"))
15966 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15967 (key (match-string 2))
15968 (value (match-string 3))
15969 (allowed (or (org-property-get-allowed-values (point) key)
15970 (and (member value '("[ ]" "[-]" "[X]"))
15971 '("[ ]" "[X]"))))
15972 (heading (save-match-data (nth 4 (org-heading-components))))
15973 nval)
15974 (unless allowed
15975 (user-error "Allowed values for this property have not been defined"))
15976 (if previous (setq allowed (reverse allowed)))
15977 (if (member value allowed)
15978 (setq nval (car (cdr (member value allowed)))))
15979 (setq nval (or nval (car allowed)))
15980 (if (equal nval value)
15981 (user-error "Only one allowed value for this property"))
15982 (org-at-property-p)
15983 (replace-match (concat " :" key ": " nval) t t)
15984 (org-indent-line)
15985 (beginning-of-line 1)
15986 (skip-chars-forward " \t")
15987 (when (equal prop org-effort-property)
15988 (save-excursion
15989 (org-back-to-heading t)
15990 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
15991 (when (string= org-clock-current-task heading)
15992 (setq org-clock-effort nval)
15993 (org-clock-update-mode-line)))
15994 (run-hook-with-args 'org-property-changed-functions key nval)))
15996 (defun org-find-olp (path &optional this-buffer)
15997 "Return a marker pointing to the entry at outline path OLP.
15998 If anything goes wrong, throw an error.
15999 You can wrap this call to catch the error like this:
16001 (condition-case msg
16002 (org-mobile-locate-entry (match-string 4))
16003 (error (nth 1 msg)))
16005 The return value will then be either a string with the error message,
16006 or a marker if everything is OK.
16008 If THIS-BUFFER is set, the outline path does not contain a file,
16009 only headings."
16010 (let* ((file (if this-buffer buffer-file-name (pop path)))
16011 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16012 (level 1)
16013 (lmin 1)
16014 (lmax 1)
16015 limit re end found pos heading cnt flevel)
16016 (unless buffer (error "File not found :%s" file))
16017 (with-current-buffer buffer
16018 (save-excursion
16019 (save-restriction
16020 (widen)
16021 (setq limit (point-max))
16022 (goto-char (point-min))
16023 (while (setq heading (pop path))
16024 (setq re (format org-complex-heading-regexp-format
16025 (regexp-quote heading)))
16026 (setq cnt 0 pos (point))
16027 (while (re-search-forward re end t)
16028 (setq level (- (match-end 1) (match-beginning 1)))
16029 (if (and (>= level lmin) (<= level lmax))
16030 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16031 (when (= cnt 0) (error "Heading not found on level %d: %s"
16032 lmax heading))
16033 (when (> cnt 1) (error "Heading not unique on level %d: %s"
16034 lmax heading))
16035 (goto-char found)
16036 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16037 (setq end (save-excursion (org-end-of-subtree t t))))
16038 (when (org-at-heading-p)
16039 (point-marker)))))))
16041 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16042 "Find node HEADING in BUFFER.
16043 Return a marker to the heading if it was found, or nil if not.
16044 If POS-ONLY is set, return just the position instead of a marker.
16046 The heading text must match exact, but it may have a TODO keyword,
16047 a priority cookie and tags in the standard locations."
16048 (with-current-buffer (or buffer (current-buffer))
16049 (save-excursion
16050 (save-restriction
16051 (widen)
16052 (goto-char (point-min))
16053 (let (case-fold-search)
16054 (if (re-search-forward
16055 (format org-complex-heading-regexp-format
16056 (regexp-quote heading)) nil t)
16057 (if pos-only
16058 (match-beginning 0)
16059 (move-marker (make-marker) (match-beginning 0)))))))))
16061 (defun org-find-exact-heading-in-directory (heading &optional dir)
16062 "Find Org node headline HEADING in all .org files in directory DIR.
16063 When the target headline is found, return a marker to this location."
16064 (let ((files (directory-files (or dir default-directory)
16065 nil "\\`[^.#].*\\.org\\'"))
16066 file visiting m buffer)
16067 (catch 'found
16068 (while (setq file (pop files))
16069 (message "trying %s" file)
16070 (setq visiting (org-find-base-buffer-visiting file))
16071 (setq buffer (or visiting (find-file-noselect file)))
16072 (setq m (org-find-exact-headline-in-buffer
16073 heading buffer))
16074 (when (and (not m) (not visiting)) (kill-buffer buffer))
16075 (and m (throw 'found m))))))
16077 (defun org-find-entry-with-id (ident)
16078 "Locate the entry that contains the ID property with exact value IDENT.
16079 IDENT can be a string, a symbol or a number, this function will search for
16080 the string representation of it.
16081 Return the position where this entry starts, or nil if there is no such entry."
16082 (interactive "sID: ")
16083 (let ((id (cond
16084 ((stringp ident) ident)
16085 ((symbol-name ident) (symbol-name ident))
16086 ((numberp ident) (number-to-string ident))
16087 (t (error "IDENT %s must be a string, symbol or number" ident))))
16088 (case-fold-search nil))
16089 (save-excursion
16090 (save-restriction
16091 (widen)
16092 (goto-char (point-min))
16093 (when (re-search-forward
16094 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16095 nil t)
16096 (org-back-to-heading t)
16097 (point))))))
16099 ;;;; Timestamps
16101 (defvar org-last-changed-timestamp nil)
16102 (defvar org-last-inserted-timestamp nil
16103 "The last time stamp inserted with `org-insert-time-stamp'.")
16104 (defvar org-ts-what) ; dynamically scoped parameter
16106 (defun org-time-stamp (arg &optional inactive)
16107 "Prompt for a date/time and insert a time stamp.
16108 If the user specifies a time like HH:MM or if this command is
16109 called with at least one prefix argument, the time stamp contains
16110 the date and the time. Otherwise, only the date is be included.
16112 All parts of a date not specified by the user is filled in from
16113 the current date/time. So if you just press return without
16114 typing anything, the time stamp will represent the current
16115 date/time.
16117 If there is already a timestamp at the cursor, it will be
16118 modified.
16120 With two universal prefix arguments, insert an active timestamp
16121 with the current time without prompting the user.
16123 When called from lisp, the timestamp is inactive if INACTIVE is
16124 non-nil."
16125 (interactive "P")
16126 (let* ((ts nil)
16127 (default-time
16128 ;; Default time is either today, or, when entering a range,
16129 ;; the range start.
16130 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16131 (save-excursion
16132 (re-search-backward
16133 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16134 (- (point) 20) t)))
16135 (apply 'encode-time (org-parse-time-string (match-string 1)))
16136 (current-time)))
16137 (default-input (and ts (org-get-compact-tod ts)))
16138 (repeater (save-excursion
16139 (save-match-data
16140 (beginning-of-line)
16141 (when (re-search-forward
16142 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16143 (save-excursion (progn (end-of-line) (point))) t)
16144 (match-string 0)))))
16145 org-time-was-given org-end-time-was-given time)
16146 (cond
16147 ((and (org-at-timestamp-p t)
16148 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16149 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16150 (insert "--")
16151 (setq time (let ((this-command this-command))
16152 (org-read-date arg 'totime nil nil
16153 default-time default-input inactive)))
16154 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16155 ((org-at-timestamp-p t)
16156 (setq time (let ((this-command this-command))
16157 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16158 (when (org-at-timestamp-p t) ; just to get the match data
16159 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16160 (replace-match "")
16161 (setq org-last-changed-timestamp
16162 (org-insert-time-stamp
16163 time (or org-time-was-given arg)
16164 inactive nil nil (list org-end-time-was-given)))
16165 (when repeater (goto-char (1- (point))) (insert " " repeater)
16166 (setq org-last-changed-timestamp
16167 (concat (substring org-last-inserted-timestamp 0 -1)
16168 " " repeater ">"))))
16169 (message "Timestamp updated"))
16170 ((equal arg '(16))
16171 (org-insert-time-stamp (current-time) t inactive))
16173 (setq time (let ((this-command this-command))
16174 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16175 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16176 nil nil (list org-end-time-was-given))))))
16178 ;; FIXME: can we use this for something else, like computing time differences?
16179 (defun org-get-compact-tod (s)
16180 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16181 (let* ((t1 (match-string 1 s))
16182 (h1 (string-to-number (match-string 2 s)))
16183 (m1 (string-to-number (match-string 3 s)))
16184 (t2 (and (match-end 4) (match-string 5 s)))
16185 (h2 (and t2 (string-to-number (match-string 6 s))))
16186 (m2 (and t2 (string-to-number (match-string 7 s))))
16187 dh dm)
16188 (if (not t2)
16190 (setq dh (- h2 h1) dm (- m2 m1))
16191 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16192 (concat t1 "+" (number-to-string dh)
16193 (and (/= 0 dm) (format ":%02d" dm)))))))
16195 (defun org-time-stamp-inactive (&optional arg)
16196 "Insert an inactive time stamp.
16197 An inactive time stamp is enclosed in square brackets instead of angle
16198 brackets. It is inactive in the sense that it does not trigger agenda entries,
16199 does not link to the calendar and cannot be changed with the S-cursor keys.
16200 So these are more for recording a certain time/date."
16201 (interactive "P")
16202 (org-time-stamp arg 'inactive))
16204 (defvar org-date-ovl (make-overlay 1 1))
16205 (overlay-put org-date-ovl 'face 'org-date-selected)
16206 (org-detach-overlay org-date-ovl)
16208 (defvar org-ans1) ; dynamically scoped parameter
16209 (defvar org-ans2) ; dynamically scoped parameter
16211 (defvar org-plain-time-of-day-regexp) ; defined below
16213 (defvar org-overriding-default-time nil) ; dynamically scoped
16214 (defvar org-read-date-overlay nil)
16215 (defvar org-dcst nil) ; dynamically scoped
16216 (defvar org-read-date-history nil)
16217 (defvar org-read-date-final-answer nil)
16218 (defvar org-read-date-analyze-futurep nil)
16219 (defvar org-read-date-analyze-forced-year nil)
16220 (defvar org-read-date-inactive)
16222 (defvar org-read-date-minibuffer-local-map
16223 (let* ((org-replace-disputed-keys nil)
16224 (map (make-sparse-keymap)))
16225 (set-keymap-parent map minibuffer-local-map)
16226 (org-defkey map (kbd ".")
16227 (lambda () (interactive)
16228 ;; Are we at the beginning of the prompt?
16229 (if (looking-back "^[^:]+: ")
16230 (org-eval-in-calendar '(calendar-goto-today))
16231 (insert "."))))
16232 (org-defkey map (kbd "C-.")
16233 (lambda () (interactive)
16234 (org-eval-in-calendar '(calendar-goto-today))))
16235 (org-defkey map [(meta shift left)]
16236 (lambda () (interactive)
16237 (org-eval-in-calendar '(calendar-backward-month 1))))
16238 (org-defkey map [(meta shift right)]
16239 (lambda () (interactive)
16240 (org-eval-in-calendar '(calendar-forward-month 1))))
16241 (org-defkey map [(meta shift up)]
16242 (lambda () (interactive)
16243 (org-eval-in-calendar '(calendar-backward-year 1))))
16244 (org-defkey map [(meta shift down)]
16245 (lambda () (interactive)
16246 (org-eval-in-calendar '(calendar-forward-year 1))))
16247 (org-defkey map [?\e (shift left)]
16248 (lambda () (interactive)
16249 (org-eval-in-calendar '(calendar-backward-month 1))))
16250 (org-defkey map [?\e (shift right)]
16251 (lambda () (interactive)
16252 (org-eval-in-calendar '(calendar-forward-month 1))))
16253 (org-defkey map [?\e (shift up)]
16254 (lambda () (interactive)
16255 (org-eval-in-calendar '(calendar-backward-year 1))))
16256 (org-defkey map [?\e (shift down)]
16257 (lambda () (interactive)
16258 (org-eval-in-calendar '(calendar-forward-year 1))))
16259 (org-defkey map [(shift up)]
16260 (lambda () (interactive)
16261 (org-eval-in-calendar '(calendar-backward-week 1))))
16262 (org-defkey map [(shift down)]
16263 (lambda () (interactive)
16264 (org-eval-in-calendar '(calendar-forward-week 1))))
16265 (org-defkey map [(shift left)]
16266 (lambda () (interactive)
16267 (org-eval-in-calendar '(calendar-backward-day 1))))
16268 (org-defkey map [(shift right)]
16269 (lambda () (interactive)
16270 (org-eval-in-calendar '(calendar-forward-day 1))))
16271 (org-defkey map "!"
16272 (lambda () (interactive)
16273 (org-eval-in-calendar '(diary-view-entries))
16274 (message "")))
16275 (org-defkey map ">"
16276 (lambda () (interactive)
16277 (org-eval-in-calendar '(scroll-calendar-left 1))))
16278 (org-defkey map "<"
16279 (lambda () (interactive)
16280 (org-eval-in-calendar '(scroll-calendar-right 1))))
16281 (org-defkey map "\C-v"
16282 (lambda () (interactive)
16283 (org-eval-in-calendar
16284 '(calendar-scroll-left-three-months 1))))
16285 (org-defkey map "\M-v"
16286 (lambda () (interactive)
16287 (org-eval-in-calendar
16288 '(calendar-scroll-right-three-months 1))))
16289 map)
16290 "Keymap for minibuffer commands when using `org-read-date'.")
16292 (defvar org-def)
16293 (defvar org-defdecode)
16294 (defvar org-with-time)
16296 (defun org-read-date (&optional org-with-time to-time from-string prompt
16297 default-time default-input inactive)
16298 "Read a date, possibly a time, and make things smooth for the user.
16299 The prompt will suggest to enter an ISO date, but you can also enter anything
16300 which will at least partially be understood by `parse-time-string'.
16301 Unrecognized parts of the date will default to the current day, month, year,
16302 hour and minute. If this command is called to replace a timestamp at point,
16303 or to enter the second timestamp of a range, the default time is taken
16304 from the existing stamp. Furthermore, the command prefers the future,
16305 so if you are giving a date where the year is not given, and the day-month
16306 combination is already past in the current year, it will assume you
16307 mean next year. For details, see the manual. A few examples:
16309 3-2-5 --> 2003-02-05
16310 feb 15 --> currentyear-02-15
16311 2/15 --> currentyear-02-15
16312 sep 12 9 --> 2009-09-12
16313 12:45 --> today 12:45
16314 22 sept 0:34 --> currentyear-09-22 0:34
16315 12 --> currentyear-currentmonth-12
16316 Fri --> nearest Friday after today
16317 -Tue --> last Tuesday
16318 etc.
16320 Furthermore you can specify a relative date by giving, as the *first* thing
16321 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16322 change in days weeks, months, years.
16323 With a single plus or minus, the date is relative to today. With a double
16324 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16325 +4d --> four days from today
16326 +4 --> same as above
16327 +2w --> two weeks from today
16328 ++5 --> five days from default date
16330 The function understands only English month and weekday abbreviations.
16332 While prompting, a calendar is popped up - you can also select the
16333 date with the mouse (button 1). The calendar shows a period of three
16334 months. To scroll it to other months, use the keys `>' and `<'.
16335 If you don't like the calendar, turn it off with
16336 \(setq org-read-date-popup-calendar nil)
16338 With optional argument TO-TIME, the date will immediately be converted
16339 to an internal time.
16340 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16341 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16342 still enter a time, and this function will inform the calling routine
16343 about this change. The calling routine may then choose to change the
16344 format used to insert the time stamp into the buffer to include the time.
16345 With optional argument FROM-STRING, read from this string instead from
16346 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16347 the time/date that is used for everything that is not specified by the
16348 user."
16349 (require 'parse-time)
16350 (let* ((org-time-stamp-rounding-minutes
16351 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16352 (org-dcst org-display-custom-times)
16353 (ct (org-current-time))
16354 (org-def (or org-overriding-default-time default-time ct))
16355 (org-defdecode (decode-time org-def))
16356 (dummy (progn
16357 (when (< (nth 2 org-defdecode) org-extend-today-until)
16358 (setcar (nthcdr 2 org-defdecode) -1)
16359 (setcar (nthcdr 1 org-defdecode) 59)
16360 (setq org-def (apply 'encode-time org-defdecode)
16361 org-defdecode (decode-time org-def)))))
16362 (mouse-autoselect-window nil) ; Don't let the mouse jump
16363 (calendar-frame-setup nil)
16364 (calendar-setup nil)
16365 (calendar-move-hook nil)
16366 (calendar-view-diary-initially-flag nil)
16367 (calendar-view-holidays-initially-flag nil)
16368 (timestr (format-time-string
16369 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16370 (prompt (concat (if prompt (concat prompt " ") "")
16371 (format "Date+time [%s]: " timestr)))
16372 ans (org-ans0 "") org-ans1 org-ans2 final)
16374 (cond
16375 (from-string (setq ans from-string))
16376 (org-read-date-popup-calendar
16377 (save-excursion
16378 (save-window-excursion
16379 (calendar)
16380 (org-eval-in-calendar '(setq cursor-type nil) t)
16381 (unwind-protect
16382 (progn
16383 (calendar-forward-day (- (time-to-days org-def)
16384 (calendar-absolute-from-gregorian
16385 (calendar-current-date))))
16386 (org-eval-in-calendar nil t)
16387 (let* ((old-map (current-local-map))
16388 (map (copy-keymap calendar-mode-map))
16389 (minibuffer-local-map
16390 (copy-keymap org-read-date-minibuffer-local-map)))
16391 (org-defkey map (kbd "RET") 'org-calendar-select)
16392 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16393 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16394 (unwind-protect
16395 (progn
16396 (use-local-map map)
16397 (setq org-read-date-inactive inactive)
16398 (add-hook 'post-command-hook 'org-read-date-display)
16399 (setq org-ans0 (read-string prompt default-input
16400 'org-read-date-history nil))
16401 ;; org-ans0: from prompt
16402 ;; org-ans1: from mouse click
16403 ;; org-ans2: from calendar motion
16404 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16405 (remove-hook 'post-command-hook 'org-read-date-display)
16406 (use-local-map old-map)
16407 (when org-read-date-overlay
16408 (delete-overlay org-read-date-overlay)
16409 (setq org-read-date-overlay nil)))))
16410 (bury-buffer "*Calendar*")))))
16412 (t ; Naked prompt only
16413 (unwind-protect
16414 (setq ans (read-string prompt default-input
16415 'org-read-date-history timestr))
16416 (when org-read-date-overlay
16417 (delete-overlay org-read-date-overlay)
16418 (setq org-read-date-overlay nil)))))
16420 (setq final (org-read-date-analyze ans org-def org-defdecode))
16422 (when org-read-date-analyze-forced-year
16423 (message "Year was forced into %s"
16424 (if org-read-date-force-compatible-dates
16425 "compatible range (1970-2037)"
16426 "range representable on this machine"))
16427 (ding))
16429 ;; One round trip to get rid of 34th of August and stuff like that....
16430 (setq final (decode-time (apply 'encode-time final)))
16432 (setq org-read-date-final-answer ans)
16434 (if to-time
16435 (apply 'encode-time final)
16436 (if (and (boundp 'org-time-was-given) org-time-was-given)
16437 (format "%04d-%02d-%02d %02d:%02d"
16438 (nth 5 final) (nth 4 final) (nth 3 final)
16439 (nth 2 final) (nth 1 final))
16440 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16442 (defun org-read-date-display ()
16443 "Display the current date prompt interpretation in the minibuffer."
16444 (when org-read-date-display-live
16445 (when org-read-date-overlay
16446 (delete-overlay org-read-date-overlay))
16447 (when (minibufferp (current-buffer))
16448 (save-excursion
16449 (end-of-line 1)
16450 (while (not (equal (buffer-substring
16451 (max (point-min) (- (point) 4)) (point))
16452 " "))
16453 (insert " ")))
16454 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16455 " " (or org-ans1 org-ans2)))
16456 (org-end-time-was-given nil)
16457 (f (org-read-date-analyze ans org-def org-defdecode))
16458 (fmts (if org-dcst
16459 org-time-stamp-custom-formats
16460 org-time-stamp-formats))
16461 (fmt (if (or org-with-time
16462 (and (boundp 'org-time-was-given) org-time-was-given))
16463 (cdr fmts)
16464 (car fmts)))
16465 (txt (format-time-string fmt (apply 'encode-time f)))
16466 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16467 (txt (concat "=> " txt)))
16468 (when (and org-end-time-was-given
16469 (string-match org-plain-time-of-day-regexp txt))
16470 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16471 org-end-time-was-given
16472 (substring txt (match-end 0)))))
16473 (when org-read-date-analyze-futurep
16474 (setq txt (concat txt " (=>F)")))
16475 (setq org-read-date-overlay
16476 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16477 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16479 (defun org-read-date-analyze (ans org-def org-defdecode)
16480 "Analyze the combined answer of the date prompt."
16481 ;; FIXME: cleanup and comment
16482 (let ((nowdecode (decode-time (current-time)))
16483 delta deltan deltaw deltadef year month day
16484 hour minute second wday pm h2 m2 tl wday1
16485 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16486 (setq org-read-date-analyze-futurep nil
16487 org-read-date-analyze-forced-year nil)
16488 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16489 (setq ans "+0"))
16491 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16492 (setq ans (replace-match "" t t ans)
16493 deltan (car delta)
16494 deltaw (nth 1 delta)
16495 deltadef (nth 2 delta)))
16497 ;; Check if there is an iso week date in there. If yes, store the
16498 ;; info and postpone interpreting it until the rest of the parsing
16499 ;; is done.
16500 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16501 (setq iso-year (if (match-end 1)
16502 (org-small-year-to-year
16503 (string-to-number (match-string 1 ans))))
16504 iso-weekday (if (match-end 3)
16505 (string-to-number (match-string 3 ans)))
16506 iso-week (string-to-number (match-string 2 ans)))
16507 (setq ans (replace-match "" t t ans)))
16509 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16510 (when (string-match
16511 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16512 (setq year (if (match-end 2)
16513 (string-to-number (match-string 2 ans))
16514 (progn (setq kill-year t)
16515 (string-to-number (format-time-string "%Y"))))
16516 month (string-to-number (match-string 3 ans))
16517 day (string-to-number (match-string 4 ans)))
16518 (if (< year 100) (setq year (+ 2000 year)))
16519 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16520 t nil ans)))
16522 ;; Help matching dotted european dates
16523 (when (string-match
16524 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16525 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16526 (setq kill-year t)
16527 (string-to-number (format-time-string "%Y")))
16528 day (string-to-number (match-string 1 ans))
16529 month (string-to-number (match-string 2 ans))
16530 ans (replace-match (format "%04d-%02d-%02d" year month day)
16531 t nil ans)))
16533 ;; Help matching american dates, like 5/30 or 5/30/7
16534 (when (string-match
16535 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16536 (setq year (if (match-end 4)
16537 (string-to-number (match-string 4 ans))
16538 (progn (setq kill-year t)
16539 (string-to-number (format-time-string "%Y"))))
16540 month (string-to-number (match-string 1 ans))
16541 day (string-to-number (match-string 2 ans)))
16542 (if (< year 100) (setq year (+ 2000 year)))
16543 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16544 t nil ans)))
16545 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16546 ;; If there is a time with am/pm, and *no* time without it, we convert
16547 ;; so that matching will be successful.
16548 (loop for i from 1 to 2 do ; twice, for end time as well
16549 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16550 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16551 (setq hour (string-to-number (match-string 1 ans))
16552 minute (if (match-end 3)
16553 (string-to-number (match-string 3 ans))
16555 pm (equal ?p
16556 (string-to-char (downcase (match-string 4 ans)))))
16557 (if (and (= hour 12) (not pm))
16558 (setq hour 0)
16559 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16560 (setq ans (replace-match (format "%02d:%02d" hour minute)
16561 t t ans))))
16563 ;; Check if a time range is given as a duration
16564 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16565 (setq hour (string-to-number (match-string 1 ans))
16566 h2 (+ hour (string-to-number (match-string 3 ans)))
16567 minute (string-to-number (match-string 2 ans))
16568 m2 (+ minute (if (match-end 5) (string-to-number
16569 (match-string 5 ans))0)))
16570 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16571 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16572 t t ans)))
16574 ;; Check if there is a time range
16575 (when (boundp 'org-end-time-was-given)
16576 (setq org-time-was-given nil)
16577 (when (and (string-match org-plain-time-of-day-regexp ans)
16578 (match-end 8))
16579 (setq org-end-time-was-given (match-string 8 ans))
16580 (setq ans (concat (substring ans 0 (match-beginning 7))
16581 (substring ans (match-end 7))))))
16583 (setq tl (parse-time-string ans)
16584 day (or (nth 3 tl) (nth 3 org-defdecode))
16585 month (or (nth 4 tl)
16586 (if (and org-read-date-prefer-future
16587 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16588 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16589 (nth 4 org-defdecode)))
16590 year (or (and (not kill-year) (nth 5 tl))
16591 (if (and org-read-date-prefer-future
16592 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16593 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16594 (nth 5 org-defdecode)))
16595 hour (or (nth 2 tl) (nth 2 org-defdecode))
16596 minute (or (nth 1 tl) (nth 1 org-defdecode))
16597 second (or (nth 0 tl) 0)
16598 wday (nth 6 tl))
16600 (when (and (eq org-read-date-prefer-future 'time)
16601 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16602 (equal day (nth 3 nowdecode))
16603 (equal month (nth 4 nowdecode))
16604 (equal year (nth 5 nowdecode))
16605 (nth 2 tl)
16606 (or (< (nth 2 tl) (nth 2 nowdecode))
16607 (and (= (nth 2 tl) (nth 2 nowdecode))
16608 (nth 1 tl)
16609 (< (nth 1 tl) (nth 1 nowdecode)))))
16610 (setq day (1+ day)
16611 futurep t))
16613 ;; Special date definitions below
16614 (cond
16615 (iso-week
16616 ;; There was an iso week
16617 (require 'cal-iso)
16618 (setq futurep nil)
16619 (setq year (or iso-year year)
16620 day (or iso-weekday wday 1)
16621 wday nil ; to make sure that the trigger below does not match
16622 iso-date (calendar-gregorian-from-absolute
16623 (calendar-absolute-from-iso
16624 (list iso-week day year))))
16625 ; FIXME: Should we also push ISO weeks into the future?
16626 ; (when (and org-read-date-prefer-future
16627 ; (not iso-year)
16628 ; (< (calendar-absolute-from-gregorian iso-date)
16629 ; (time-to-days (current-time))))
16630 ; (setq year (1+ year)
16631 ; iso-date (calendar-gregorian-from-absolute
16632 ; (calendar-absolute-from-iso
16633 ; (list iso-week day year)))))
16634 (setq month (car iso-date)
16635 year (nth 2 iso-date)
16636 day (nth 1 iso-date)))
16637 (deltan
16638 (setq futurep nil)
16639 (unless deltadef
16640 (let ((now (decode-time (current-time))))
16641 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16642 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16643 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16644 ((equal deltaw "m") (setq month (+ month deltan)))
16645 ((equal deltaw "y") (setq year (+ year deltan)))))
16646 ((and wday (not (nth 3 tl)))
16647 ;; Weekday was given, but no day, so pick that day in the week
16648 ;; on or after the derived date.
16649 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16650 (unless (equal wday wday1)
16651 (setq day (+ day (% (- wday wday1 -7) 7))))))
16652 (if (and (boundp 'org-time-was-given)
16653 (nth 2 tl))
16654 (setq org-time-was-given t))
16655 (if (< year 100) (setq year (+ 2000 year)))
16656 ;; Check of the date is representable
16657 (if org-read-date-force-compatible-dates
16658 (progn
16659 (if (< year 1970)
16660 (setq year 1970 org-read-date-analyze-forced-year t))
16661 (if (> year 2037)
16662 (setq year 2037 org-read-date-analyze-forced-year t)))
16663 (condition-case nil
16664 (ignore (encode-time second minute hour day month year))
16665 (error
16666 (setq year (nth 5 org-defdecode))
16667 (setq org-read-date-analyze-forced-year t))))
16668 (setq org-read-date-analyze-futurep futurep)
16669 (list second minute hour day month year)))
16671 (defvar parse-time-weekdays)
16672 (defun org-read-date-get-relative (s today default)
16673 "Check string S for special relative date string.
16674 TODAY and DEFAULT are internal times, for today and for a default.
16675 Return shift list (N what def-flag)
16676 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16677 N is the number of WHATs to shift.
16678 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16679 the DEFAULT date rather than TODAY."
16680 (require 'parse-time)
16681 (when (and
16682 (string-match
16683 (concat
16684 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16685 "\\([0-9]+\\)?"
16686 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16687 "\\([ \t]\\|$\\)") s)
16688 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16689 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16690 (string-to-char (substring (match-string 1 s) -1))
16691 ?+))
16692 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16693 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16694 (what (if (match-end 3) (match-string 3 s) "d"))
16695 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16696 (date (if rel default today))
16697 (wday (nth 6 (decode-time date)))
16698 delta)
16699 (if wday1
16700 (progn
16701 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16702 (if (= delta 0) (setq delta 7))
16703 (if (= dir ?-)
16704 (progn
16705 (setq delta (- delta 7))
16706 (if (= delta 0) (setq delta -7))))
16707 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16708 (list delta "d" rel))
16709 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16711 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16712 "Turn a user-specified date into the internal representation.
16713 The internal representation needed by the calendar is (month day year).
16714 This is a wrapper to handle the brain-dead convention in calendar that
16715 user function argument order change dependent on argument order."
16716 (if (boundp 'calendar-date-style)
16717 (cond
16718 ((eq calendar-date-style 'american)
16719 (list arg1 arg2 arg3))
16720 ((eq calendar-date-style 'european)
16721 (list arg2 arg1 arg3))
16722 ((eq calendar-date-style 'iso)
16723 (list arg2 arg3 arg1)))
16724 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16725 (if (org-bound-and-true-p european-calendar-style)
16726 (list arg2 arg1 arg3)
16727 (list arg1 arg2 arg3)))))
16729 (defun org-eval-in-calendar (form &optional keepdate)
16730 "Eval FORM in the calendar window and return to current window.
16731 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16732 otherwise stick to the current value of `org-ans2'."
16733 (let ((sf (selected-frame))
16734 (sw (selected-window)))
16735 (select-window (get-buffer-window "*Calendar*" t))
16736 (eval form)
16737 (when (and (not keepdate) (calendar-cursor-to-date))
16738 (let* ((date (calendar-cursor-to-date))
16739 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16740 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16741 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16742 (select-window sw)
16743 (org-select-frame-set-input-focus sf)))
16745 (defun org-calendar-select ()
16746 "Return to `org-read-date' with the date currently selected.
16747 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16748 (interactive)
16749 (when (calendar-cursor-to-date)
16750 (let* ((date (calendar-cursor-to-date))
16751 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16752 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16753 (if (active-minibuffer-window) (exit-minibuffer))))
16755 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16756 "Insert a date stamp for the date given by the internal TIME.
16757 WITH-HM means use the stamp format that includes the time of the day.
16758 INACTIVE means use square brackets instead of angular ones, so that the
16759 stamp will not contribute to the agenda.
16760 PRE and POST are optional strings to be inserted before and after the
16761 stamp.
16762 The command returns the inserted time stamp."
16763 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16764 stamp)
16765 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16766 (insert-before-markers (or pre ""))
16767 (when (listp extra)
16768 (setq extra (car extra))
16769 (if (and (stringp extra)
16770 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16771 (setq extra (format "-%02d:%02d"
16772 (string-to-number (match-string 1 extra))
16773 (string-to-number (match-string 2 extra))))
16774 (setq extra nil)))
16775 (when extra
16776 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16777 (insert-before-markers (setq stamp (format-time-string fmt time)))
16778 (insert-before-markers (or post ""))
16779 (setq org-last-inserted-timestamp stamp)))
16781 (defun org-toggle-time-stamp-overlays ()
16782 "Toggle the use of custom time stamp formats."
16783 (interactive)
16784 (setq org-display-custom-times (not org-display-custom-times))
16785 (unless org-display-custom-times
16786 (let ((p (point-min)) (bmp (buffer-modified-p)))
16787 (while (setq p (next-single-property-change p 'display))
16788 (if (and (get-text-property p 'display)
16789 (eq (get-text-property p 'face) 'org-date))
16790 (remove-text-properties
16791 p (setq p (next-single-property-change p 'display))
16792 '(display t))))
16793 (set-buffer-modified-p bmp)))
16794 (if (featurep 'xemacs)
16795 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16796 (org-restart-font-lock)
16797 (setq org-table-may-need-update t)
16798 (if org-display-custom-times
16799 (message "Time stamps are overlaid with custom format")
16800 (message "Time stamp overlays removed")))
16802 (defun org-display-custom-time (beg end)
16803 "Overlay modified time stamp format over timestamp between BEG and END."
16804 (let* ((ts (buffer-substring beg end))
16805 t1 w1 with-hm tf time str w2 (off 0))
16806 (save-match-data
16807 (setq t1 (org-parse-time-string ts t))
16808 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16809 (setq off (- (match-end 0) (match-beginning 0)))))
16810 (setq end (- end off))
16811 (setq w1 (- end beg)
16812 with-hm (and (nth 1 t1) (nth 2 t1))
16813 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16814 time (org-fix-decoded-time t1)
16815 str (org-add-props
16816 (format-time-string
16817 (substring tf 1 -1) (apply 'encode-time time))
16818 nil 'mouse-face 'highlight)
16819 w2 (length str))
16820 (if (not (= w2 w1))
16821 (add-text-properties (1+ beg) (+ 2 beg)
16822 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16823 (if (featurep 'xemacs)
16824 (progn
16825 (put-text-property beg end 'invisible t)
16826 (put-text-property beg end 'end-glyph (make-glyph str)))
16827 (put-text-property beg end 'display str))))
16829 (defun org-translate-time (string)
16830 "Translate all timestamps in STRING to custom format.
16831 But do this only if the variable `org-display-custom-times' is set."
16832 (when org-display-custom-times
16833 (save-match-data
16834 (let* ((start 0)
16835 (re org-ts-regexp-both)
16836 t1 with-hm inactive tf time str beg end)
16837 (while (setq start (string-match re string start))
16838 (setq beg (match-beginning 0)
16839 end (match-end 0)
16840 t1 (save-match-data
16841 (org-parse-time-string (substring string beg end) t))
16842 with-hm (and (nth 1 t1) (nth 2 t1))
16843 inactive (equal (substring string beg (1+ beg)) "[")
16844 tf (funcall (if with-hm 'cdr 'car)
16845 org-time-stamp-custom-formats)
16846 time (org-fix-decoded-time t1)
16847 str (format-time-string
16848 (concat
16849 (if inactive "[" "<") (substring tf 1 -1)
16850 (if inactive "]" ">"))
16851 (apply 'encode-time time))
16852 string (replace-match str t t string)
16853 start (+ start (length str)))))))
16854 string)
16856 (defun org-fix-decoded-time (time)
16857 "Set 0 instead of nil for the first 6 elements of time.
16858 Don't touch the rest."
16859 (let ((n 0))
16860 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16862 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16864 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16865 "Difference between TIMESTAMP-STRING and now in days.
16866 If SECONDS is non-nil, return the difference in seconds."
16867 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16868 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16869 (funcall fdiff (current-time)))))
16871 (defun org-deadline-close (timestamp-string &optional ndays)
16872 "Is the time in TIMESTAMP-STRING close to the current date?"
16873 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16874 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16875 (not (org-entry-is-done-p))))
16877 (defun org-get-wdays (ts &optional delay zero-delay)
16878 "Get the deadline lead time appropriate for timestring TS.
16879 When DELAY is non-nil, get the delay time for scheduled items
16880 instead of the deadline lead time. When ZERO-DELAY is non-nil
16881 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16882 don't try to find the delay cookie in the scheduled timestamp."
16883 (let ((tv (if delay org-scheduled-delay-days
16884 org-deadline-warning-days)))
16885 (cond
16886 ((or (and delay (< tv 0))
16887 (and delay zero-delay (<= tv 0))
16888 (and (not delay) (<= tv 0)))
16889 ;; Enforce this value no matter what
16890 (- tv))
16891 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16892 ;; lead time is specified.
16893 (floor (* (string-to-number (match-string 1 ts))
16894 (cdr (assoc (match-string 2 ts)
16895 '(("d" . 1) ("w" . 7)
16896 ("m" . 30.4) ("y" . 365.25)
16897 ("h" . 0.041667)))))))
16898 ;; go for the default.
16899 (t tv))))
16901 (defun org-calendar-select-mouse (ev)
16902 "Return to `org-read-date' with the date currently selected.
16903 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16904 (interactive "e")
16905 (mouse-set-point ev)
16906 (when (calendar-cursor-to-date)
16907 (let* ((date (calendar-cursor-to-date))
16908 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16909 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16910 (if (active-minibuffer-window) (exit-minibuffer))))
16912 (defun org-check-deadlines (ndays)
16913 "Check if there are any deadlines due or past due.
16914 A deadline is considered due if it happens within `org-deadline-warning-days'
16915 days from today's date. If the deadline appears in an entry marked DONE,
16916 it is not shown. The prefix arg NDAYS can be used to test that many
16917 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16918 (interactive "P")
16919 (let* ((org-warn-days
16920 (cond
16921 ((equal ndays '(4)) 100000)
16922 (ndays (prefix-numeric-value ndays))
16923 (t (abs org-deadline-warning-days))))
16924 (case-fold-search nil)
16925 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16926 (callback
16927 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16929 (message "%d deadlines past-due or due within %d days"
16930 (org-occur regexp nil callback)
16931 org-warn-days)))
16933 (defsubst org-re-timestamp (type)
16934 "Return a regexp for timestamp TYPE.
16935 Allowed values for TYPE are:
16937 all: all timestamps
16938 active: only active timestamps (<...>)
16939 inactive: only inactive timestamps ([...])
16940 scheduled: only scheduled timestamps
16941 deadline: only deadline timestamps
16942 closed: only closed time-stamps
16944 When TYPE is nil, fall back on returning a regexp that matches
16945 both scheduled and deadline timestamps."
16946 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16947 ((eq type 'active) org-ts-regexp)
16948 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16949 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16950 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16951 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
16952 ((eq type 'scheduled-or-deadline)
16953 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16955 (defun org-check-before-date (date)
16956 "Check if there are deadlines or scheduled entries before DATE."
16957 (interactive (list (org-read-date)))
16958 (let ((case-fold-search nil)
16959 (regexp (org-re-timestamp org-ts-type))
16960 (callback
16961 (lambda () (time-less-p
16962 (org-time-string-to-time (match-string 1))
16963 (org-time-string-to-time date)))))
16964 (message "%d entries before %s"
16965 (org-occur regexp nil callback) date)))
16967 (defun org-check-after-date (date)
16968 "Check if there are deadlines or scheduled entries after DATE."
16969 (interactive (list (org-read-date)))
16970 (let ((case-fold-search nil)
16971 (regexp (org-re-timestamp org-ts-type))
16972 (callback
16973 (lambda () (not
16974 (time-less-p
16975 (org-time-string-to-time (match-string 1))
16976 (org-time-string-to-time date))))))
16977 (message "%d entries after %s"
16978 (org-occur regexp nil callback) date)))
16980 (defun org-check-dates-range (start-date end-date)
16981 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16982 (interactive (list (org-read-date nil nil nil "Range starts")
16983 (org-read-date nil nil nil "Range end")))
16984 (let ((case-fold-search nil)
16985 (regexp (org-re-timestamp org-ts-type))
16986 (callback
16987 (lambda ()
16988 (let ((match (match-string 1)))
16989 (and
16990 (not (time-less-p
16991 (org-time-string-to-time match)
16992 (org-time-string-to-time start-date)))
16993 (time-less-p
16994 (org-time-string-to-time match)
16995 (org-time-string-to-time end-date)))))))
16996 (message "%d entries between %s and %s"
16997 (org-occur regexp nil callback) start-date end-date)))
16999 (defun org-evaluate-time-range (&optional to-buffer)
17000 "Evaluate a time range by computing the difference between start and end.
17001 Normally the result is just printed in the echo area, but with prefix arg
17002 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17003 If the time range is actually in a table, the result is inserted into the
17004 next column.
17005 For time difference computation, a year is assumed to be exactly 365
17006 days in order to avoid rounding problems."
17007 (interactive "P")
17009 (org-clock-update-time-maybe)
17010 (save-excursion
17011 (unless (org-at-date-range-p t)
17012 (goto-char (point-at-bol))
17013 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17014 (if (not (org-at-date-range-p t))
17015 (user-error "Not at a time-stamp range, and none found in current line")))
17016 (let* ((ts1 (match-string 1))
17017 (ts2 (match-string 2))
17018 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17019 (match-end (match-end 0))
17020 (time1 (org-time-string-to-time ts1))
17021 (time2 (org-time-string-to-time ts2))
17022 (t1 (org-float-time time1))
17023 (t2 (org-float-time time2))
17024 (diff (abs (- t2 t1)))
17025 (negative (< (- t2 t1) 0))
17026 ;; (ys (floor (* 365 24 60 60)))
17027 (ds (* 24 60 60))
17028 (hs (* 60 60))
17029 (fy "%dy %dd %02d:%02d")
17030 (fy1 "%dy %dd")
17031 (fd "%dd %02d:%02d")
17032 (fd1 "%dd")
17033 (fh "%02d:%02d")
17034 y d h m align)
17035 (if havetime
17036 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17038 d (floor (/ diff ds)) diff (mod diff ds)
17039 h (floor (/ diff hs)) diff (mod diff hs)
17040 m (floor (/ diff 60)))
17041 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17043 d (floor (+ (/ diff ds) 0.5))
17044 h 0 m 0))
17045 (if (not to-buffer)
17046 (message "%s" (org-make-tdiff-string y d h m))
17047 (if (org-at-table-p)
17048 (progn
17049 (goto-char match-end)
17050 (setq align t)
17051 (and (looking-at " *|") (goto-char (match-end 0))))
17052 (goto-char match-end))
17053 (if (looking-at
17054 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17055 (replace-match ""))
17056 (if negative (insert " -"))
17057 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17058 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17059 (insert " " (format fh h m))))
17060 (if align (org-table-align))
17061 (message "Time difference inserted")))))
17063 (defun org-make-tdiff-string (y d h m)
17064 (let ((fmt "")
17065 (l nil))
17066 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
17067 l (push y l)))
17068 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
17069 l (push d l)))
17070 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
17071 l (push h l)))
17072 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
17073 l (push m l)))
17074 (apply 'format fmt (nreverse l))))
17076 (defun org-time-string-to-time (s &optional buffer pos)
17077 "Convert a timestamp string into internal time."
17078 (condition-case errdata
17079 (apply 'encode-time (org-parse-time-string s))
17080 (error (error "Bad timestamp `%s'%s\nError was: %s"
17081 s (if (not (and buffer pos))
17083 (format " at %d in buffer `%s'" pos buffer))
17084 (cdr errdata)))))
17086 (defun org-time-string-to-seconds (s)
17087 "Convert a timestamp string to a number of seconds."
17088 (org-float-time (org-time-string-to-time s)))
17090 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17091 "Convert a time stamp to an absolute day number.
17092 If there is a specifier for a cyclic time stamp, get the closest
17093 date to DAYNR.
17094 PREFER and SHOW-ALL are passed through to `org-closest-date'.
17095 The variable `date' is bound by the calendar when this is called."
17096 (cond
17097 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17098 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17099 daynr
17100 (+ daynr 1000)))
17101 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
17102 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17103 (time-to-days (current-time))) (match-string 0 s)
17104 prefer show-all))
17105 (t (time-to-days
17106 (condition-case errdata
17107 (apply 'encode-time (org-parse-time-string s))
17108 (error (error "Bad timestamp `%s'%s\nError was: %s"
17109 s (if (not (and buffer pos))
17111 (format " at %d in buffer `%s'" pos buffer))
17112 (cdr errdata))))))))
17114 (defun org-days-to-iso-week (days)
17115 "Return the iso week number."
17116 (require 'cal-iso)
17117 (car (calendar-iso-from-absolute days)))
17119 (defun org-small-year-to-year (year)
17120 "Convert 2-digit years into 4-digit years.
17121 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
17122 The year 2000 cannot be abbreviated. Any year larger than 99
17123 is returned unchanged."
17124 (if (< year 38)
17125 (setq year (+ 2000 year))
17126 (if (< year 100)
17127 (setq year (+ 1900 year))))
17128 year)
17130 (defun org-time-from-absolute (d)
17131 "Return the time corresponding to date D.
17132 D may be an absolute day number, or a calendar-type list (month day year)."
17133 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17134 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17136 (defun org-calendar-holiday ()
17137 "List of holidays, for Diary display in Org-mode."
17138 (require 'holidays)
17139 (let ((hl (funcall
17140 (if (fboundp 'calendar-check-holidays)
17141 'calendar-check-holidays 'check-calendar-holidays) date)))
17142 (if hl (mapconcat 'identity hl "; "))))
17144 (defun org-diary-sexp-entry (sexp entry date)
17145 "Process a SEXP diary ENTRY for DATE."
17146 (require 'diary-lib)
17147 (let ((result (if calendar-debug-sexp
17148 (let ((stack-trace-on-error t))
17149 (eval (car (read-from-string sexp))))
17150 (condition-case nil
17151 (eval (car (read-from-string sexp)))
17152 (error
17153 (beep)
17154 (message "Bad sexp at line %d in %s: %s"
17155 (org-current-line)
17156 (buffer-file-name) sexp)
17157 (sleep-for 2))))))
17158 (cond ((stringp result) (split-string result "; "))
17159 ((and (consp result)
17160 (not (consp (cdr result)))
17161 (stringp (cdr result))) (cdr result))
17162 ((and (consp result)
17163 (stringp (car result))) result)
17164 (result entry))))
17166 (defun org-diary-to-ical-string (frombuf)
17167 "Get iCalendar entries from diary entries in buffer FROMBUF.
17168 This uses the icalendar.el library."
17169 (let* ((tmpdir (if (featurep 'xemacs)
17170 (temp-directory)
17171 temporary-file-directory))
17172 (tmpfile (make-temp-name
17173 (expand-file-name "orgics" tmpdir)))
17174 buf rtn b e)
17175 (with-current-buffer frombuf
17176 (icalendar-export-region (point-min) (point-max) tmpfile)
17177 (setq buf (find-buffer-visiting tmpfile))
17178 (set-buffer buf)
17179 (goto-char (point-min))
17180 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17181 (setq b (match-beginning 0)))
17182 (goto-char (point-max))
17183 (if (re-search-backward "^END:VEVENT" nil t)
17184 (setq e (match-end 0)))
17185 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17186 (kill-buffer buf)
17187 (delete-file tmpfile)
17188 rtn))
17190 (defun org-closest-date (start current change prefer show-all)
17191 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17192 When PREFER is `past', return a date that is either CURRENT or past.
17193 When PREFER is `future', return a date that is either CURRENT or future.
17194 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17195 ;; Make the proper lists from the dates
17196 (catch 'exit
17197 (let ((a1 '(("h" . hour)
17198 ("d" . day)
17199 ("w" . week)
17200 ("m" . month)
17201 ("y" . year)))
17202 (shour (nth 2 (org-parse-time-string start)))
17203 dn dw sday cday n1 n2 n0
17204 d m y y1 y2 date1 date2 nmonths nm ny m2)
17206 (setq start (org-date-to-gregorian start)
17207 current (org-date-to-gregorian
17208 (if show-all
17209 current
17210 (time-to-days (current-time))))
17211 sday (calendar-absolute-from-gregorian start)
17212 cday (calendar-absolute-from-gregorian current))
17214 (if (<= cday sday) (throw 'exit sday))
17216 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17217 (setq dn (string-to-number (match-string 1 change))
17218 dw (cdr (assoc (match-string 2 change) a1)))
17219 (user-error "Invalid change specifier: %s" change))
17220 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17221 (cond
17222 ((eq dw 'hour)
17223 (let ((missing-hours
17224 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17225 dn)))
17226 (setq n1 (if (zerop missing-hours) cday
17227 (- cday (1+ (floor (/ missing-hours 24)))))
17228 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17229 ((eq dw 'day)
17230 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17231 n2 (+ n1 dn)))
17232 ((eq dw 'year)
17233 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17234 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17235 (setq date1 (list m d y1)
17236 n1 (calendar-absolute-from-gregorian date1)
17237 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17238 n2 (calendar-absolute-from-gregorian date2)))
17239 ((eq dw 'month)
17240 ;; approx number of month between the two dates
17241 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17242 ;; How often does dn fit in there?
17243 (setq d (nth 1 start) m (car start) y (nth 2 start)
17244 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17245 m (+ m nm)
17246 ny (floor (/ m 12))
17247 y (+ y ny)
17248 m (- m (* ny 12)))
17249 (while (> m 12) (setq m (- m 12) y (1+ y)))
17250 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17251 (setq m2 (+ m dn) y2 y)
17252 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17253 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17254 (while (<= n2 cday)
17255 (setq n1 n2 m m2 y y2)
17256 (setq m2 (+ m dn) y2 y)
17257 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17258 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17259 ;; Make sure n1 is the earlier date
17260 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17261 (if show-all
17262 (cond
17263 ((eq prefer 'past) (if (= cday n2) n2 n1))
17264 ((eq prefer 'future) (if (= cday n1) n1 n2))
17265 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17266 (cond
17267 ((eq prefer 'past) (if (= cday n2) n2 n1))
17268 ((eq prefer 'future) (if (= cday n1) n1 n2))
17269 (t (if (= cday n1) n1 n2)))))))
17271 (defun org-date-to-gregorian (date)
17272 "Turn any specification of DATE into a Gregorian date for the calendar."
17273 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17274 ((and (listp date) (= (length date) 3)) date)
17275 ((stringp date)
17276 (setq date (org-parse-time-string date))
17277 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17278 ((listp date)
17279 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17281 (defun org-parse-time-string (s &optional nodefault)
17282 "Parse the standard Org-mode time string.
17283 This should be a lot faster than the normal `parse-time-string'.
17284 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17285 hour and minute fields will be nil if not given."
17286 (cond ((string-match org-ts-regexp0 s)
17287 (list 0
17288 (if (or (match-beginning 8) (not nodefault))
17289 (string-to-number (or (match-string 8 s) "0")))
17290 (if (or (match-beginning 7) (not nodefault))
17291 (string-to-number (or (match-string 7 s) "0")))
17292 (string-to-number (match-string 4 s))
17293 (string-to-number (match-string 3 s))
17294 (string-to-number (match-string 2 s))
17295 nil nil nil))
17296 ((string-match "^<[^>]+>$" s)
17297 (decode-time (seconds-to-time (org-matcher-time s))))
17298 (t (error "Not a standard Org-mode time string: %s" s))))
17300 (defun org-timestamp-up (&optional arg)
17301 "Increase the date item at the cursor by one.
17302 If the cursor is on the year, change the year. If it is on the month,
17303 the day or the time, change that.
17304 With prefix ARG, change by that many units."
17305 (interactive "p")
17306 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17308 (defun org-timestamp-down (&optional arg)
17309 "Decrease the date item at the cursor by one.
17310 If the cursor is on the year, change the year. If it is on the month,
17311 the day or the time, change that.
17312 With prefix ARG, change by that many units."
17313 (interactive "p")
17314 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17316 (defun org-timestamp-up-day (&optional arg)
17317 "Increase the date in the time stamp by one day.
17318 With prefix ARG, change that many days."
17319 (interactive "p")
17320 (if (and (not (org-at-timestamp-p t))
17321 (org-at-heading-p))
17322 (org-todo 'up)
17323 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17325 (defun org-timestamp-down-day (&optional arg)
17326 "Decrease the date in the time stamp by one day.
17327 With prefix ARG, change that many days."
17328 (interactive "p")
17329 (if (and (not (org-at-timestamp-p t))
17330 (org-at-heading-p))
17331 (org-todo 'down)
17332 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17334 (defun org-at-timestamp-p (&optional inactive-ok)
17335 "Determine if the cursor is in or at a timestamp."
17336 (interactive)
17337 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17338 (pos (point))
17339 (ans (or (looking-at tsr)
17340 (save-excursion
17341 (skip-chars-backward "^[<\n\r\t")
17342 (if (> (point) (point-min)) (backward-char 1))
17343 (and (looking-at tsr)
17344 (> (- (match-end 0) pos) -1))))))
17345 (and ans
17346 (boundp 'org-ts-what)
17347 (setq org-ts-what
17348 (cond
17349 ((= pos (match-beginning 0)) 'bracket)
17350 ;; Point is considered to be "on the bracket" whether
17351 ;; it's really on it or right after it.
17352 ((= pos (1- (match-end 0))) 'bracket)
17353 ((= pos (match-end 0)) 'after)
17354 ((org-pos-in-match-range pos 2) 'year)
17355 ((org-pos-in-match-range pos 3) 'month)
17356 ((org-pos-in-match-range pos 7) 'hour)
17357 ((org-pos-in-match-range pos 8) 'minute)
17358 ((or (org-pos-in-match-range pos 4)
17359 (org-pos-in-match-range pos 5)) 'day)
17360 ((and (> pos (or (match-end 8) (match-end 5)))
17361 (< pos (match-end 0)))
17362 (- pos (or (match-end 8) (match-end 5))))
17363 (t 'day))))
17364 ans))
17366 (defun org-toggle-timestamp-type ()
17367 "Toggle the type (<active> or [inactive]) of a time stamp."
17368 (interactive)
17369 (when (org-at-timestamp-p t)
17370 (let ((beg (match-beginning 0)) (end (match-end 0))
17371 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17372 (save-excursion
17373 (goto-char beg)
17374 (while (re-search-forward "[][<>]" end t)
17375 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17376 t t)))
17377 (message "Timestamp is now %sactive"
17378 (if (equal (char-after beg) ?<) "" "in")))))
17380 (defun org-at-clock-log-p nil
17381 "Is the cursor on the clock log line?"
17382 (save-excursion
17383 (move-beginning-of-line 1)
17384 (looking-at "^[ \t]*CLOCK:")))
17386 (defvar org-clock-history) ; defined in org-clock.el
17387 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17388 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17389 "Change the date in the time stamp at point.
17390 The date will be changed by N times WHAT. WHAT can be `day', `month',
17391 `year', `minute', `second'. If WHAT is not given, the cursor position
17392 in the timestamp determines what will be changed.
17393 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17394 (let ((origin (point)) origin-cat
17395 with-hm inactive
17396 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17397 org-ts-what
17398 extra rem
17399 ts time time0 fixnext clrgx)
17400 (if (not (org-at-timestamp-p t))
17401 (user-error "Not at a timestamp"))
17402 (if (and (not what) (eq org-ts-what 'bracket))
17403 (org-toggle-timestamp-type)
17404 ;; Point isn't on brackets. Remember the part of the time-stamp
17405 ;; the point was in. Indeed, size of time-stamps may change,
17406 ;; but point must be kept in the same category nonetheless.
17407 (setq origin-cat org-ts-what)
17408 (if (and (not what) (not (eq org-ts-what 'day))
17409 org-display-custom-times
17410 (get-text-property (point) 'display)
17411 (not (get-text-property (1- (point)) 'display)))
17412 (setq org-ts-what 'day))
17413 (setq org-ts-what (or what org-ts-what)
17414 inactive (= (char-after (match-beginning 0)) ?\[)
17415 ts (match-string 0))
17416 (replace-match "")
17417 (when (string-match
17418 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17420 (setq extra (match-string 1 ts))
17421 (if suppress-tmp-delay
17422 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17423 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17424 (setq with-hm t))
17425 (setq time0 (org-parse-time-string ts))
17426 (when (and updown
17427 (eq org-ts-what 'minute)
17428 (not current-prefix-arg))
17429 ;; This looks like s-up and s-down. Change by one rounding step.
17430 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17431 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17432 (setcar (cdr time0) (+ (nth 1 time0)
17433 (if (> n 0) (- rem) (- dm rem))))))
17434 (setq time
17435 (encode-time (or (car time0) 0)
17436 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17437 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17438 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17439 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17440 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17441 (nthcdr 6 time0)))
17442 (when (and (member org-ts-what '(hour minute))
17443 extra
17444 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17445 (setq extra (org-modify-ts-extra
17446 extra
17447 (if (eq org-ts-what 'hour) 2 5)
17448 n dm)))
17449 (when (integerp org-ts-what)
17450 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17451 (if (eq what 'calendar)
17452 (let ((cal-date (org-get-date-from-calendar)))
17453 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17454 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17455 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17456 (setcar time0 (or (car time0) 0))
17457 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17458 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17459 (setq time (apply 'encode-time time0))))
17460 ;; Insert the new time-stamp, and ensure point stays in the same
17461 ;; category as before (i.e. not after the last position in that
17462 ;; category).
17463 (let ((pos (point)))
17464 ;; Stay before inserted string. `save-excursion' is of no use.
17465 (setq org-last-changed-timestamp
17466 (org-insert-time-stamp time with-hm inactive nil nil extra))
17467 (goto-char pos))
17468 (save-match-data
17469 (looking-at org-ts-regexp3)
17470 (goto-char (cond
17471 ;; `day' category ends before `hour' if any, or at
17472 ;; the end of the day name.
17473 ((eq origin-cat 'day)
17474 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17475 ((eq origin-cat 'hour) (min (match-end 7) origin))
17476 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17477 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17478 ;; `year' and `month' have both fixed size: point
17479 ;; couldn't have moved into another part.
17480 (t origin))))
17481 ;; Update clock if on a CLOCK line.
17482 (org-clock-update-time-maybe)
17483 ;; Maybe adjust the closest clock in `org-clock-history'
17484 (when org-clock-adjust-closest
17485 (if (not (and (org-at-clock-log-p)
17486 (< 1 (length (delq nil (mapcar 'marker-position
17487 org-clock-history))))))
17488 (message "No clock to adjust")
17489 (cond ((save-excursion ; fix previous clock?
17490 (re-search-backward org-ts-regexp0 nil t)
17491 (org-looking-back (concat org-clock-string " \\[")))
17492 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17493 ((save-excursion ; fix next clock?
17494 (re-search-backward org-ts-regexp0 nil t)
17495 (looking-at (concat org-ts-regexp0 "\\] =>")))
17496 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17497 (save-window-excursion
17498 ;; Find closest clock to point, adjust the previous/next one in history
17499 (let* ((p (save-excursion (org-back-to-heading t)))
17500 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17501 (clfixnth
17502 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17503 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17504 (if (not clfixpos)
17505 (message "No clock to adjust")
17506 (save-excursion
17507 (org-goto-marker-or-bmk clfixpos)
17508 (org-show-subtree)
17509 (when (re-search-forward clrgx nil t)
17510 (goto-char (match-beginning 1))
17511 (let (org-clock-adjust-closest)
17512 (org-timestamp-change n org-ts-what updown))
17513 (message "Clock adjusted in %s for heading: %s"
17514 (file-name-nondirectory (buffer-file-name))
17515 (org-get-heading t t)))))))))
17516 ;; Try to recenter the calendar window, if any.
17517 (if (and org-calendar-follow-timestamp-change
17518 (get-buffer-window "*Calendar*" t)
17519 (memq org-ts-what '(day month year)))
17520 (org-recenter-calendar (time-to-days time))))))
17522 (defun org-modify-ts-extra (s pos n dm)
17523 "Change the different parts of the lead-time and repeat fields in timestamp."
17524 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17525 ng h m new rem)
17526 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17527 (cond
17528 ((or (org-pos-in-match-range pos 2)
17529 (org-pos-in-match-range pos 3))
17530 (setq m (string-to-number (match-string 3 s))
17531 h (string-to-number (match-string 2 s)))
17532 (if (org-pos-in-match-range pos 2)
17533 (setq h (+ h n))
17534 (setq n (* dm (org-no-warnings (signum n))))
17535 (when (not (= 0 (setq rem (% m dm))))
17536 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17537 (setq m (+ m n)))
17538 (if (< m 0) (setq m (+ m 60) h (1- h)))
17539 (if (> m 59) (setq m (- m 60) h (1+ h)))
17540 (setq h (min 24 (max 0 h)))
17541 (setq ng 1 new (format "-%02d:%02d" h m)))
17542 ((org-pos-in-match-range pos 6)
17543 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17544 ((org-pos-in-match-range pos 5)
17545 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17547 ((org-pos-in-match-range pos 9)
17548 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17549 ((org-pos-in-match-range pos 8)
17550 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17552 (when ng
17553 (setq s (concat
17554 (substring s 0 (match-beginning ng))
17556 (substring s (match-end ng))))))
17559 (defun org-recenter-calendar (date)
17560 "If the calendar is visible, recenter it to DATE."
17561 (let ((cwin (get-buffer-window "*Calendar*" t)))
17562 (when cwin
17563 (let ((calendar-move-hook nil))
17564 (with-selected-window cwin
17565 (calendar-goto-date (if (listp date) date
17566 (calendar-gregorian-from-absolute date))))))))
17568 (defun org-goto-calendar (&optional arg)
17569 "Go to the Emacs calendar at the current date.
17570 If there is a time stamp in the current line, go to that date.
17571 A prefix ARG can be used to force the current date."
17572 (interactive "P")
17573 (let ((tsr org-ts-regexp) diff
17574 (calendar-move-hook nil)
17575 (calendar-view-holidays-initially-flag nil)
17576 (calendar-view-diary-initially-flag nil))
17577 (if (or (org-at-timestamp-p)
17578 (save-excursion
17579 (beginning-of-line 1)
17580 (looking-at (concat ".*" tsr))))
17581 (let ((d1 (time-to-days (current-time)))
17582 (d2 (time-to-days
17583 (org-time-string-to-time (match-string 1)))))
17584 (setq diff (- d2 d1))))
17585 (calendar)
17586 (calendar-goto-today)
17587 (if (and diff (not arg)) (calendar-forward-day diff))))
17589 (defun org-get-date-from-calendar ()
17590 "Return a list (month day year) of date at point in calendar."
17591 (with-current-buffer "*Calendar*"
17592 (save-match-data
17593 (calendar-cursor-to-date))))
17595 (defun org-date-from-calendar ()
17596 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17597 If there is already a time stamp at the cursor position, update it."
17598 (interactive)
17599 (if (org-at-timestamp-p t)
17600 (org-timestamp-change 0 'calendar)
17601 (let ((cal-date (org-get-date-from-calendar)))
17602 (org-insert-time-stamp
17603 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17605 (defcustom org-effort-durations
17606 `(("h" . 60)
17607 ("d" . ,(* 60 8))
17608 ("w" . ,(* 60 8 5))
17609 ("m" . ,(* 60 8 5 4))
17610 ("y" . ,(* 60 8 5 40)))
17611 "Conversion factor to minutes for an effort modifier.
17613 Each entry has the form (MODIFIER . MINUTES).
17615 In an effort string, a number followed by MODIFIER is multiplied
17616 by the specified number of MINUTES to obtain an effort in
17617 minutes.
17619 For example, if the value of this variable is ((\"hours\" . 60)), then an
17620 effort string \"2hours\" is equivalent to 120 minutes."
17621 :group 'org-agenda
17622 :version "24.1"
17623 :type '(alist :key-type (string :tag "Modifier")
17624 :value-type (number :tag "Minutes")))
17626 (defun org-minutes-to-clocksum-string (m)
17627 "Format number of minutes as a clocksum string.
17628 The format is determined by `org-time-clocksum-format',
17629 `org-time-clocksum-use-fractional' and
17630 `org-time-clocksum-fractional-format' and
17631 `org-time-clocksum-use-effort-durations'."
17632 (let ((clocksum "")
17633 (m (round m)) ; Don't allow fractions of minutes
17634 h d w mo y fmt n)
17635 (setq h (if org-time-clocksum-use-effort-durations
17636 (cdr (assoc "h" org-effort-durations)) 60)
17637 d (if org-time-clocksum-use-effort-durations
17638 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17639 w (if org-time-clocksum-use-effort-durations
17640 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17641 mo (if org-time-clocksum-use-effort-durations
17642 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17643 y (if org-time-clocksum-use-effort-durations
17644 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17645 ;; fractional format
17646 (if org-time-clocksum-use-fractional
17647 (cond
17648 ;; single format string
17649 ((stringp org-time-clocksum-fractional-format)
17650 (format org-time-clocksum-fractional-format (/ m (float h))))
17651 ;; choice of fractional formats for different time units
17652 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17653 (> (/ (truncate m) (* y d h)) 0))
17654 (format fmt (/ m (* y d (float h)))))
17655 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17656 (> (/ (truncate m) (* mo d h)) 0))
17657 (format fmt (/ m (* mo d (float h)))))
17658 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17659 (> (/ (truncate m) (* w d h)) 0))
17660 (format fmt (/ m (* w d (float h)))))
17661 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17662 (> (/ (truncate m) (* d h)) 0))
17663 (format fmt (/ m (* d (float h)))))
17664 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17665 (> (/ (truncate m) h) 0))
17666 (format fmt (/ m (float h))))
17667 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17668 (format fmt m))
17669 ;; fall back to smallest time unit with a format
17670 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17671 (format fmt (/ m (float h))))
17672 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17673 (format fmt (/ m (* d (float h)))))
17674 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17675 (format fmt (/ m (* w d (float h)))))
17676 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17677 (format fmt (/ m (* mo d (float h)))))
17678 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17679 (format fmt (/ m (* y d (float h))))))
17680 ;; standard (non-fractional) format, with single format string
17681 (if (stringp org-time-clocksum-format)
17682 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17683 ;; separate formats components
17684 (and (setq fmt (plist-get org-time-clocksum-format :years))
17685 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17686 (plist-get org-time-clocksum-format :require-years))
17687 (setq clocksum (concat clocksum (format fmt n))
17688 m (- m (* n y d h))))
17689 (and (setq fmt (plist-get org-time-clocksum-format :months))
17690 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17691 (plist-get org-time-clocksum-format :require-months))
17692 (setq clocksum (concat clocksum (format fmt n))
17693 m (- m (* n mo d h))))
17694 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17695 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17696 (plist-get org-time-clocksum-format :require-weeks))
17697 (setq clocksum (concat clocksum (format fmt n))
17698 m (- m (* n w d h))))
17699 (and (setq fmt (plist-get org-time-clocksum-format :days))
17700 (or (> (setq n (/ (truncate m) (* d h))) 0)
17701 (plist-get org-time-clocksum-format :require-days))
17702 (setq clocksum (concat clocksum (format fmt n))
17703 m (- m (* n d h))))
17704 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17705 (or (> (setq n (/ (truncate m) h)) 0)
17706 (plist-get org-time-clocksum-format :require-hours))
17707 (setq clocksum (concat clocksum (format fmt n))
17708 m (- m (* n h))))
17709 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17710 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17711 (setq clocksum (concat clocksum (format fmt m))))
17712 ;; return formatted time duration
17713 clocksum))))
17715 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17716 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17717 "Org mode version 8.0")
17719 (defun org-hours-to-clocksum-string (n)
17720 (org-minutes-to-clocksum-string (* n 60)))
17722 (defun org-hh:mm-string-to-minutes (s)
17723 "Convert a string H:MM to a number of minutes.
17724 If the string is just a number, interpret it as minutes.
17725 In fact, the first hh:mm or number in the string will be taken,
17726 there can be extra stuff in the string.
17727 If no number is found, the return value is 0."
17728 (cond
17729 ((integerp s) s)
17730 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17731 (+ (* (string-to-number (match-string 1 s)) 60)
17732 (string-to-number (match-string 2 s))))
17733 ((string-match "\\([0-9]+\\)" s)
17734 (string-to-number (match-string 1 s)))
17735 (t 0)))
17737 (defcustom org-image-actual-width t
17738 "Should we use the actual width of images when inlining them?
17740 When set to `t', always use the image width.
17742 When set to a number, use imagemagick (when available) to set
17743 the image's width to this value.
17745 When set to a number in a list, try to get the width from any
17746 #+ATTR.* keyword if it matches a width specification like
17748 #+ATTR_HTML: :width 300px
17750 and fall back on that number if none is found.
17752 When set to nil, try to get the width from an #+ATTR.* keyword
17753 and fall back on the original width if none is found.
17755 This requires Emacs >= 24.1, build with imagemagick support."
17756 :group 'org-appearance
17757 :version "24.4"
17758 :package-version '(Org . "8.0")
17759 :type '(choice
17760 (const :tag "Use the image width" t)
17761 (integer :tag "Use a number of pixels")
17762 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17763 (const :tag "Use #+ATTR* or don't resize" nil)))
17765 (defcustom org-agenda-inhibit-startup nil
17766 "Inhibit startup when preparing agenda buffers.
17767 When this variable is `t' (the default), the initialization of
17768 the Org agenda buffers is inhibited: e.g. the visibility state
17769 is not set, the tables are not re-aligned, etc."
17770 :type 'boolean
17771 :version "24.3"
17772 :group 'org-agenda)
17774 (defcustom org-agenda-ignore-drawer-properties nil
17775 "Avoid updating text properties when building the agenda.
17776 Properties are used to prepare buffers for effort estimates, appointments,
17777 and subtree-local categories.
17778 If you don't use these in the agenda, you can add them to this list and
17779 agenda building will be a bit faster.
17780 The value is a list, with zero or more of the symbols `effort', `appt',
17781 or `category'."
17782 :type '(set :greedy t
17783 (const effort)
17784 (const appt)
17785 (const category))
17786 :version "24.3"
17787 :group 'org-agenda)
17789 (defun org-duration-string-to-minutes (s &optional output-to-string)
17790 "Convert a duration string S to minutes.
17792 A bare number is interpreted as minutes, modifiers can be set by
17793 customizing `org-effort-durations' (which see).
17795 Entries containing a colon are interpreted as H:MM by
17796 `org-hh:mm-string-to-minutes'."
17797 (let ((result 0)
17798 (re (concat "\\([0-9.]+\\) *\\("
17799 (regexp-opt (mapcar 'car org-effort-durations))
17800 "\\)")))
17801 (while (string-match re s)
17802 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17803 (string-to-number (match-string 1 s))))
17804 (setq s (replace-match "" nil t s)))
17805 (setq result (floor result))
17806 (incf result (org-hh:mm-string-to-minutes s))
17807 (if output-to-string (number-to-string result) result)))
17809 ;;;; Files
17811 (defun org-save-all-org-buffers ()
17812 "Save all Org-mode buffers without user confirmation."
17813 (interactive)
17814 (message "Saving all Org-mode buffers...")
17815 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17816 (when (featurep 'org-id) (org-id-locations-save))
17817 (message "Saving all Org-mode buffers... done"))
17819 (defun org-revert-all-org-buffers ()
17820 "Revert all Org-mode buffers.
17821 Prompt for confirmation when there are unsaved changes.
17822 Be sure you know what you are doing before letting this function
17823 overwrite your changes.
17825 This function is useful in a setup where one tracks org files
17826 with a version control system, to revert on one machine after pulling
17827 changes from another. I believe the procedure must be like this:
17829 1. M-x org-save-all-org-buffers
17830 2. Pull changes from the other machine, resolve conflicts
17831 3. M-x org-revert-all-org-buffers"
17832 (interactive)
17833 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17834 (user-error "Abort"))
17835 (save-excursion
17836 (save-window-excursion
17837 (mapc
17838 (lambda (b)
17839 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17840 (with-current-buffer b buffer-file-name))
17841 (org-pop-to-buffer-same-window b)
17842 (revert-buffer t 'no-confirm)))
17843 (buffer-list))
17844 (when (and (featurep 'org-id) org-id-track-globally)
17845 (org-id-locations-load)))))
17847 ;;;; Agenda files
17849 ;;;###autoload
17850 (defun org-switchb (&optional arg)
17851 "Switch between Org buffers.
17852 With one prefix argument, restrict available buffers to files.
17853 With two prefix arguments, restrict available buffers to agenda files.
17855 Defaults to `iswitchb' for buffer name completion.
17856 Set `org-completion-use-ido' to make it use ido instead."
17857 (interactive "P")
17858 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17859 ((equal arg '(16)) (org-buffer-list 'agenda))
17860 (t (org-buffer-list))))
17861 (org-completion-use-iswitchb org-completion-use-iswitchb)
17862 (org-completion-use-ido org-completion-use-ido))
17863 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17864 (setq org-completion-use-iswitchb t))
17865 (org-pop-to-buffer-same-window
17866 (org-icompleting-read "Org buffer: "
17867 (mapcar 'list (mapcar 'buffer-name blist))
17868 nil t))))
17870 ;;; Define some older names previously used for this functionality
17871 ;;;###autoload
17872 (defalias 'org-ido-switchb 'org-switchb)
17873 ;;;###autoload
17874 (defalias 'org-iswitchb 'org-switchb)
17876 (defun org-buffer-list (&optional predicate exclude-tmp)
17877 "Return a list of Org buffers.
17878 PREDICATE can be `export', `files' or `agenda'.
17880 export restrict the list to Export buffers.
17881 files restrict the list to buffers visiting Org files.
17882 agenda restrict the list to buffers visiting agenda files.
17884 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17885 (let* ((bfn nil)
17886 (agenda-files (and (eq predicate 'agenda)
17887 (mapcar 'file-truename (org-agenda-files t))))
17888 (filter
17889 (cond
17890 ((eq predicate 'files)
17891 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17892 ((eq predicate 'export)
17893 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17894 ((eq predicate 'agenda)
17895 (lambda (b)
17896 (with-current-buffer b
17897 (and (derived-mode-p 'org-mode)
17898 (setq bfn (buffer-file-name b))
17899 (member (file-truename bfn) agenda-files)))))
17900 (t (lambda (b) (with-current-buffer b
17901 (or (derived-mode-p 'org-mode)
17902 (string-match "\*Org .*Export"
17903 (buffer-name b)))))))))
17904 (delq nil
17905 (mapcar
17906 (lambda(b)
17907 (if (and (funcall filter b)
17908 (or (not exclude-tmp)
17909 (not (string-match "tmp" (buffer-name b)))))
17911 nil))
17912 (buffer-list)))))
17914 (defun org-agenda-files (&optional unrestricted archives)
17915 "Get the list of agenda files.
17916 Optional UNRESTRICTED means return the full list even if a restriction
17917 is currently in place.
17918 When ARCHIVES is t, include all archive files that are really being
17919 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17920 `org-agenda-archives-mode' is t."
17921 (let ((files
17922 (cond
17923 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17924 ((stringp org-agenda-files) (org-read-agenda-file-list))
17925 ((listp org-agenda-files) org-agenda-files)
17926 (t (error "Invalid value of `org-agenda-files'")))))
17927 (setq files (apply 'append
17928 (mapcar (lambda (f)
17929 (if (file-directory-p f)
17930 (directory-files
17931 f t org-agenda-file-regexp)
17932 (list f)))
17933 files)))
17934 (when org-agenda-skip-unavailable-files
17935 (setq files (delq nil
17936 (mapcar (function
17937 (lambda (file)
17938 (and (file-readable-p file) file)))
17939 files))))
17940 (when (or (eq archives t)
17941 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17942 (setq files (org-add-archive-files files)))
17943 files))
17945 (defun org-agenda-file-p (&optional file)
17946 "Return non-nil, if FILE is an agenda file.
17947 If FILE is omitted, use the file associated with the current
17948 buffer."
17949 (member (or file (buffer-file-name))
17950 (org-agenda-files t)))
17952 (defun org-edit-agenda-file-list ()
17953 "Edit the list of agenda files.
17954 Depending on setup, this either uses customize to edit the variable
17955 `org-agenda-files', or it visits the file that is holding the list. In the
17956 latter case, the buffer is set up in a way that saving it automatically kills
17957 the buffer and restores the previous window configuration."
17958 (interactive)
17959 (if (stringp org-agenda-files)
17960 (let ((cw (current-window-configuration)))
17961 (find-file org-agenda-files)
17962 (org-set-local 'org-window-configuration cw)
17963 (org-add-hook 'after-save-hook
17964 (lambda ()
17965 (set-window-configuration
17966 (prog1 org-window-configuration
17967 (kill-buffer (current-buffer))))
17968 (org-install-agenda-files-menu)
17969 (message "New agenda file list installed"))
17970 nil 'local)
17971 (message "%s" (substitute-command-keys
17972 "Edit list and finish with \\[save-buffer]")))
17973 (customize-variable 'org-agenda-files)))
17975 (defun org-store-new-agenda-file-list (list)
17976 "Set new value for the agenda file list and save it correctly."
17977 (if (stringp org-agenda-files)
17978 (let ((fe (org-read-agenda-file-list t)) b u)
17979 (while (setq b (find-buffer-visiting org-agenda-files))
17980 (kill-buffer b))
17981 (with-temp-file org-agenda-files
17982 (insert
17983 (mapconcat
17984 (lambda (f) ;; Keep un-expanded entries.
17985 (if (setq u (assoc f fe))
17986 (cdr u)
17988 list "\n")
17989 "\n")))
17990 (let ((org-mode-hook nil) (org-inhibit-startup t)
17991 (org-insert-mode-line-in-empty-file nil))
17992 (setq org-agenda-files list)
17993 (customize-save-variable 'org-agenda-files org-agenda-files))))
17995 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17996 "Read the list of agenda files from a file.
17997 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17998 filenames, used by `org-store-new-agenda-file-list' to write back
17999 un-expanded file names."
18000 (when (file-directory-p org-agenda-files)
18001 (error "`org-agenda-files' cannot be a single directory"))
18002 (when (stringp org-agenda-files)
18003 (with-temp-buffer
18004 (insert-file-contents org-agenda-files)
18005 (mapcar
18006 (lambda (f)
18007 (let ((e (expand-file-name (substitute-in-file-name f)
18008 org-directory)))
18009 (if pair-with-expansion
18010 (cons e f)
18011 e)))
18012 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18014 ;;;###autoload
18015 (defun org-cycle-agenda-files ()
18016 "Cycle through the files in `org-agenda-files'.
18017 If the current buffer visits an agenda file, find the next one in the list.
18018 If the current buffer does not, find the first agenda file."
18019 (interactive)
18020 (let* ((fs (org-agenda-files t))
18021 (files (append fs (list (car fs))))
18022 (tcf (if buffer-file-name (file-truename buffer-file-name)))
18023 file)
18024 (unless files (user-error "No agenda files"))
18025 (catch 'exit
18026 (while (setq file (pop files))
18027 (if (equal (file-truename file) tcf)
18028 (when (car files)
18029 (find-file (car files))
18030 (throw 'exit t))))
18031 (find-file (car fs)))
18032 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
18034 (defun org-agenda-file-to-front (&optional to-end)
18035 "Move/add the current file to the top of the agenda file list.
18036 If the file is not present in the list, it is added to the front. If it is
18037 present, it is moved there. With optional argument TO-END, add/move to the
18038 end of the list."
18039 (interactive "P")
18040 (let ((org-agenda-skip-unavailable-files nil)
18041 (file-alist (mapcar (lambda (x)
18042 (cons (file-truename x) x))
18043 (org-agenda-files t)))
18044 (ctf (file-truename
18045 (or buffer-file-name
18046 (user-error "Please save the current buffer to a file"))))
18047 x had)
18048 (setq x (assoc ctf file-alist) had x)
18050 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18051 (if to-end
18052 (setq file-alist (append (delq x file-alist) (list x)))
18053 (setq file-alist (cons x (delq x file-alist))))
18054 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18055 (org-install-agenda-files-menu)
18056 (message "File %s to %s of agenda file list"
18057 (if had "moved" "added") (if to-end "end" "front"))))
18059 (defun org-remove-file (&optional file)
18060 "Remove current file from the list of files in variable `org-agenda-files'.
18061 These are the files which are being checked for agenda entries.
18062 Optional argument FILE means use this file instead of the current."
18063 (interactive)
18064 (let* ((org-agenda-skip-unavailable-files nil)
18065 (file (or file buffer-file-name
18066 (user-error "Current buffer does not visit a file")))
18067 (true-file (file-truename file))
18068 (afile (abbreviate-file-name file))
18069 (files (delq nil (mapcar
18070 (lambda (x)
18071 (if (equal true-file
18072 (file-truename x))
18073 nil x))
18074 (org-agenda-files t)))))
18075 (if (not (= (length files) (length (org-agenda-files t))))
18076 (progn
18077 (org-store-new-agenda-file-list files)
18078 (org-install-agenda-files-menu)
18079 (message "Removed file: %s" afile))
18080 (message "File was not in list: %s (not removed)" afile))))
18082 (defun org-file-menu-entry (file)
18083 (vector file (list 'find-file file) t))
18085 (defun org-check-agenda-file (file)
18086 "Make sure FILE exists. If not, ask user what to do."
18087 (when (not (file-exists-p file))
18088 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18089 (abbreviate-file-name file))
18090 (let ((r (downcase (read-char-exclusive))))
18091 (cond
18092 ((equal r ?r)
18093 (org-remove-file file)
18094 (throw 'nextfile t))
18095 (t (error "Abort"))))))
18097 (defun org-get-agenda-file-buffer (file)
18098 "Get a buffer visiting FILE. If the buffer needs to be created, add
18099 it to the list of buffers which might be released later."
18100 (let ((buf (org-find-base-buffer-visiting file)))
18101 (if buf
18102 buf ; just return it
18103 ;; Make a new buffer and remember it
18104 (setq buf (find-file-noselect file))
18105 (if buf (push buf org-agenda-new-buffers))
18106 buf)))
18108 (defun org-release-buffers (blist)
18109 "Release all buffers in list, asking the user for confirmation when needed.
18110 When a buffer is unmodified, it is just killed. When modified, it is saved
18111 \(if the user agrees) and then killed."
18112 (let (buf file)
18113 (while (setq buf (pop blist))
18114 (setq file (buffer-file-name buf))
18115 (when (and (buffer-modified-p buf)
18116 file
18117 (y-or-n-p (format "Save file %s? " file)))
18118 (with-current-buffer buf (save-buffer)))
18119 (kill-buffer buf))))
18121 (defun org-agenda-prepare-buffers (files)
18122 "Create buffers for all agenda files, protect archived trees and comments."
18123 (interactive)
18124 (let ((pa '(:org-archived t))
18125 (pc '(:org-comment t))
18126 (pall '(:org-archived t :org-comment t))
18127 (inhibit-read-only t)
18128 (org-inhibit-startup org-agenda-inhibit-startup)
18129 (rea (concat ":" org-archive-tag ":"))
18130 file re pos)
18131 (setq org-tag-alist-for-agenda nil
18132 org-tag-groups-alist-for-agenda nil)
18133 (save-window-excursion
18134 (save-restriction
18135 (while (setq file (pop files))
18136 (catch 'nextfile
18137 (if (bufferp file)
18138 (set-buffer file)
18139 (org-check-agenda-file file)
18140 (set-buffer (org-get-agenda-file-buffer file)))
18141 (widen)
18142 (org-set-regexps-and-options-for-tags)
18143 (setq pos (point))
18144 (goto-char (point-min))
18145 (let ((case-fold-search t))
18146 (when (search-forward "#+setupfile" nil t)
18147 ;; Don't set all regexps and options systematically as
18148 ;; this is only run for setting agenda tags from setup
18149 ;; file
18150 (org-set-regexps-and-options)))
18151 (or (memq 'category org-agenda-ignore-drawer-properties)
18152 (org-refresh-category-properties))
18153 (or (memq 'effort org-agenda-ignore-drawer-properties)
18154 (org-refresh-properties org-effort-property 'org-effort))
18155 (or (memq 'appt org-agenda-ignore-drawer-properties)
18156 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18157 (setq org-todo-keywords-for-agenda
18158 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18159 (setq org-done-keywords-for-agenda
18160 (append org-done-keywords-for-agenda org-done-keywords))
18161 (setq org-todo-keyword-alist-for-agenda
18162 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18163 (setq org-tag-alist-for-agenda
18164 (org-uniquify
18165 (append org-tag-alist-for-agenda
18166 org-tag-alist
18167 org-tag-persistent-alist)))
18168 (if org-group-tags
18169 (setq org-tag-groups-alist-for-agenda
18170 (org-uniquify-alist
18171 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18172 (org-with-silent-modifications
18173 (save-excursion
18174 (remove-text-properties (point-min) (point-max) pall)
18175 (when org-agenda-skip-archived-trees
18176 (goto-char (point-min))
18177 (while (re-search-forward rea nil t)
18178 (if (org-at-heading-p t)
18179 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18180 (goto-char (point-min))
18181 (setq re (format org-heading-keyword-regexp-format
18182 org-comment-string))
18183 (while (re-search-forward re nil t)
18184 (add-text-properties
18185 (match-beginning 0) (org-end-of-subtree t) pc))))
18186 (goto-char pos)))))
18187 (setq org-todo-keywords-for-agenda
18188 (org-uniquify org-todo-keywords-for-agenda))
18189 (setq org-todo-keyword-alist-for-agenda
18190 (org-uniquify org-todo-keyword-alist-for-agenda))))
18193 ;;;; CDLaTeX minor mode
18195 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18196 "Keymap for the minor `org-cdlatex-mode'.")
18198 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18199 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18200 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18201 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18202 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
18204 (defvar org-cdlatex-texmathp-advice-is-done nil
18205 "Flag remembering if we have applied the advice to texmathp already.")
18207 (define-minor-mode org-cdlatex-mode
18208 "Toggle the minor `org-cdlatex-mode'.
18209 This mode supports entering LaTeX environment and math in LaTeX fragments
18210 in Org-mode.
18211 \\{org-cdlatex-mode-map}"
18212 nil " OCDL" nil
18213 (when org-cdlatex-mode
18214 (require 'cdlatex)
18215 (run-hooks 'cdlatex-mode-hook)
18216 (cdlatex-compute-tables))
18217 (unless org-cdlatex-texmathp-advice-is-done
18218 (setq org-cdlatex-texmathp-advice-is-done t)
18219 (defadvice texmathp (around org-math-always-on activate)
18220 "Always return t in org-mode buffers.
18221 This is because we want to insert math symbols without dollars even outside
18222 the LaTeX math segments. If Orgmode thinks that point is actually inside
18223 an embedded LaTeX fragment, let texmathp do its job.
18224 \\[org-cdlatex-mode-map]"
18225 (interactive)
18226 (let (p)
18227 (cond
18228 ((not (derived-mode-p 'org-mode)) ad-do-it)
18229 ((eq this-command 'cdlatex-math-symbol)
18230 (setq ad-return-value t
18231 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18233 (let ((p (org-inside-LaTeX-fragment-p)))
18234 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18235 (setq ad-return-value t
18236 texmathp-why '("Org-mode embedded math" . 0))
18237 (if p ad-do-it)))))))))
18239 (defun turn-on-org-cdlatex ()
18240 "Unconditionally turn on `org-cdlatex-mode'."
18241 (org-cdlatex-mode 1))
18243 (defun org-try-cdlatex-tab ()
18244 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18245 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18246 - inside a LaTeX fragment, or
18247 - after the first word in a line, where an abbreviation expansion could
18248 insert a LaTeX environment."
18249 (when org-cdlatex-mode
18250 (cond
18251 ;; Before any word on the line: No expansion possible.
18252 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18253 ;; Just after first word on the line: Expand it. Make sure it
18254 ;; cannot happen on headlines, though.
18255 ((save-excursion
18256 (skip-chars-backward "a-zA-Z0-9*")
18257 (skip-chars-backward " \t")
18258 (and (bolp) (not (org-at-heading-p))))
18259 (cdlatex-tab) t)
18260 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18262 (defun org-cdlatex-underscore-caret (&optional arg)
18263 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18264 Revert to the normal definition outside of these fragments."
18265 (interactive "P")
18266 (if (org-inside-LaTeX-fragment-p)
18267 (call-interactively 'cdlatex-sub-superscript)
18268 (let (org-cdlatex-mode)
18269 (call-interactively (key-binding (vector last-input-event))))))
18271 (defun org-cdlatex-math-modify (&optional arg)
18272 "Execute `cdlatex-math-modify' in LaTeX fragments.
18273 Revert to the normal definition outside of these fragments."
18274 (interactive "P")
18275 (if (org-inside-LaTeX-fragment-p)
18276 (call-interactively 'cdlatex-math-modify)
18277 (let (org-cdlatex-mode)
18278 (call-interactively (key-binding (vector last-input-event))))))
18282 ;;;; LaTeX fragments
18284 (defun org-inside-LaTeX-fragment-p ()
18285 "Test if point is inside a LaTeX fragment.
18286 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18287 sequence appearing also before point.
18288 Even though the matchers for math are configurable, this function assumes
18289 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18290 delimiters are skipped when they have been removed by customization.
18291 The return value is nil, or a cons cell with the delimiter and the
18292 position of this delimiter.
18294 This function does a reasonably good job, but can locally be fooled by
18295 for example currency specifications. For example it will assume being in
18296 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18297 fragments that are properly closed, but during editing, we have to live
18298 with the uncertainty caused by missing closing delimiters. This function
18299 looks only before point, not after."
18300 (catch 'exit
18301 (let ((pos (point))
18302 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18303 (lim (progn
18304 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18305 (point)))
18306 dd-on str (start 0) m re)
18307 (goto-char pos)
18308 (when dodollar
18309 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18310 re (nth 1 (assoc "$" org-latex-regexps)))
18311 (while (string-match re str start)
18312 (cond
18313 ((= (match-end 0) (length str))
18314 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18315 ((= (match-end 0) (- (length str) 5))
18316 (throw 'exit nil))
18317 (t (setq start (match-end 0))))))
18318 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18319 (goto-char pos)
18320 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18321 (and (match-beginning 2) (throw 'exit nil))
18322 ;; count $$
18323 (while (re-search-backward "\\$\\$" lim t)
18324 (setq dd-on (not dd-on)))
18325 (goto-char pos)
18326 (if dd-on (cons "$$" m))))))
18328 (defun org-inside-latex-macro-p ()
18329 "Is point inside a LaTeX macro or its arguments?"
18330 (save-match-data
18331 (org-in-regexp
18332 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18334 (defvar org-latex-fragment-image-overlays nil
18335 "List of overlays carrying the images of latex fragments.")
18336 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18338 (defun org-remove-latex-fragment-image-overlays ()
18339 "Remove all overlays with LaTeX fragment images in current buffer."
18340 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18341 (setq org-latex-fragment-image-overlays nil))
18343 (defun org-preview-latex-fragment (&optional subtree)
18344 "Preview the LaTeX fragment at point, or all locally or globally.
18345 If the cursor is in a LaTeX fragment, create the image and overlay
18346 it over the source code. If there is no fragment at point, display
18347 all fragments in the current text, from one headline to the next. With
18348 prefix SUBTREE, display all fragments in the current subtree. With a
18349 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18350 the cursor is before the first headline,
18351 display all fragments in the buffer.
18352 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18353 (interactive "P")
18354 (unless buffer-file-name
18355 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18356 (when (display-graphic-p)
18357 (org-remove-latex-fragment-image-overlays)
18358 (save-excursion
18359 (save-restriction
18360 (let (beg end at msg)
18361 (cond
18362 ((or (equal subtree '(16))
18363 (not (save-excursion
18364 (re-search-backward org-outline-regexp-bol nil t))))
18365 (setq beg (point-min) end (point-max)
18366 msg "Creating images for buffer...%s"))
18367 ((equal subtree '(4))
18368 (org-back-to-heading)
18369 (setq beg (point) end (org-end-of-subtree t)
18370 msg "Creating images for subtree...%s"))
18372 (if (setq at (org-inside-LaTeX-fragment-p))
18373 (goto-char (max (point-min) (- (cdr at) 2)))
18374 (org-back-to-heading))
18375 (setq beg (point) end (progn (outline-next-heading) (point))
18376 msg (if at "Creating image...%s"
18377 "Creating images for entry...%s"))))
18378 (message msg "")
18379 (narrow-to-region beg end)
18380 (goto-char beg)
18381 (org-format-latex
18382 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18383 (file-name-nondirectory
18384 buffer-file-name)))
18385 default-directory 'overlays msg at 'forbuffer
18386 org-latex-create-formula-image-program)
18387 (message msg "done. Use `C-c C-c' to remove images."))))))
18389 (defun org-format-latex (prefix &optional dir overlays msg at
18390 forbuffer processing-type)
18391 "Replace LaTeX fragments with links to an image, and produce images.
18392 Some of the options can be changed using the variable
18393 `org-format-latex-options'."
18394 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18395 (let* ((prefixnodir (file-name-nondirectory prefix))
18396 (absprefix (expand-file-name prefix dir))
18397 (todir (file-name-directory absprefix))
18398 (opt org-format-latex-options)
18399 (optnew org-format-latex-options)
18400 (matchers (plist-get opt :matchers))
18401 (re-list org-latex-regexps)
18402 (cnt 0) txt hash link beg end re e checkdir
18403 string
18404 m n block-type block linkfile movefile ov)
18405 ;; Check the different regular expressions
18406 (while (setq e (pop re-list))
18407 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18408 block (if block-type "\n\n" ""))
18409 (when (member m matchers)
18410 (goto-char (point-min))
18411 (while (re-search-forward re nil t)
18412 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18413 (or (not overlays)
18414 (not (eq (get-char-property (match-beginning n)
18415 'org-overlay-type)
18416 'org-latex-overlay))))
18417 (cond
18418 ((eq processing-type 'verbatim))
18419 ((eq processing-type 'mathjax)
18420 ;; Prepare for MathJax processing.
18421 (setq string (match-string n))
18422 (when (member m '("$" "$1"))
18423 (save-excursion
18424 (delete-region (match-beginning n) (match-end n))
18425 (goto-char (match-beginning n))
18426 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18427 ((or (eq processing-type 'dvipng)
18428 (eq processing-type 'imagemagick))
18429 ;; Process to an image.
18430 (setq txt (match-string n)
18431 beg (match-beginning n) end (match-end n)
18432 cnt (1+ cnt))
18433 (let ((face (face-at-point))
18434 (fg (plist-get opt :foreground))
18435 (bg (plist-get opt :background))
18436 ;; Ensure full list is printed.
18437 print-length print-level)
18438 (when forbuffer
18439 ;; Get the colors from the face at point.
18440 (goto-char beg)
18441 (when (eq fg 'auto)
18442 (setq fg (face-attribute face :foreground nil 'default)))
18443 (when (eq bg 'auto)
18444 (setq bg (face-attribute face :background nil 'default)))
18445 (setq optnew (copy-sequence opt))
18446 (plist-put optnew :foreground fg)
18447 (plist-put optnew :background bg))
18448 (setq hash (sha1 (prin1-to-string
18449 (list org-format-latex-header
18450 org-latex-default-packages-alist
18451 org-latex-packages-alist
18452 org-format-latex-options
18453 forbuffer txt fg bg)))
18454 linkfile (format "%s_%s.png" prefix hash)
18455 movefile (format "%s_%s.png" absprefix hash)))
18456 (setq link (concat block "[[file:" linkfile "]]" block))
18457 (if msg (message msg cnt))
18458 (goto-char beg)
18459 (unless checkdir ; Ensure the directory exists.
18460 (setq checkdir t)
18461 (or (file-directory-p todir) (make-directory todir t)))
18462 (unless (file-exists-p movefile)
18463 (org-create-formula-image
18464 txt movefile optnew forbuffer processing-type))
18465 (if overlays
18466 (progn
18467 (mapc (lambda (o)
18468 (if (eq (overlay-get o 'org-overlay-type)
18469 'org-latex-overlay)
18470 (delete-overlay o)))
18471 (overlays-in beg end))
18472 (setq ov (make-overlay beg end))
18473 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18474 (if (featurep 'xemacs)
18475 (progn
18476 (overlay-put ov 'invisible t)
18477 (overlay-put
18478 ov 'end-glyph
18479 (make-glyph (vector 'png :file movefile))))
18480 (overlay-put
18481 ov 'display
18482 (list 'image :type 'png :file movefile :ascent 'center)))
18483 (push ov org-latex-fragment-image-overlays)
18484 (goto-char end))
18485 (delete-region beg end)
18486 (insert (org-add-props link
18487 (list 'org-latex-src
18488 (replace-regexp-in-string
18489 "\"" "" txt)
18490 'org-latex-src-embed-type
18491 (if block-type 'paragraph 'character))))))
18492 ((eq processing-type 'mathml)
18493 ;; Process to MathML
18494 (unless (save-match-data (org-format-latex-mathml-available-p))
18495 (user-error "LaTeX to MathML converter not configured"))
18496 (setq txt (match-string n)
18497 beg (match-beginning n) end (match-end n)
18498 cnt (1+ cnt))
18499 (if msg (message msg cnt))
18500 (goto-char beg)
18501 (delete-region beg end)
18502 (insert (org-format-latex-as-mathml
18503 txt block-type prefix dir)))
18505 (error "Unknown conversion type %s for LaTeX fragments"
18506 processing-type)))))))))
18508 (defun org-create-math-formula (latex-frag &optional mathml-file)
18509 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18510 Use `org-latex-to-mathml-convert-command'. If the conversion is
18511 sucessful, return the portion between \"<math...> </math>\"
18512 elements otherwise return nil. When MATHML-FILE is specified,
18513 write the results in to that file. When invoked as an
18514 interactive command, prompt for LATEX-FRAG, with initial value
18515 set to the current active region and echo the results for user
18516 inspection."
18517 (interactive (list (let ((frag (when (org-region-active-p)
18518 (buffer-substring-no-properties
18519 (region-beginning) (region-end)))))
18520 (read-string "LaTeX Fragment: " frag nil frag))))
18521 (unless latex-frag (error "Invalid LaTeX fragment"))
18522 (let* ((tmp-in-file (file-relative-name
18523 (make-temp-name (expand-file-name "ltxmathml-in"))))
18524 (ignore (write-region latex-frag nil tmp-in-file))
18525 (tmp-out-file (file-relative-name
18526 (make-temp-name (expand-file-name "ltxmathml-out"))))
18527 (cmd (format-spec
18528 org-latex-to-mathml-convert-command
18529 `((?j . ,(shell-quote-argument
18530 (expand-file-name org-latex-to-mathml-jar-file)))
18531 (?I . ,(shell-quote-argument tmp-in-file))
18532 (?o . ,(shell-quote-argument tmp-out-file)))))
18533 mathml shell-command-output)
18534 (when (org-called-interactively-p 'any)
18535 (unless (org-format-latex-mathml-available-p)
18536 (user-error "LaTeX to MathML converter not configured")))
18537 (message "Running %s" cmd)
18538 (setq shell-command-output (shell-command-to-string cmd))
18539 (setq mathml
18540 (when (file-readable-p tmp-out-file)
18541 (with-current-buffer (find-file-noselect tmp-out-file t)
18542 (goto-char (point-min))
18543 (when (re-search-forward
18544 (concat
18545 (regexp-quote
18546 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18547 "\\(.\\|\n\\)*"
18548 (regexp-quote "</math>")) nil t)
18549 (prog1 (match-string 0) (kill-buffer))))))
18550 (cond
18551 (mathml
18552 (setq mathml
18553 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18554 (when mathml-file
18555 (write-region mathml nil mathml-file))
18556 (when (org-called-interactively-p 'any)
18557 (message mathml)))
18558 ((message "LaTeX to MathML conversion failed")
18559 (message shell-command-output)))
18560 (delete-file tmp-in-file)
18561 (when (file-exists-p tmp-out-file)
18562 (delete-file tmp-out-file))
18563 mathml))
18565 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18566 prefix &optional dir)
18567 "Use `org-create-math-formula' but check local cache first."
18568 (let* ((absprefix (expand-file-name prefix dir))
18569 (print-length nil) (print-level nil)
18570 (formula-id (concat
18571 "formula-"
18572 (sha1
18573 (prin1-to-string
18574 (list latex-frag
18575 org-latex-to-mathml-convert-command)))))
18576 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18577 (formula-cache-dir (file-name-directory formula-cache)))
18579 (unless (file-directory-p formula-cache-dir)
18580 (make-directory formula-cache-dir t))
18582 (unless (file-exists-p formula-cache)
18583 (org-create-math-formula latex-frag formula-cache))
18585 (if (file-exists-p formula-cache)
18586 ;; Successful conversion. Return the link to MathML file.
18587 (org-add-props
18588 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18589 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18590 'org-latex-src-embed-type (if latex-frag-type
18591 'paragraph 'character)))
18592 ;; Failed conversion. Return the LaTeX fragment verbatim
18593 latex-frag)))
18595 (defun org-create-formula-image (string tofile options buffer &optional type)
18596 "Create an image from LaTeX source using dvipng or convert.
18597 This function calls either `org-create-formula-image-with-dvipng'
18598 or `org-create-formula-image-with-imagemagick' depending on the
18599 value of `org-latex-create-formula-image-program' or on the value
18600 of the optional TYPE variable.
18602 Note: ultimately these two function should be combined as they
18603 share a good deal of logic."
18604 (org-check-external-command
18605 "latex" "needed to convert LaTeX fragments to images")
18606 (funcall
18607 (case (or type org-latex-create-formula-image-program)
18608 ('dvipng
18609 (org-check-external-command
18610 "dvipng" "needed to convert LaTeX fragments to images")
18611 #'org-create-formula-image-with-dvipng)
18612 ('imagemagick
18613 (org-check-external-command
18614 "convert" "you need to install imagemagick")
18615 #'org-create-formula-image-with-imagemagick)
18616 (t (error
18617 "Invalid value of `org-latex-create-formula-image-program'")))
18618 string tofile options buffer))
18620 (declare-function org-export-get-backend "ox" (name))
18621 (declare-function org-export--get-global-options "ox" (&optional backend))
18622 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18623 (declare-function org-latex-guess-inputenc "ox-latex" (header))
18624 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
18625 (defun org-create-formula--latex-header ()
18626 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18627 (let ((info (org-combine-plists (org-export--get-global-options
18628 (org-export-get-backend 'latex))
18629 (org-export--get-inbuffer-options
18630 (org-export-get-backend 'latex)))))
18631 (org-latex-guess-babel-language
18632 (org-latex-guess-inputenc
18633 (org-splice-latex-header
18634 org-format-latex-header
18635 org-latex-default-packages-alist
18636 org-latex-packages-alist t
18637 (plist-get info :latex-header)))
18638 info)))
18640 ;; This function borrows from Ganesh Swami's latex2png.el
18641 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18642 "This calls dvipng."
18643 (require 'ox-latex)
18644 (let* ((tmpdir (if (featurep 'xemacs)
18645 (temp-directory)
18646 temporary-file-directory))
18647 (texfilebase (make-temp-name
18648 (expand-file-name "orgtex" tmpdir)))
18649 (texfile (concat texfilebase ".tex"))
18650 (dvifile (concat texfilebase ".dvi"))
18651 (pngfile (concat texfilebase ".png"))
18652 (fnh (if (featurep 'xemacs)
18653 (font-height (face-font 'default))
18654 (face-attribute 'default :height nil)))
18655 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18656 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18657 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18658 "Black"))
18659 (bg (or (plist-get options (if buffer :background :html-background))
18660 "Transparent")))
18661 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18662 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18663 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18664 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18665 (let ((latex-header (org-create-formula--latex-header)))
18666 (with-temp-file texfile
18667 (insert latex-header)
18668 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18669 (let ((dir default-directory))
18670 (condition-case nil
18671 (progn
18672 (cd tmpdir)
18673 (call-process "latex" nil nil nil texfile))
18674 (error nil))
18675 (cd dir))
18676 (if (not (file-exists-p dvifile))
18677 (progn (message "Failed to create dvi file from %s" texfile) nil)
18678 (condition-case nil
18679 (if (featurep 'xemacs)
18680 (call-process "dvipng" nil nil nil
18681 "-fg" fg "-bg" bg
18682 "-T" "tight"
18683 "-o" pngfile
18684 dvifile)
18685 (call-process "dvipng" nil nil nil
18686 "-fg" fg "-bg" bg
18687 "-D" dpi
18688 ;;"-x" scale "-y" scale
18689 "-T" "tight"
18690 "-o" pngfile
18691 dvifile))
18692 (error nil))
18693 (if (not (file-exists-p pngfile))
18694 (if org-format-latex-signal-error
18695 (error "Failed to create png file from %s" texfile)
18696 (message "Failed to create png file from %s" texfile)
18697 nil)
18698 ;; Use the requested file name and clean up
18699 (copy-file pngfile tofile 'replace)
18700 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18701 (if (file-exists-p (concat texfilebase e))
18702 (delete-file (concat texfilebase e))))
18703 pngfile))))
18705 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18706 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18707 "This calls convert, which is included into imagemagick."
18708 (require 'ox-latex)
18709 (let* ((tmpdir (if (featurep 'xemacs)
18710 (temp-directory)
18711 temporary-file-directory))
18712 (texfilebase (make-temp-name
18713 (expand-file-name "orgtex" tmpdir)))
18714 (texfile (concat texfilebase ".tex"))
18715 (pdffile (concat texfilebase ".pdf"))
18716 (pngfile (concat texfilebase ".png"))
18717 (fnh (if (featurep 'xemacs)
18718 (font-height (face-font 'default))
18719 (face-attribute 'default :height nil)))
18720 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18721 (dpi (number-to-string (* scale (floor (if buffer fnh 120.)))))
18722 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18723 "black"))
18724 (bg (or (plist-get options (if buffer :background :html-background))
18725 "white")))
18726 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18727 (setq fg (org-latex-color-format fg)))
18728 (if (eq bg 'default) (setq bg (org-latex-color :background))
18729 (setq bg (org-latex-color-format
18730 (if (string= bg "Transparent") "white" bg))))
18731 (let ((latex-header (org-create-formula--latex-header)))
18732 (with-temp-file texfile
18733 (insert latex-header)
18734 (insert "\n\\begin{document}\n"
18735 "\\definecolor{fg}{rgb}{" fg "}\n"
18736 "\\definecolor{bg}{rgb}{" bg "}\n"
18737 "\n\\pagecolor{bg}\n"
18738 "\n{\\color{fg}\n"
18739 string
18740 "\n}\n"
18741 "\n\\end{document}\n")))
18742 (org-latex-compile texfile t)
18743 (if (not (file-exists-p pdffile))
18744 (progn (message "Failed to create pdf file from %s" texfile) nil)
18745 (condition-case nil
18746 (if (featurep 'xemacs)
18747 (call-process "convert" nil nil nil
18748 "-density" "96"
18749 "-trim"
18750 "-antialias"
18751 pdffile
18752 "-quality" "100"
18753 ;; "-sharpen" "0x1.0"
18754 pngfile)
18755 (call-process "convert" nil nil nil
18756 "-density" dpi
18757 "-trim"
18758 "-antialias"
18759 pdffile
18760 "-quality" "100"
18761 ;; "-sharpen" "0x1.0"
18762 pngfile))
18763 (error nil))
18764 (if (not (file-exists-p pngfile))
18765 (if org-format-latex-signal-error
18766 (error "Failed to create png file from %s" texfile)
18767 (message "Failed to create png file from %s" texfile)
18768 nil)
18769 ;; Use the requested file name and clean up
18770 (copy-file pngfile tofile 'replace)
18771 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18772 (if (file-exists-p (concat texfilebase e))
18773 (delete-file (concat texfilebase e))))
18774 pngfile))))
18776 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18777 "Fill a LaTeX header template TPL.
18778 In the template, the following place holders will be recognized:
18780 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18781 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18782 [PACKAGES] \\usepackage statements for PKG
18783 [NO-PACKAGES] do not include PKG
18784 [EXTRA] the string EXTRA
18785 [NO-EXTRA] do not include EXTRA
18787 For backward compatibility, if both the positive and the negative place
18788 holder is missing, the positive one (without the \"NO-\") will be
18789 assumed to be present at the end of the template.
18790 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18791 EXTRA is a string.
18792 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18793 (let (rpl (end ""))
18794 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18795 (setq rpl (if (or (match-end 1) (not def-pkg))
18796 "" (org-latex-packages-to-string def-pkg snippets-p t))
18797 tpl (replace-match rpl t t tpl))
18798 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18800 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18801 (setq rpl (if (or (match-end 1) (not pkg))
18802 "" (org-latex-packages-to-string pkg snippets-p t))
18803 tpl (replace-match rpl t t tpl))
18804 (if pkg (setq end
18805 (concat end "\n"
18806 (org-latex-packages-to-string pkg snippets-p)))))
18808 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18809 (setq rpl (if (or (match-end 1) (not extra))
18810 "" (concat extra "\n"))
18811 tpl (replace-match rpl t t tpl))
18812 (if (and extra (string-match "\\S-" extra))
18813 (setq end (concat end "\n" extra))))
18815 (if (string-match "\\S-" end)
18816 (concat tpl "\n" end)
18817 tpl)))
18819 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18820 "Turn an alist of packages into a string with the \\usepackage macros."
18821 (setq pkg (mapconcat (lambda(p)
18822 (cond
18823 ((stringp p) p)
18824 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18825 (format "%% Package %s omitted" (cadr p)))
18826 ((equal "" (car p))
18827 (format "\\usepackage{%s}" (cadr p)))
18829 (format "\\usepackage[%s]{%s}"
18830 (car p) (cadr p)))))
18832 "\n"))
18833 (if newline (concat pkg "\n") pkg))
18835 (defun org-dvipng-color (attr)
18836 "Return a RGB color specification for dvipng."
18837 (apply 'format "rgb %s %s %s"
18838 (mapcar 'org-normalize-color
18839 (if (featurep 'xemacs)
18840 (color-rgb-components
18841 (face-property 'default
18842 (cond ((eq attr :foreground) 'foreground)
18843 ((eq attr :background) 'background))))
18844 (color-values (face-attribute 'default attr nil))))))
18846 (defun org-dvipng-color-format (color-name)
18847 "Convert COLOR-NAME to a RGB color value for dvipng."
18848 (apply 'format "rgb %s %s %s"
18849 (mapcar 'org-normalize-color
18850 (color-values color-name))))
18852 (defun org-latex-color (attr)
18853 "Return a RGB color for the LaTeX color package."
18854 (apply 'format "%s,%s,%s"
18855 (mapcar 'org-normalize-color
18856 (if (featurep 'xemacs)
18857 (color-rgb-components
18858 (face-property 'default
18859 (cond ((eq attr :foreground) 'foreground)
18860 ((eq attr :background) 'background))))
18861 (color-values (face-attribute 'default attr nil))))))
18863 (defun org-latex-color-format (color-name)
18864 "Convert COLOR-NAME to a RGB color value."
18865 (apply 'format "%s,%s,%s"
18866 (mapcar 'org-normalize-color
18867 (color-values color-name))))
18869 (defun org-normalize-color (value)
18870 "Return string to be used as color value for an RGB component."
18871 (format "%g" (/ value 65535.0)))
18875 ;; Image display
18877 (defvar org-inline-image-overlays nil)
18878 (make-variable-buffer-local 'org-inline-image-overlays)
18880 (defun org-toggle-inline-images (&optional include-linked)
18881 "Toggle the display of inline images.
18882 INCLUDE-LINKED is passed to `org-display-inline-images'."
18883 (interactive "P")
18884 (if org-inline-image-overlays
18885 (progn
18886 (org-remove-inline-images)
18887 (message "Inline image display turned off"))
18888 (org-display-inline-images include-linked)
18889 (if (and (org-called-interactively-p)
18890 org-inline-image-overlays)
18891 (message "%d images displayed inline"
18892 (length org-inline-image-overlays))
18893 (message "No images to display inline"))))
18895 (defun org-redisplay-inline-images ()
18896 "Refresh the display of inline images."
18897 (interactive)
18898 (if (not org-inline-image-overlays)
18899 (org-toggle-inline-images)
18900 (org-toggle-inline-images)
18901 (org-toggle-inline-images)))
18903 (defun org-display-inline-images (&optional include-linked refresh beg end)
18904 "Display inline images.
18906 An inline image is a link which follows either of these
18907 conventions:
18909 1. Its path is a file with an extension matching return value
18910 from `image-file-name-regexp' and it has no contents.
18912 2. Its description consists in a single link of the previous
18913 type.
18915 When optional argument INCLUDE-LINKED is non-nil, also links with
18916 a text description part will be inlined. This can be nice for
18917 a quick look at those images, but it does not reflect what
18918 exported files will look like.
18920 When optional argument REFRESH is non-nil, refresh existing
18921 images between BEG and END. This will create new image displays
18922 only if necessary. BEG and END default to the buffer
18923 boundaries."
18924 (interactive "P")
18925 (when (display-graphic-p)
18926 (unless refresh
18927 (org-remove-inline-images)
18928 (when (fboundp 'clear-image-cache) (clear-image-cache)))
18929 (org-with-wide-buffer
18930 (goto-char (or beg (point-min)))
18931 (let ((case-fold-search t)
18932 (file-extension-re (org-image-file-name-regexp)))
18933 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
18934 (let ((link (save-match-data (org-element-context))))
18935 ;; Check if we're at an inline image.
18936 (when (and (equal (org-element-property :type link) "file")
18937 (or include-linked
18938 (not (org-element-property :contents-begin link)))
18939 (let ((parent (org-element-property :parent link)))
18940 (or (not (eq (org-element-type parent) 'link))
18941 (not (cdr (org-element-contents parent)))))
18942 (org-string-match-p file-extension-re
18943 (org-element-property :path link)))
18944 (let ((file (expand-file-name (org-element-property :path link))))
18945 (when (file-exists-p file)
18946 (let ((width
18947 ;; Apply `org-image-actual-width' specifications.
18948 (cond
18949 ((not (image-type-available-p 'imagemagick)) nil)
18950 ((eq org-image-actual-width t) nil)
18951 ((listp org-image-actual-width)
18953 ;; First try to find a width among
18954 ;; attributes associated to the paragraph
18955 ;; containing link.
18956 (let ((paragraph
18957 (let ((e link))
18958 (while (and (setq e (org-element-property
18959 :parent e))
18960 (not (eq (org-element-type e)
18961 'paragraph))))
18962 e)))
18963 (when paragraph
18964 (save-excursion
18965 (goto-char (org-element-property :begin paragraph))
18966 (when (save-match-data
18967 (re-search-forward
18968 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
18969 (org-element-property
18970 :post-affiliated paragraph)
18972 (string-to-number (match-string 1))))))
18973 ;; Otherwise, fall-back to provided number.
18974 (car org-image-actual-width)))
18975 ((numberp org-image-actual-width)
18976 org-image-actual-width)))
18977 (old (get-char-property-and-overlay
18978 (org-element-property :begin link)
18979 'org-image-overlay)))
18980 (if (and (car-safe old) refresh)
18981 (image-refresh (overlay-get (cdr old) 'display))
18982 (let ((image (save-match-data
18983 (create-image file
18984 (and width 'imagemagick)
18986 :width width))))
18987 (when image
18988 (let* ((link
18989 ;; If inline image is the description
18990 ;; of another link, be sure to
18991 ;; consider the latter as the one to
18992 ;; apply the overlay on.
18993 (let ((parent
18994 (org-element-property :parent link)))
18995 (if (eq (org-element-type parent) 'link)
18996 parent
18997 link)))
18998 (ov (make-overlay
18999 (org-element-property :begin link)
19000 (progn
19001 (goto-char
19002 (org-element-property :end link))
19003 (skip-chars-backward " \t")
19004 (point)))))
19005 (overlay-put ov 'display image)
19006 (overlay-put ov 'face 'default)
19007 (overlay-put ov 'org-image-overlay t)
19008 (overlay-put
19009 ov 'modification-hooks
19010 (list 'org-display-inline-remove-overlay))
19011 (push ov org-inline-image-overlays)))))))))))))))
19013 (define-obsolete-function-alias
19014 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
19016 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
19017 "Remove inline-display overlay if a corresponding region is modified."
19018 (let ((inhibit-modification-hooks t))
19019 (when (and ov after)
19020 (delete ov org-inline-image-overlays)
19021 (delete-overlay ov))))
19023 (defun org-remove-inline-images ()
19024 "Remove inline display of images."
19025 (interactive)
19026 (mapc 'delete-overlay org-inline-image-overlays)
19027 (setq org-inline-image-overlays nil))
19029 ;;;; Key bindings
19031 ;; Outline functions from `outline-mode-prefix-map'
19032 ;; that can be remapped in Org:
19033 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19034 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
19035 (define-key org-mode-map [remap outline-forward-same-level]
19036 'org-forward-heading-same-level)
19037 (define-key org-mode-map [remap outline-backward-same-level]
19038 'org-backward-heading-same-level)
19039 (define-key org-mode-map [remap show-branches]
19040 'org-kill-note-or-show-branches)
19041 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19042 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19043 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19045 ;; Outline functions from `outline-mode-prefix-map' that can not
19046 ;; be remapped in Org:
19048 ;; - the column "key binding" shows whether the Outline function is still
19049 ;; available in Org mode on the same key that it has been bound to in
19050 ;; Outline mode:
19051 ;; - "overridden": key used for a different functionality in Org mode
19052 ;; - else: key still bound to the same Outline function in Org mode
19054 ;; | Outline function | key binding | Org replacement |
19055 ;; |------------------------------------+-------------+-----------------------|
19056 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
19057 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
19058 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19059 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19060 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19061 ;; | `show-entry' | overridden | no replacement |
19062 ;; | `show-children' | `C-c C-i' | visibility cycling |
19063 ;; | `show-branches' | `C-c C-k' | still same function |
19064 ;; | `show-subtree' | overridden | visibility cycling |
19065 ;; | `show-all' | overridden | no replacement |
19066 ;; | `hide-subtree' | overridden | visibility cycling |
19067 ;; | `hide-body' | overridden | no replacement |
19068 ;; | `hide-entry' | overridden | visibility cycling |
19069 ;; | `hide-leaves' | overridden | no replacement |
19070 ;; | `hide-sublevels' | overridden | no replacement |
19071 ;; | `hide-other' | overridden | no replacement |
19073 ;; Make `C-c C-x' a prefix key
19074 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19076 ;; TAB key with modifiers
19077 (org-defkey org-mode-map "\C-i" 'org-cycle)
19078 (org-defkey org-mode-map [(tab)] 'org-cycle)
19079 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19080 (org-defkey org-mode-map "\M-\t" 'pcomplete)
19081 ;; The following line is necessary under Suse GNU/Linux
19082 (unless (featurep 'xemacs)
19083 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
19084 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19085 (define-key org-mode-map [backtab] 'org-shifttab)
19087 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19088 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19089 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19091 ;; Cursor keys with modifiers
19092 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19093 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19094 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19095 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19097 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19098 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19099 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19100 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19102 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19103 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19104 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19105 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19107 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19108 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19109 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19110 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19112 ;; Babel keys
19113 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19114 (mapc (lambda (pair)
19115 (define-key org-babel-map (car pair) (cdr pair)))
19116 org-babel-key-bindings)
19118 ;;; Extra keys for tty access.
19119 ;; We only set them when really needed because otherwise the
19120 ;; menus don't show the simple keys
19122 (when (or org-use-extra-keys
19123 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19124 (not window-system))
19125 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19126 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19127 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19128 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19129 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19130 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19131 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19132 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19133 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19134 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19135 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19136 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19137 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19138 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19139 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19140 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19141 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19142 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19143 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19144 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19145 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19146 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19147 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
19148 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19149 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19150 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19151 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19152 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19154 ;; All the other keys
19156 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
19157 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19158 (if (boundp 'narrow-map)
19159 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19160 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19161 (if (boundp 'narrow-map)
19162 (org-defkey narrow-map "b" 'org-narrow-to-block)
19163 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19164 (if (boundp 'narrow-map)
19165 (org-defkey narrow-map "e" 'org-narrow-to-element)
19166 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19167 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19168 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19169 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19170 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19171 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19172 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19173 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19174 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19175 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19176 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19177 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
19178 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19179 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19180 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19181 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19182 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19183 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19184 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19185 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19186 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19187 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19188 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19189 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19190 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19191 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19192 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19193 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19194 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19195 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19196 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19197 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19198 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19199 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19200 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19201 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19202 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19203 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19204 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19205 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19206 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19207 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19208 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19209 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19210 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19211 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19212 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19213 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19214 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19215 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19216 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19217 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19218 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19219 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19220 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19221 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19222 (org-defkey org-mode-map "\C-c^" 'org-sort)
19223 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19224 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19225 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19226 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19227 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19228 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19229 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19230 (org-defkey org-mode-map "\C-m" 'org-return)
19231 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19232 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19233 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19234 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19235 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19236 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19237 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19238 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19239 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19240 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19241 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19242 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19243 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19244 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19245 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
19246 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19247 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19248 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19249 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19250 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19251 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19252 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19253 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19255 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19256 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19257 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19259 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19260 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19261 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19262 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19263 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19264 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19265 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19266 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19267 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19268 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19269 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
19270 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19271 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19272 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19273 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19274 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19275 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19276 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19277 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19278 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19279 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19280 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19281 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19283 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19284 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19285 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19286 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19287 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19289 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19291 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19293 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19294 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19296 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19299 (when (featurep 'xemacs)
19300 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19303 (defconst org-speed-commands-default
19305 ("Outline Navigation")
19306 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19307 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19308 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19309 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19310 ("F" . org-next-block)
19311 ("B" . org-previous-block)
19312 ("u" . (org-speed-move-safe 'outline-up-heading))
19313 ("j" . org-goto)
19314 ("g" . (org-refile t))
19315 ("Outline Visibility")
19316 ("c" . org-cycle)
19317 ("C" . org-shifttab)
19318 (" " . org-display-outline-path)
19319 ("s" . org-narrow-to-subtree)
19320 ("=" . org-columns)
19321 ("Outline Structure Editing")
19322 ("U" . org-shiftmetaup)
19323 ("D" . org-shiftmetadown)
19324 ("r" . org-metaright)
19325 ("l" . org-metaleft)
19326 ("R" . org-shiftmetaright)
19327 ("L" . org-shiftmetaleft)
19328 ("i" . (progn (forward-char 1) (call-interactively
19329 'org-insert-heading-respect-content)))
19330 ("^" . org-sort)
19331 ("w" . org-refile)
19332 ("a" . org-archive-subtree-default-with-confirmation)
19333 ("@" . org-mark-subtree)
19334 ("#" . org-toggle-comment)
19335 ("Clock Commands")
19336 ("I" . org-clock-in)
19337 ("O" . org-clock-out)
19338 ("Meta Data Editing")
19339 ("t" . org-todo)
19340 ("," . (org-priority))
19341 ("0" . (org-priority ?\ ))
19342 ("1" . (org-priority ?A))
19343 ("2" . (org-priority ?B))
19344 ("3" . (org-priority ?C))
19345 (":" . org-set-tags-command)
19346 ("e" . org-set-effort)
19347 ("E" . org-inc-effort)
19348 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19349 (org-entry-put (point) "APPT_WARNTIME" m)))
19350 ("Agenda Views etc")
19351 ("v" . org-agenda)
19352 ("/" . org-sparse-tree)
19353 ("Misc")
19354 ("o" . org-open-at-point)
19355 ("?" . org-speed-command-help)
19356 ("<" . (org-agenda-set-restriction-lock 'subtree))
19357 (">" . (org-agenda-remove-restriction-lock))
19359 "The default speed commands.")
19361 (defun org-print-speed-command (e)
19362 (if (> (length (car e)) 1)
19363 (progn
19364 (princ "\n")
19365 (princ (car e))
19366 (princ "\n")
19367 (princ (make-string (length (car e)) ?-))
19368 (princ "\n"))
19369 (princ (car e))
19370 (princ " ")
19371 (if (symbolp (cdr e))
19372 (princ (symbol-name (cdr e)))
19373 (prin1 (cdr e)))
19374 (princ "\n")))
19376 (defun org-speed-command-help ()
19377 "Show the available speed commands."
19378 (interactive)
19379 (if (not org-use-speed-commands)
19380 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19381 (with-output-to-temp-buffer "*Help*"
19382 (princ "User-defined Speed commands\n===========================\n")
19383 (mapc 'org-print-speed-command org-speed-commands-user)
19384 (princ "\n")
19385 (princ "Built-in Speed commands\n=======================\n")
19386 (mapc 'org-print-speed-command org-speed-commands-default))
19387 (with-current-buffer "*Help*"
19388 (setq truncate-lines t))))
19390 (defun org-speed-move-safe (cmd)
19391 "Execute CMD, but make sure that the cursor always ends up in a headline.
19392 If not, return to the original position and throw an error."
19393 (interactive)
19394 (let ((pos (point)))
19395 (call-interactively cmd)
19396 (unless (and (bolp) (org-at-heading-p))
19397 (goto-char pos)
19398 (error "Boundary reached while executing %s" cmd))))
19400 (defvar org-self-insert-command-undo-counter 0)
19402 (defvar org-table-auto-blank-field) ; defined in org-table.el
19403 (defvar org-speed-command nil)
19405 (define-obsolete-function-alias
19406 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19408 (defun org-speed-command-activate (keys)
19409 "Hook for activating single-letter speed commands.
19410 `org-speed-commands-default' specifies a minimal command set.
19411 Use `org-speed-commands-user' for further customization."
19412 (when (or (and (bolp) (looking-at org-outline-regexp))
19413 (and (functionp org-use-speed-commands)
19414 (funcall org-use-speed-commands)))
19415 (cdr (assoc keys (append org-speed-commands-user
19416 org-speed-commands-default)))))
19418 (define-obsolete-function-alias
19419 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19421 (defun org-babel-speed-command-activate (keys)
19422 "Hook for activating single-letter code block commands."
19423 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19424 (cdr (assoc keys org-babel-key-bindings))))
19426 (defcustom org-speed-command-hook
19427 '(org-speed-command-default-hook org-babel-speed-command-hook)
19428 "Hook for activating speed commands at strategic locations.
19429 Hook functions are called in sequence until a valid handler is
19430 found.
19432 Each hook takes a single argument, a user-pressed command key
19433 which is also a `self-insert-command' from the global map.
19435 Within the hook, examine the cursor position and the command key
19436 and return nil or a valid handler as appropriate. Handler could
19437 be one of an interactive command, a function, or a form.
19439 Set `org-use-speed-commands' to non-nil value to enable this
19440 hook. The default setting is `org-speed-command-activate'."
19441 :group 'org-structure
19442 :version "24.1"
19443 :type 'hook)
19445 (defun org-self-insert-command (N)
19446 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19447 If the cursor is in a table looking at whitespace, the whitespace is
19448 overwritten, and the table is not marked as requiring realignment."
19449 (interactive "p")
19450 (org-check-before-invisible-edit 'insert)
19451 (cond
19452 ((and org-use-speed-commands
19453 (setq org-speed-command
19454 (run-hook-with-args-until-success
19455 'org-speed-command-hook (this-command-keys))))
19456 (cond
19457 ((commandp org-speed-command)
19458 (setq this-command org-speed-command)
19459 (call-interactively org-speed-command))
19460 ((functionp org-speed-command)
19461 (funcall org-speed-command))
19462 ((and org-speed-command (listp org-speed-command))
19463 (eval org-speed-command))
19464 (t (let (org-use-speed-commands)
19465 (call-interactively 'org-self-insert-command)))))
19466 ((and
19467 (org-table-p)
19468 (progn
19469 ;; check if we blank the field, and if that triggers align
19470 (and (featurep 'org-table) org-table-auto-blank-field
19471 (member last-command
19472 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19473 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19474 ;; got extra space, this field does not determine column width
19475 (let (org-table-may-need-update) (org-table-blank-field))
19476 ;; no extra space, this field may determine column width
19477 (org-table-blank-field)))
19479 (eq N 1)
19480 (looking-at "[^|\n]* |"))
19481 (let (org-table-may-need-update)
19482 (goto-char (1- (match-end 0)))
19483 (backward-delete-char 1)
19484 (goto-char (match-beginning 0))
19485 (self-insert-command N)))
19487 (setq org-table-may-need-update t)
19488 (self-insert-command N)
19489 (org-fix-tags-on-the-fly)
19490 (if org-self-insert-cluster-for-undo
19491 (if (not (eq last-command 'org-self-insert-command))
19492 (setq org-self-insert-command-undo-counter 1)
19493 (if (>= org-self-insert-command-undo-counter 20)
19494 (setq org-self-insert-command-undo-counter 1)
19495 (and (> org-self-insert-command-undo-counter 0)
19496 buffer-undo-list (listp buffer-undo-list)
19497 (not (cadr buffer-undo-list)) ; remove nil entry
19498 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19499 (setq org-self-insert-command-undo-counter
19500 (1+ org-self-insert-command-undo-counter))))))))
19502 (defun org-check-before-invisible-edit (kind)
19503 "Check is editing if kind KIND would be dangerous with invisible text around.
19504 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19505 ;; First, try to get out of here as quickly as possible, to reduce overhead
19506 (if (and org-catch-invisible-edits
19507 (or (not (boundp 'visible-mode)) (not visible-mode))
19508 (or (get-char-property (point) 'invisible)
19509 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19510 ;; OK, we need to take a closer look
19511 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19512 (invisible-before-point (if (bobp) nil (get-char-property
19513 (1- (point)) 'invisible)))
19514 (border-and-ok-direction
19516 ;; Check if we are acting predictably before invisible text
19517 (and invisible-at-point (not invisible-before-point)
19518 (memq kind '(insert delete-backward)))
19519 ;; Check if we are acting predictably after invisible text
19520 ;; This works not well, and I have turned it off. It seems
19521 ;; better to always show and stop after invisible text.
19522 ;; (and (not invisible-at-point) invisible-before-point
19523 ;; (memq kind '(insert delete)))
19525 (when (or (memq invisible-at-point '(outline org-hide-block t))
19526 (memq invisible-before-point '(outline org-hide-block t)))
19527 (if (eq org-catch-invisible-edits 'error)
19528 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19529 (if (and org-custom-properties-overlays
19530 (y-or-n-p "Display invisible properties in this buffer? "))
19531 (org-toggle-custom-properties-visibility)
19532 ;; Make the area visible
19533 (save-excursion
19534 (if invisible-before-point
19535 (goto-char (previous-single-char-property-change
19536 (point) 'invisible)))
19537 (org-cycle))
19538 (cond
19539 ((eq org-catch-invisible-edits 'show)
19540 ;; That's it, we do the edit after showing
19541 (message
19542 "Unfolding invisible region around point before editing")
19543 (sit-for 1))
19544 ((and (eq org-catch-invisible-edits 'smart)
19545 border-and-ok-direction)
19546 (message "Unfolding invisible region around point before editing"))
19548 ;; Don't do the edit, make the user repeat it in full visibility
19549 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19551 (defun org-fix-tags-on-the-fly ()
19552 (when (and (equal (char-after (point-at-bol)) ?*)
19553 (org-at-heading-p))
19554 (org-align-tags-here org-tags-column)))
19556 (defun org-delete-backward-char (N)
19557 "Like `delete-backward-char', insert whitespace at field end in tables.
19558 When deleting backwards, in tables this function will insert whitespace in
19559 front of the next \"|\" separator, to keep the table aligned. The table will
19560 still be marked for re-alignment if the field did fill the entire column,
19561 because, in this case the deletion might narrow the column."
19562 (interactive "p")
19563 (save-match-data
19564 (org-check-before-invisible-edit 'delete-backward)
19565 (if (and (org-table-p)
19566 (eq N 1)
19567 (string-match "|" (buffer-substring (point-at-bol) (point)))
19568 (looking-at ".*?|"))
19569 (let ((pos (point))
19570 (noalign (looking-at "[^|\n\r]* |"))
19571 (c org-table-may-need-update))
19572 (backward-delete-char N)
19573 (if (not overwrite-mode)
19574 (progn
19575 (skip-chars-forward "^|")
19576 (insert " ")
19577 (goto-char (1- pos))))
19578 ;; noalign: if there were two spaces at the end, this field
19579 ;; does not determine the width of the column.
19580 (if noalign (setq org-table-may-need-update c)))
19581 (backward-delete-char N)
19582 (org-fix-tags-on-the-fly))))
19584 (defun org-delete-char (N)
19585 "Like `delete-char', but insert whitespace at field end in tables.
19586 When deleting characters, in tables this function will insert whitespace in
19587 front of the next \"|\" separator, to keep the table aligned. The table will
19588 still be marked for re-alignment if the field did fill the entire column,
19589 because, in this case the deletion might narrow the column."
19590 (interactive "p")
19591 (save-match-data
19592 (org-check-before-invisible-edit 'delete)
19593 (if (and (org-table-p)
19594 (not (bolp))
19595 (not (= (char-after) ?|))
19596 (eq N 1))
19597 (if (looking-at ".*?|")
19598 (let ((pos (point))
19599 (noalign (looking-at "[^|\n\r]* |"))
19600 (c org-table-may-need-update))
19601 (replace-match
19602 (concat (substring (match-string 0) 1 -1) " |") nil t)
19603 (goto-char pos)
19604 ;; noalign: if there were two spaces at the end, this field
19605 ;; does not determine the width of the column.
19606 (if noalign (setq org-table-may-need-update c)))
19607 (delete-char N))
19608 (delete-char N)
19609 (org-fix-tags-on-the-fly))))
19611 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19612 (put 'org-self-insert-command 'delete-selection
19613 (lambda ()
19614 (not (run-hook-with-args-until-success
19615 'self-insert-uses-region-functions))))
19616 (put 'orgtbl-self-insert-command 'delete-selection
19617 (lambda ()
19618 (not (run-hook-with-args-until-success
19619 'self-insert-uses-region-functions))))
19620 (put 'org-delete-char 'delete-selection 'supersede)
19621 (put 'org-delete-backward-char 'delete-selection 'supersede)
19622 (put 'org-yank 'delete-selection 'yank)
19624 ;; Make `flyspell-mode' delay after some commands
19625 (put 'org-self-insert-command 'flyspell-delayed t)
19626 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19627 (put 'org-delete-char 'flyspell-delayed t)
19628 (put 'org-delete-backward-char 'flyspell-delayed t)
19630 ;; Make pabbrev-mode expand after org-mode commands
19631 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19632 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19634 (defun org-remap (map &rest commands)
19635 "In MAP, remap the functions given in COMMANDS.
19636 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19637 (let (new old)
19638 (while commands
19639 (setq old (pop commands) new (pop commands))
19640 (if (fboundp 'command-remapping)
19641 (org-defkey map (vector 'remap old) new)
19642 (substitute-key-definition old new map global-map)))))
19644 (defun org-transpose-words ()
19645 "Transpose words for Org.
19646 This uses the `org-mode-transpose-word-syntax-table' syntax
19647 table, which interprets characters in `org-emphasis-alist' as
19648 word constituents."
19649 (interactive)
19650 (with-syntax-table org-mode-transpose-word-syntax-table
19651 (call-interactively 'transpose-words)))
19652 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19654 (when (eq org-enable-table-editor 'optimized)
19655 ;; If the user wants maximum table support, we need to hijack
19656 ;; some standard editing functions
19657 (org-remap org-mode-map
19658 'self-insert-command 'org-self-insert-command
19659 'delete-char 'org-delete-char
19660 'delete-backward-char 'org-delete-backward-char)
19661 (org-defkey org-mode-map "|" 'org-force-self-insert))
19663 (defvar org-ctrl-c-ctrl-c-hook nil
19664 "Hook for functions attaching themselves to `C-c C-c'.
19666 This can be used to add additional functionality to the C-c C-c
19667 key which executes context-dependent commands. This hook is run
19668 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19669 run after the last test.
19671 Each function will be called with no arguments. The function
19672 must check if the context is appropriate for it to act. If yes,
19673 it should do its thing and then return a non-nil value. If the
19674 context is wrong, just do nothing and return nil.")
19676 (defvar org-ctrl-c-ctrl-c-final-hook nil
19677 "Hook for functions attaching themselves to `C-c C-c'.
19679 This can be used to add additional functionality to the C-c C-c
19680 key which executes context-dependent commands. This hook is run
19681 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19682 before the first test.
19684 Each function will be called with no arguments. The function
19685 must check if the context is appropriate for it to act. If yes,
19686 it should do its thing and then return a non-nil value. If the
19687 context is wrong, just do nothing and return nil.")
19689 (defvar org-tab-first-hook nil
19690 "Hook for functions to attach themselves to TAB.
19691 See `org-ctrl-c-ctrl-c-hook' for more information.
19692 This hook runs as the first action when TAB is pressed, even before
19693 `org-cycle' messes around with the `outline-regexp' to cater for
19694 inline tasks and plain list item folding.
19695 If any function in this hook returns t, any other actions that
19696 would have been caused by TAB (such as table field motion or visibility
19697 cycling) will not occur.")
19699 (defvar org-tab-after-check-for-table-hook nil
19700 "Hook for functions to attach themselves to TAB.
19701 See `org-ctrl-c-ctrl-c-hook' for more information.
19702 This hook runs after it has been established that the cursor is not in a
19703 table, but before checking if the cursor is in a headline or if global cycling
19704 should be done.
19705 If any function in this hook returns t, not other actions like visibility
19706 cycling will be done.")
19708 (defvar org-tab-after-check-for-cycling-hook nil
19709 "Hook for functions to attach themselves to TAB.
19710 See `org-ctrl-c-ctrl-c-hook' for more information.
19711 This hook runs after it has been established that not table field motion and
19712 not visibility should be done because of current context. This is probably
19713 the place where a package like yasnippets can hook in.")
19715 (defvar org-tab-before-tab-emulation-hook nil
19716 "Hook for functions to attach themselves to TAB.
19717 See `org-ctrl-c-ctrl-c-hook' for more information.
19718 This hook runs after every other options for TAB have been exhausted, but
19719 before indentation and \t insertion takes place.")
19721 (defvar org-metaleft-hook nil
19722 "Hook for functions attaching themselves to `M-left'.
19723 See `org-ctrl-c-ctrl-c-hook' for more information.")
19724 (defvar org-metaright-hook nil
19725 "Hook for functions attaching themselves to `M-right'.
19726 See `org-ctrl-c-ctrl-c-hook' for more information.")
19727 (defvar org-metaup-hook nil
19728 "Hook for functions attaching themselves to `M-up'.
19729 See `org-ctrl-c-ctrl-c-hook' for more information.")
19730 (defvar org-metadown-hook nil
19731 "Hook for functions attaching themselves to `M-down'.
19732 See `org-ctrl-c-ctrl-c-hook' for more information.")
19733 (defvar org-shiftmetaleft-hook nil
19734 "Hook for functions attaching themselves to `M-S-left'.
19735 See `org-ctrl-c-ctrl-c-hook' for more information.")
19736 (defvar org-shiftmetaright-hook nil
19737 "Hook for functions attaching themselves to `M-S-right'.
19738 See `org-ctrl-c-ctrl-c-hook' for more information.")
19739 (defvar org-shiftmetaup-hook nil
19740 "Hook for functions attaching themselves to `M-S-up'.
19741 See `org-ctrl-c-ctrl-c-hook' for more information.")
19742 (defvar org-shiftmetadown-hook nil
19743 "Hook for functions attaching themselves to `M-S-down'.
19744 See `org-ctrl-c-ctrl-c-hook' for more information.")
19745 (defvar org-metareturn-hook nil
19746 "Hook for functions attaching themselves to `M-RET'.
19747 See `org-ctrl-c-ctrl-c-hook' for more information.")
19748 (defvar org-shiftup-hook nil
19749 "Hook for functions attaching themselves to `S-up'.
19750 See `org-ctrl-c-ctrl-c-hook' for more information.")
19751 (defvar org-shiftup-final-hook nil
19752 "Hook for functions attaching themselves to `S-up'.
19753 This one runs after all other options except shift-select have been excluded.
19754 See `org-ctrl-c-ctrl-c-hook' for more information.")
19755 (defvar org-shiftdown-hook nil
19756 "Hook for functions attaching themselves to `S-down'.
19757 See `org-ctrl-c-ctrl-c-hook' for more information.")
19758 (defvar org-shiftdown-final-hook nil
19759 "Hook for functions attaching themselves to `S-down'.
19760 This one runs after all other options except shift-select have been excluded.
19761 See `org-ctrl-c-ctrl-c-hook' for more information.")
19762 (defvar org-shiftleft-hook nil
19763 "Hook for functions attaching themselves to `S-left'.
19764 See `org-ctrl-c-ctrl-c-hook' for more information.")
19765 (defvar org-shiftleft-final-hook nil
19766 "Hook for functions attaching themselves to `S-left'.
19767 This one runs after all other options except shift-select have been excluded.
19768 See `org-ctrl-c-ctrl-c-hook' for more information.")
19769 (defvar org-shiftright-hook nil
19770 "Hook for functions attaching themselves to `S-right'.
19771 See `org-ctrl-c-ctrl-c-hook' for more information.")
19772 (defvar org-shiftright-final-hook nil
19773 "Hook for functions attaching themselves to `S-right'.
19774 This one runs after all other options except shift-select have been excluded.
19775 See `org-ctrl-c-ctrl-c-hook' for more information.")
19777 (defun org-modifier-cursor-error ()
19778 "Throw an error, a modified cursor command was applied in wrong context."
19779 (user-error "This command is active in special context like tables, headlines or items"))
19781 (defun org-shiftselect-error ()
19782 "Throw an error because Shift-Cursor command was applied in wrong context."
19783 (if (and (boundp 'shift-select-mode) shift-select-mode)
19784 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19785 (user-error "This command works only in special context like headlines or timestamps")))
19787 (defun org-call-for-shift-select (cmd)
19788 (let ((this-command-keys-shift-translated t))
19789 (call-interactively cmd)))
19791 (defun org-shifttab (&optional arg)
19792 "Global visibility cycling or move to previous table field.
19793 Call `org-table-previous-field' within a table.
19794 When ARG is nil, cycle globally through visibility states.
19795 When ARG is a numeric prefix, show contents of this level."
19796 (interactive "P")
19797 (cond
19798 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19799 ((integerp arg)
19800 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19801 (message "Content view to level: %d" arg)
19802 (org-content (prefix-numeric-value arg2))
19803 (org-cycle-show-empty-lines t)
19804 (setq org-cycle-global-status 'overview)))
19805 (t (call-interactively 'org-global-cycle))))
19807 (defun org-shiftmetaleft ()
19808 "Promote subtree or delete table column.
19809 Calls `org-promote-subtree', `org-outdent-item-tree', or
19810 `org-table-delete-column', depending on context. See the
19811 individual commands for more information."
19812 (interactive)
19813 (cond
19814 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19815 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19816 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19817 ((if (not (org-region-active-p)) (org-at-item-p)
19818 (save-excursion (goto-char (region-beginning))
19819 (org-at-item-p)))
19820 (call-interactively 'org-outdent-item-tree))
19821 (t (org-modifier-cursor-error))))
19823 (defun org-shiftmetaright ()
19824 "Demote subtree or insert table column.
19825 Calls `org-demote-subtree', `org-indent-item-tree', or
19826 `org-table-insert-column', depending on context. See the
19827 individual commands for more information."
19828 (interactive)
19829 (cond
19830 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19831 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19832 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19833 ((if (not (org-region-active-p)) (org-at-item-p)
19834 (save-excursion (goto-char (region-beginning))
19835 (org-at-item-p)))
19836 (call-interactively 'org-indent-item-tree))
19837 (t (org-modifier-cursor-error))))
19839 (defun org-shiftmetaup (&optional arg)
19840 "Move subtree up or kill table row.
19841 Calls `org-move-subtree-up' or `org-table-kill-row' or
19842 `org-move-item-up' or `org-timestamp-up', depending on context.
19843 See the individual commands for more information."
19844 (interactive "P")
19845 (cond
19846 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19847 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19848 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19849 ((org-at-item-p) (call-interactively 'org-move-item-up))
19850 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19851 (call-interactively 'org-timestamp-up)))
19852 (t (call-interactively 'org-drag-line-backward))))
19854 (defun org-shiftmetadown (&optional arg)
19855 "Move subtree down or insert table row.
19856 Calls `org-move-subtree-down' or `org-table-insert-row' or
19857 `org-move-item-down' or `org-timestamp-up', depending on context.
19858 See the individual commands for more information."
19859 (interactive "P")
19860 (cond
19861 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19862 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19863 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19864 ((org-at-item-p) (call-interactively 'org-move-item-down))
19865 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19866 (call-interactively 'org-timestamp-down)))
19867 (t (call-interactively 'org-drag-line-forward))))
19869 (defsubst org-hidden-tree-error ()
19870 (user-error
19871 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19873 (defun org-metaleft (&optional arg)
19874 "Promote heading or move table column to left.
19875 Calls `org-do-promote' or `org-table-move-column', depending on context.
19876 With no specific context, calls the Emacs default `backward-word'.
19877 See the individual commands for more information."
19878 (interactive "P")
19879 (cond
19880 ((run-hook-with-args-until-success 'org-metaleft-hook))
19881 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19882 ((org-with-limited-levels
19883 (or (org-at-heading-p)
19884 (and (org-region-active-p)
19885 (save-excursion
19886 (goto-char (region-beginning))
19887 (org-at-heading-p)))))
19888 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19889 (call-interactively 'org-do-promote))
19890 ;; At an inline task.
19891 ((org-at-heading-p)
19892 (call-interactively 'org-inlinetask-promote))
19893 ((or (org-at-item-p)
19894 (and (org-region-active-p)
19895 (save-excursion
19896 (goto-char (region-beginning))
19897 (org-at-item-p))))
19898 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19899 (call-interactively 'org-outdent-item))
19900 (t (call-interactively 'backward-word))))
19902 (defun org-metaright (&optional arg)
19903 "Demote a subtree, a list item or move table column to right.
19904 In front of a drawer or a block keyword, indent it correctly.
19905 With no specific context, calls the Emacs default `forward-word'.
19906 See the individual commands for more information."
19907 (interactive "P")
19908 (cond
19909 ((run-hook-with-args-until-success 'org-metaright-hook))
19910 ((org-at-table-p) (call-interactively 'org-table-move-column))
19911 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19912 ((org-at-block-p) (call-interactively 'org-indent-block))
19913 ((org-with-limited-levels
19914 (or (org-at-heading-p)
19915 (and (org-region-active-p)
19916 (save-excursion
19917 (goto-char (region-beginning))
19918 (org-at-heading-p)))))
19919 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19920 (call-interactively 'org-do-demote))
19921 ;; At an inline task.
19922 ((org-at-heading-p)
19923 (call-interactively 'org-inlinetask-demote))
19924 ((or (org-at-item-p)
19925 (and (org-region-active-p)
19926 (save-excursion
19927 (goto-char (region-beginning))
19928 (org-at-item-p))))
19929 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19930 (call-interactively 'org-indent-item))
19931 (t (call-interactively 'forward-word))))
19933 (defun org-check-for-hidden (what)
19934 "Check if there are hidden headlines/items in the current visual line.
19935 WHAT can be either `headlines' or `items'. If the current line is
19936 an outline or item heading and it has a folded subtree below it,
19937 this function returns t, nil otherwise."
19938 (let ((re (cond
19939 ((eq what 'headlines) org-outline-regexp-bol)
19940 ((eq what 'items) (org-item-beginning-re))
19941 (t (error "This should not happen"))))
19942 beg end)
19943 (save-excursion
19944 (catch 'exit
19945 (unless (org-region-active-p)
19946 (setq beg (point-at-bol))
19947 (beginning-of-line 2)
19948 (while (and (not (eobp)) ;; this is like `next-line'
19949 (get-char-property (1- (point)) 'invisible))
19950 (beginning-of-line 2))
19951 (setq end (point))
19952 (goto-char beg)
19953 (goto-char (point-at-eol))
19954 (setq end (max end (point)))
19955 (while (re-search-forward re end t)
19956 (if (get-char-property (match-beginning 0) 'invisible)
19957 (throw 'exit t))))
19958 nil))))
19960 (defun org-metaup (&optional arg)
19961 "Move subtree up or move table row up.
19962 Calls `org-move-subtree-up' or `org-table-move-row' or
19963 `org-move-item-up', depending on context. See the individual commands
19964 for more information."
19965 (interactive "P")
19966 (cond
19967 ((run-hook-with-args-until-success 'org-metaup-hook))
19968 ((org-region-active-p)
19969 (let* ((a (min (region-beginning) (region-end)))
19970 (b (1- (max (region-beginning) (region-end))))
19971 (c (save-excursion (goto-char a)
19972 (move-beginning-of-line 0)))
19973 (d (save-excursion (goto-char a)
19974 (move-end-of-line 0) (point))))
19975 (transpose-regions a b c d)
19976 (goto-char c)))
19977 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19978 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19979 ((org-at-item-p) (call-interactively 'org-move-item-up))
19980 (t (org-drag-element-backward))))
19982 (defun org-metadown (&optional arg)
19983 "Move subtree down or move table row down.
19984 Calls `org-move-subtree-down' or `org-table-move-row' or
19985 `org-move-item-down', depending on context. See the individual
19986 commands for more information."
19987 (interactive "P")
19988 (cond
19989 ((run-hook-with-args-until-success 'org-metadown-hook))
19990 ((org-region-active-p)
19991 (let* ((a (min (region-beginning) (region-end)))
19992 (b (max (region-beginning) (region-end)))
19993 (c (save-excursion (goto-char b)
19994 (move-beginning-of-line 1)))
19995 (d (save-excursion (goto-char b)
19996 (move-end-of-line 1) (1+ (point)))))
19997 (transpose-regions a b c d)
19998 (goto-char d)))
19999 ((org-at-table-p) (call-interactively 'org-table-move-row))
20000 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20001 ((org-at-item-p) (call-interactively 'org-move-item-down))
20002 (t (org-drag-element-forward))))
20004 (defun org-shiftup (&optional arg)
20005 "Increase item in timestamp or increase priority of current headline.
20006 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20007 depending on context. See the individual commands for more information."
20008 (interactive "P")
20009 (cond
20010 ((run-hook-with-args-until-success 'org-shiftup-hook))
20011 ((and org-support-shift-select (org-region-active-p))
20012 (org-call-for-shift-select 'previous-line))
20013 ((org-at-timestamp-p t)
20014 (call-interactively (if org-edit-timestamp-down-means-later
20015 'org-timestamp-down 'org-timestamp-up)))
20016 ((and (not (eq org-support-shift-select 'always))
20017 org-enable-priority-commands
20018 (org-at-heading-p))
20019 (call-interactively 'org-priority-up))
20020 ((and (not org-support-shift-select) (org-at-item-p))
20021 (call-interactively 'org-previous-item))
20022 ((org-clocktable-try-shift 'up arg))
20023 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20024 (org-support-shift-select
20025 (org-call-for-shift-select 'previous-line))
20026 (t (org-shiftselect-error))))
20028 (defun org-shiftdown (&optional arg)
20029 "Decrease item in timestamp or decrease priority of current headline.
20030 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20031 depending on context. See the individual commands for more information."
20032 (interactive "P")
20033 (cond
20034 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20035 ((and org-support-shift-select (org-region-active-p))
20036 (org-call-for-shift-select 'next-line))
20037 ((org-at-timestamp-p t)
20038 (call-interactively (if org-edit-timestamp-down-means-later
20039 'org-timestamp-up 'org-timestamp-down)))
20040 ((and (not (eq org-support-shift-select 'always))
20041 org-enable-priority-commands
20042 (org-at-heading-p))
20043 (call-interactively 'org-priority-down))
20044 ((and (not org-support-shift-select) (org-at-item-p))
20045 (call-interactively 'org-next-item))
20046 ((org-clocktable-try-shift 'down arg))
20047 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20048 (org-support-shift-select
20049 (org-call-for-shift-select 'next-line))
20050 (t (org-shiftselect-error))))
20052 (defun org-shiftright (&optional arg)
20053 "Cycle the thing at point or in the current line, depending on context.
20054 Depending on context, this does one of the following:
20056 - switch a timestamp at point one day into the future
20057 - on a headline, switch to the next TODO keyword.
20058 - on an item, switch entire list to the next bullet type
20059 - on a property line, switch to the next allowed value
20060 - on a clocktable definition line, move time block into the future"
20061 (interactive "P")
20062 (cond
20063 ((run-hook-with-args-until-success 'org-shiftright-hook))
20064 ((and org-support-shift-select (org-region-active-p))
20065 (org-call-for-shift-select 'forward-char))
20066 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20067 ((and (not (eq org-support-shift-select 'always))
20068 (org-at-heading-p))
20069 (let ((org-inhibit-logging
20070 (not org-treat-S-cursor-todo-selection-as-state-change))
20071 (org-inhibit-blocking
20072 (not org-treat-S-cursor-todo-selection-as-state-change)))
20073 (org-call-with-arg 'org-todo 'right)))
20074 ((or (and org-support-shift-select
20075 (not (eq org-support-shift-select 'always))
20076 (org-at-item-bullet-p))
20077 (and (not org-support-shift-select) (org-at-item-p)))
20078 (org-call-with-arg 'org-cycle-list-bullet nil))
20079 ((and (not (eq org-support-shift-select 'always))
20080 (org-at-property-p))
20081 (call-interactively 'org-property-next-allowed-value))
20082 ((org-clocktable-try-shift 'right arg))
20083 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20084 (org-support-shift-select
20085 (org-call-for-shift-select 'forward-char))
20086 (t (org-shiftselect-error))))
20088 (defun org-shiftleft (&optional arg)
20089 "Cycle the thing at point or in the current line, depending on context.
20090 Depending on context, this does one of the following:
20092 - switch a timestamp at point one day into the past
20093 - on a headline, switch to the previous TODO keyword.
20094 - on an item, switch entire list to the previous bullet type
20095 - on a property line, switch to the previous allowed value
20096 - on a clocktable definition line, move time block into the past"
20097 (interactive "P")
20098 (cond
20099 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20100 ((and org-support-shift-select (org-region-active-p))
20101 (org-call-for-shift-select 'backward-char))
20102 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20103 ((and (not (eq org-support-shift-select 'always))
20104 (org-at-heading-p))
20105 (let ((org-inhibit-logging
20106 (not org-treat-S-cursor-todo-selection-as-state-change))
20107 (org-inhibit-blocking
20108 (not org-treat-S-cursor-todo-selection-as-state-change)))
20109 (org-call-with-arg 'org-todo 'left)))
20110 ((or (and org-support-shift-select
20111 (not (eq org-support-shift-select 'always))
20112 (org-at-item-bullet-p))
20113 (and (not org-support-shift-select) (org-at-item-p)))
20114 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20115 ((and (not (eq org-support-shift-select 'always))
20116 (org-at-property-p))
20117 (call-interactively 'org-property-previous-allowed-value))
20118 ((org-clocktable-try-shift 'left arg))
20119 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20120 (org-support-shift-select
20121 (org-call-for-shift-select 'backward-char))
20122 (t (org-shiftselect-error))))
20124 (defun org-shiftcontrolright ()
20125 "Switch to next TODO set."
20126 (interactive)
20127 (cond
20128 ((and org-support-shift-select (org-region-active-p))
20129 (org-call-for-shift-select 'forward-word))
20130 ((and (not (eq org-support-shift-select 'always))
20131 (org-at-heading-p))
20132 (org-call-with-arg 'org-todo 'nextset))
20133 (org-support-shift-select
20134 (org-call-for-shift-select 'forward-word))
20135 (t (org-shiftselect-error))))
20137 (defun org-shiftcontrolleft ()
20138 "Switch to previous TODO set."
20139 (interactive)
20140 (cond
20141 ((and org-support-shift-select (org-region-active-p))
20142 (org-call-for-shift-select 'backward-word))
20143 ((and (not (eq org-support-shift-select 'always))
20144 (org-at-heading-p))
20145 (org-call-with-arg 'org-todo 'previousset))
20146 (org-support-shift-select
20147 (org-call-for-shift-select 'backward-word))
20148 (t (org-shiftselect-error))))
20150 (defun org-shiftcontrolup (&optional n)
20151 "Change timestamps synchronously up in CLOCK log lines.
20152 Optional argument N tells to change by that many units."
20153 (interactive "P")
20154 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20155 (let (org-support-shift-select)
20156 (org-clock-timestamps-up n))
20157 (user-error "Not at a clock log")))
20159 (defun org-shiftcontroldown (&optional n)
20160 "Change timestamps synchronously down in CLOCK log lines.
20161 Optional argument N tells to change by that many units."
20162 (interactive "P")
20163 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20164 (let (org-support-shift-select)
20165 (org-clock-timestamps-down n))
20166 (user-error "Not at a clock log")))
20168 (defun org-ctrl-c-ret ()
20169 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20170 (interactive)
20171 (cond
20172 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20173 (t (call-interactively 'org-insert-heading))))
20175 (defun org-find-visible ()
20176 (let ((s (point)))
20177 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20178 (get-char-property s 'invisible)))
20180 (defun org-find-invisible ()
20181 (let ((s (point)))
20182 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20183 (not (get-char-property s 'invisible))))
20186 (defun org-copy-visible (beg end)
20187 "Copy the visible parts of the region."
20188 (interactive "r")
20189 (let (snippets s)
20190 (save-excursion
20191 (save-restriction
20192 (narrow-to-region beg end)
20193 (setq s (goto-char (point-min)))
20194 (while (not (= (point) (point-max)))
20195 (goto-char (org-find-invisible))
20196 (push (buffer-substring s (point)) snippets)
20197 (setq s (goto-char (org-find-visible))))))
20198 (kill-new (apply 'concat (nreverse snippets)))))
20200 (defun org-copy-special ()
20201 "Copy region in table or copy current subtree.
20202 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20203 See the individual commands for more information."
20204 (interactive)
20205 (call-interactively
20206 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20208 (defun org-cut-special ()
20209 "Cut region in table or cut current subtree.
20210 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20211 See the individual commands for more information."
20212 (interactive)
20213 (call-interactively
20214 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20216 (defun org-paste-special (arg)
20217 "Paste rectangular region into table, or past subtree relative to level.
20218 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20219 See the individual commands for more information."
20220 (interactive "P")
20221 (if (org-at-table-p)
20222 (org-table-paste-rectangle)
20223 (org-paste-subtree arg)))
20225 (defsubst org-in-fixed-width-region-p ()
20226 "Is point in a fixed-width region?"
20227 (save-match-data
20228 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20230 (defun org-edit-special (&optional arg)
20231 "Call a special editor for the element at point.
20232 When at a table, call the formula editor with `org-table-edit-formulas'.
20233 When in a source code block, call `org-edit-src-code'.
20234 When in a fixed-width region, call `org-edit-fixed-width-region'.
20235 When at an #+INCLUDE keyword, visit the included file.
20236 On a link, call `ffap' to visit the link at point.
20237 Otherwise, return a user error."
20238 (interactive "P")
20239 (let ((element (org-element-at-point)))
20240 (assert (not buffer-read-only) nil
20241 "Buffer is read-only: %s" (buffer-name))
20242 (case (org-element-type element)
20243 (src-block
20244 (if (not arg) (org-edit-src-code)
20245 (let* ((info (org-babel-get-src-block-info))
20246 (lang (nth 0 info))
20247 (params (nth 2 info))
20248 (session (cdr (assq :session params))))
20249 (if (not session) (org-edit-src-code)
20250 ;; At a src-block with a session and function called with
20251 ;; an ARG: switch to the buffer related to the inferior
20252 ;; process.
20253 (switch-to-buffer
20254 (funcall (intern (concat "org-babel-prep-session:" lang))
20255 session params))))))
20256 (keyword
20257 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20258 (find-file
20259 (org-remove-double-quotes
20260 (car (org-split-string (org-element-property :value element)))))
20261 (user-error "No special environment to edit here")))
20262 (table
20263 (if (eq (org-element-property :type element) 'table.el)
20264 (org-edit-src-code)
20265 (call-interactively 'org-table-edit-formulas)))
20266 ;; Only Org tables contain `table-row' type elements.
20267 (table-row (call-interactively 'org-table-edit-formulas))
20268 ((example-block export-block) (org-edit-src-code))
20269 (fixed-width (org-edit-fixed-width-region))
20270 (otherwise
20271 ;; No notable element at point. Though, we may be at a link,
20272 ;; which is an object. Thus, scan deeper.
20273 (if (eq (org-element-type (org-element-context element)) 'link)
20274 (call-interactively 'ffap)
20275 (user-error "No special environment to edit here"))))))
20277 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20278 (defun org-ctrl-c-ctrl-c (&optional arg)
20279 "Set tags in headline, or update according to changed information at point.
20281 This command does many different things, depending on context:
20283 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20284 this is what we do.
20286 - If the cursor is on a statistics cookie, update it.
20288 - If the cursor is in a headline, prompt for tags and insert them
20289 into the current line, aligned to `org-tags-column'. When called
20290 with prefix arg, realign all tags in the current buffer.
20292 - If the cursor is in one of the special #+KEYWORD lines, this
20293 triggers scanning the buffer for these lines and updating the
20294 information.
20296 - If the cursor is inside a table, realign the table. This command
20297 works even if the automatic table editor has been turned off.
20299 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20300 the entire table.
20302 - If the cursor is at a footnote reference or definition, jump to
20303 the corresponding definition or references, respectively.
20305 - If the cursor is a the beginning of a dynamic block, update it.
20307 - If the current buffer is a capture buffer, close note and file it.
20309 - If the cursor is on a <<<target>>>, update radio targets and
20310 corresponding links in this buffer.
20312 - If the cursor is on a numbered item in a plain list, renumber the
20313 ordered list.
20315 - If the cursor is on a checkbox, toggle it.
20317 - If the cursor is on a code block, evaluate it. The variable
20318 `org-confirm-babel-evaluate' can be used to control prompting
20319 before code block evaluation, by default every code block
20320 evaluation requires confirmation. Code block evaluation can be
20321 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20322 (interactive "P")
20323 (cond
20324 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20325 org-occur-highlights
20326 org-latex-fragment-image-overlays)
20327 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20328 (org-remove-occur-highlights)
20329 (org-remove-latex-fragment-image-overlays)
20330 (message "Temporary highlights/overlays removed from current buffer"))
20331 ((and (local-variable-p 'org-finish-function (current-buffer))
20332 (fboundp org-finish-function))
20333 (funcall org-finish-function))
20334 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20336 (let* ((context (org-element-context)) (type (org-element-type context)))
20337 ;; Test if point is within a blank line.
20338 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20339 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20340 (user-error "C-c C-c can do nothing useful at this location"))
20341 (case type
20342 ;; When at a link, act according to the parent instead.
20343 (link (setq context (org-element-property :parent context))
20344 (setq type (org-element-type context)))
20345 ;; Unsupported object types: check parent element instead.
20346 ((bold code entity export-snippet inline-babel-call inline-src-block
20347 italic latex-fragment line-break macro strike-through subscript
20348 superscript underline verbatim)
20349 (while (and (setq context (org-element-property :parent context))
20350 (not (memq (setq type (org-element-type context))
20351 '(paragraph verse-block)))))))
20352 ;; For convenience: at the first line of a paragraph on the
20353 ;; same line as an item, apply function on that item instead.
20354 (when (eq type 'paragraph)
20355 (let ((parent (org-element-property :parent context)))
20356 (when (and (eq (org-element-type parent) 'item)
20357 (= (point-at-bol) (org-element-property :begin parent)))
20358 (setq context parent type 'item))))
20359 ;; Act according to type of element or object at point.
20360 (case type
20361 (clock (org-clock-update-time-maybe))
20362 (dynamic-block
20363 (save-excursion
20364 (goto-char (org-element-property :post-affiliated context))
20365 (org-update-dblock)))
20366 (footnote-definition
20367 (goto-char (org-element-property :post-affiliated context))
20368 (call-interactively 'org-footnote-action))
20369 (footnote-reference (call-interactively 'org-footnote-action))
20370 ((headline inlinetask)
20371 (save-excursion (goto-char (org-element-property :begin context))
20372 (call-interactively 'org-set-tags)))
20373 (item
20374 ;; At an item: a double C-u set checkbox to "[-]"
20375 ;; unconditionally, whereas a single one will toggle its
20376 ;; presence. Without an universal argument, if the item
20377 ;; has a checkbox, toggle it. Otherwise repair the list.
20378 (let* ((box (org-element-property :checkbox context))
20379 (struct (org-element-property :structure context))
20380 (old-struct (copy-tree struct))
20381 (parents (org-list-parents-alist struct))
20382 (prevs (org-list-prevs-alist struct))
20383 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20384 (org-list-set-checkbox
20385 (org-element-property :begin context) struct
20386 (cond ((equal arg '(16)) "[-]")
20387 ((and (not box) (equal arg '(4))) "[ ]")
20388 ((or (not box) (equal arg '(4))) nil)
20389 ((eq box 'on) "[ ]")
20390 (t "[X]")))
20391 ;; Mimic `org-list-write-struct' but with grabbing
20392 ;; a return value from `org-list-struct-fix-box'.
20393 (org-list-struct-fix-ind struct parents 2)
20394 (org-list-struct-fix-item-end struct)
20395 (org-list-struct-fix-bul struct prevs)
20396 (org-list-struct-fix-ind struct parents)
20397 (let ((block-item
20398 (org-list-struct-fix-box struct parents prevs orderedp)))
20399 (if (and box (equal struct old-struct))
20400 (if (equal arg '(16))
20401 (message "Checkboxes already reset")
20402 (user-error "Cannot toggle this checkbox: %s"
20403 (if (eq box 'on)
20404 "all subitems checked"
20405 "unchecked subitems")))
20406 (org-list-struct-apply-struct struct old-struct)
20407 (org-update-checkbox-count-maybe))
20408 (when block-item
20409 (message "Checkboxes were removed due to empty box at line %d"
20410 (org-current-line block-item))))))
20411 (keyword
20412 (let ((org-inhibit-startup-visibility-stuff t)
20413 (org-startup-align-all-tables nil))
20414 (when (boundp 'org-table-coordinate-overlays)
20415 (mapc 'delete-overlay org-table-coordinate-overlays)
20416 (setq org-table-coordinate-overlays nil))
20417 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20418 (message "Local setup has been refreshed"))
20419 (plain-list
20420 ;; At a plain list, with a double C-u argument, set
20421 ;; checkboxes of each item to "[-]", whereas a single one
20422 ;; will toggle their presence according to the state of the
20423 ;; first item in the list. Without an argument, repair the
20424 ;; list.
20425 (let* ((begin (org-element-property :contents-begin context))
20426 (beginm (move-marker (make-marker) begin))
20427 (struct (org-element-property :structure context))
20428 (old-struct (copy-tree struct))
20429 (first-box (save-excursion
20430 (goto-char begin)
20431 (looking-at org-list-full-item-re)
20432 (match-string-no-properties 3)))
20433 (new-box (cond ((equal arg '(16)) "[-]")
20434 ((equal arg '(4)) (unless first-box "[ ]"))
20435 ((equal first-box "[X]") "[ ]")
20436 (t "[X]"))))
20437 (cond
20438 (arg
20439 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20440 (org-list-get-all-items
20441 begin struct (org-list-prevs-alist struct))))
20442 ((and first-box (eq (point) begin))
20443 ;; For convenience, when point is at bol on the first
20444 ;; item of the list and no argument is provided, simply
20445 ;; toggle checkbox of that item, if any.
20446 (org-list-set-checkbox begin struct new-box)))
20447 (org-list-write-struct
20448 struct (org-list-parents-alist struct) old-struct)
20449 (org-update-checkbox-count-maybe)
20450 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20451 ((property-drawer node-property)
20452 (call-interactively 'org-property-action))
20453 ((radio-target target)
20454 (call-interactively 'org-update-radio-target-regexp))
20455 (statistics-cookie
20456 (call-interactively 'org-update-statistics-cookies))
20457 ((table table-cell table-row)
20458 ;; At a table, recalculate every field and align it. Also
20459 ;; send the table if necessary. If the table has
20460 ;; a `table.el' type, just give up. At a table row or
20461 ;; cell, maybe recalculate line but always align table.
20462 (if (eq (org-element-property :type context) 'table.el)
20463 (message "Use C-c ' to edit table.el tables")
20464 (let ((org-enable-table-editor t))
20465 (if (or (eq type 'table)
20466 ;; Check if point is at a TBLFM line.
20467 (and (eq type 'table-row)
20468 (= (point) (org-element-property :end context))))
20469 (save-excursion
20470 (if (org-at-TBLFM-p)
20471 (progn (require 'org-table)
20472 (org-table-calc-current-TBLFM))
20473 (goto-char (org-element-property :contents-begin context))
20474 (org-call-with-arg 'org-table-recalculate (or arg t))
20475 (orgtbl-send-table 'maybe)))
20476 (org-table-maybe-eval-formula)
20477 (cond (arg (call-interactively 'org-table-recalculate))
20478 ((org-table-maybe-recalculate-line))
20479 (t (org-table-align)))))))
20480 (timestamp (org-timestamp-change 0 'day))
20481 (otherwise
20482 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20483 (user-error
20484 "C-c C-c can do nothing useful at this location")))))))))
20486 (defun org-mode-restart ()
20487 "Restart Org-mode, to scan again for special lines.
20488 Also updates the keyword regular expressions."
20489 (interactive)
20490 ;; this will set the mode *and* set file local variables.
20491 (normal-mode)
20492 ;; but it may leave us in some unrelated mode
20493 (unless (derived-mode-p "org-mode")
20494 (org-mode))
20495 (message "Org-mode restarted"))
20497 (defun org-kill-note-or-show-branches ()
20498 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20499 (interactive)
20500 (if (not org-finish-function)
20501 (progn
20502 (hide-subtree)
20503 (call-interactively 'show-branches))
20504 (let ((org-note-abort t))
20505 (funcall org-finish-function))))
20507 (defun org-open-line (n)
20508 "Insert a new row in tables, call `open-line' elsewhere.
20509 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
20510 (interactive "*p")
20511 (cond
20512 ((not org-special-ctrl-o)
20513 (open-line n))
20514 ((org-at-table-p)
20515 (org-table-insert-row))
20517 (open-line n))))
20519 (defun org-return (&optional indent)
20520 "Goto next table row or insert a newline.
20521 Calls `org-table-next-row' or `newline', depending on context.
20522 See the individual commands for more information."
20523 (interactive)
20524 (let (org-ts-what)
20525 (cond
20526 ((or (bobp) (org-in-src-block-p))
20527 (if indent (newline-and-indent) (newline)))
20528 ((org-at-table-p)
20529 (org-table-justify-field-maybe)
20530 (call-interactively 'org-table-next-row))
20531 ;; when `newline-and-indent' is called within a list, make sure
20532 ;; text moved stays inside the item.
20533 ((and (org-in-item-p) indent)
20534 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20535 (progn
20536 (save-match-data (newline))
20537 (org-indent-line-to (length (match-string 0))))
20538 (let ((ind (org-get-indentation)))
20539 (newline)
20540 (if (org-looking-back org-list-end-re)
20541 (org-indent-line)
20542 (org-indent-line-to ind)))))
20543 ((and org-return-follows-link
20544 (org-at-timestamp-p t)
20545 (not (eq org-ts-what 'after)))
20546 (org-follow-timestamp-link))
20547 ((and org-return-follows-link
20548 (let ((tprop (get-text-property (point) 'face)))
20549 (or (eq tprop 'org-link)
20550 (and (listp tprop) (memq 'org-link tprop)))))
20551 (call-interactively 'org-open-at-point))
20552 ((and (org-at-heading-p)
20553 (looking-at
20554 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20555 (org-show-entry)
20556 (end-of-line 1)
20557 (newline))
20558 (t (if indent (newline-and-indent) (newline))))))
20560 (defun org-return-indent ()
20561 "Goto next table row or insert a newline and indent.
20562 Calls `org-table-next-row' or `newline-and-indent', depending on
20563 context. See the individual commands for more information."
20564 (interactive)
20565 (org-return t))
20567 (defun org-ctrl-c-star ()
20568 "Compute table, or change heading status of lines.
20569 Calls `org-table-recalculate' or `org-toggle-heading',
20570 depending on context."
20571 (interactive)
20572 (cond
20573 ((org-at-table-p)
20574 (call-interactively 'org-table-recalculate))
20576 ;; Convert all lines in region to list items
20577 (call-interactively 'org-toggle-heading))))
20579 (defun org-ctrl-c-minus ()
20580 "Insert separator line in table or modify bullet status of line.
20581 Also turns a plain line or a region of lines into list items.
20582 Calls `org-table-insert-hline', `org-toggle-item', or
20583 `org-cycle-list-bullet', depending on context."
20584 (interactive)
20585 (cond
20586 ((org-at-table-p)
20587 (call-interactively 'org-table-insert-hline))
20588 ((org-region-active-p)
20589 (call-interactively 'org-toggle-item))
20590 ((org-in-item-p)
20591 (call-interactively 'org-cycle-list-bullet))
20593 (call-interactively 'org-toggle-item))))
20595 (defun org-toggle-item (arg)
20596 "Convert headings or normal lines to items, items to normal lines.
20597 If there is no active region, only the current line is considered.
20599 If the first non blank line in the region is a headline, convert
20600 all headlines to items, shifting text accordingly.
20602 If it is an item, convert all items to normal lines.
20604 If it is normal text, change region into a list of items.
20605 With a prefix argument ARG, change the region in a single item."
20606 (interactive "P")
20607 (let ((shift-text
20608 (function
20609 ;; Shift text in current section to IND, from point to END.
20610 ;; The function leaves point to END line.
20611 (lambda (ind end)
20612 (let ((min-i 1000) (end (copy-marker end)))
20613 ;; First determine the minimum indentation (MIN-I) of
20614 ;; the text.
20615 (save-excursion
20616 (catch 'exit
20617 (while (< (point) end)
20618 (let ((i (org-get-indentation)))
20619 (cond
20620 ;; Skip blank lines and inline tasks.
20621 ((looking-at "^[ \t]*$"))
20622 ((looking-at org-outline-regexp-bol))
20623 ;; We can't find less than 0 indentation.
20624 ((zerop i) (throw 'exit (setq min-i 0)))
20625 ((< i min-i) (setq min-i i))))
20626 (forward-line))))
20627 ;; Then indent each line so that a line indented to
20628 ;; MIN-I becomes indented to IND. Ignore blank lines
20629 ;; and inline tasks in the process.
20630 (let ((delta (- ind min-i)))
20631 (while (< (point) end)
20632 (unless (or (looking-at "^[ \t]*$")
20633 (looking-at org-outline-regexp-bol))
20634 (org-indent-line-to (+ (org-get-indentation) delta)))
20635 (forward-line)))))))
20636 (skip-blanks
20637 (function
20638 ;; Return beginning of first non-blank line, starting from
20639 ;; line at POS.
20640 (lambda (pos)
20641 (save-excursion
20642 (goto-char pos)
20643 (skip-chars-forward " \r\t\n")
20644 (point-at-bol)))))
20645 beg end)
20646 ;; Determine boundaries of changes.
20647 (if (org-region-active-p)
20648 (setq beg (funcall skip-blanks (region-beginning))
20649 end (copy-marker (region-end)))
20650 (setq beg (funcall skip-blanks (point-at-bol))
20651 end (copy-marker (point-at-eol))))
20652 ;; Depending on the starting line, choose an action on the text
20653 ;; between BEG and END.
20654 (org-with-limited-levels
20655 (save-excursion
20656 (goto-char beg)
20657 (cond
20658 ;; Case 1. Start at an item: de-itemize. Note that it only
20659 ;; happens when a region is active: `org-ctrl-c-minus'
20660 ;; would call `org-cycle-list-bullet' otherwise.
20661 ((org-at-item-p)
20662 (while (< (point) end)
20663 (when (org-at-item-p)
20664 (skip-chars-forward " \t")
20665 (delete-region (point) (match-end 0)))
20666 (forward-line)))
20667 ;; Case 2. Start at an heading: convert to items.
20668 ((org-at-heading-p)
20669 (let* ((bul (org-list-bullet-string "-"))
20670 (bul-len (length bul))
20671 ;; Indentation of the first heading. It should be
20672 ;; relative to the indentation of its parent, if any.
20673 (start-ind (save-excursion
20674 (cond
20675 ((not org-adapt-indentation) 0)
20676 ((not (outline-previous-heading)) 0)
20677 (t (length (match-string 0))))))
20678 ;; Level of first heading. Further headings will be
20679 ;; compared to it to determine hierarchy in the list.
20680 (ref-level (org-reduced-level (org-outline-level))))
20681 (while (< (point) end)
20682 (let* ((level (org-reduced-level (org-outline-level)))
20683 (delta (max 0 (- level ref-level))))
20684 ;; If current headline is less indented than the first
20685 ;; one, set it as reference, in order to preserve
20686 ;; subtrees.
20687 (when (< level ref-level) (setq ref-level level))
20688 (replace-match bul t t)
20689 (org-indent-line-to (+ start-ind (* delta bul-len)))
20690 ;; Ensure all text down to END (or SECTION-END) belongs
20691 ;; to the newly created item.
20692 (let ((section-end (save-excursion
20693 (or (outline-next-heading) (point)))))
20694 (forward-line)
20695 (funcall shift-text
20696 (+ start-ind (* (1+ delta) bul-len))
20697 (min end section-end)))))))
20698 ;; Case 3. Normal line with ARG: make the first line of region
20699 ;; an item, and shift indentation of others lines to
20700 ;; set them as item's body.
20701 (arg (let* ((bul (org-list-bullet-string "-"))
20702 (bul-len (length bul))
20703 (ref-ind (org-get-indentation)))
20704 (skip-chars-forward " \t")
20705 (insert bul)
20706 (forward-line)
20707 (while (< (point) end)
20708 ;; Ensure that lines less indented than first one
20709 ;; still get included in item body.
20710 (funcall shift-text
20711 (+ ref-ind bul-len)
20712 (min end (save-excursion (or (outline-next-heading)
20713 (point)))))
20714 (forward-line))))
20715 ;; Case 4. Normal line without ARG: turn each non-item line
20716 ;; into an item.
20718 (while (< (point) end)
20719 (unless (or (org-at-heading-p) (org-at-item-p))
20720 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20721 (replace-match
20722 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20723 (forward-line))))))))
20725 (defun org-toggle-heading (&optional nstars)
20726 "Convert headings to normal text, or items or text to headings.
20727 If there is no active region, only convert the current line.
20729 With a \\[universal-argument] prefix, convert the whole list at
20730 point into heading.
20732 In a region:
20734 - If the first non blank line is a headline, remove the stars
20735 from all headlines in the region.
20737 - If it is a normal line, turn each and every normal line (i.e.,
20738 not an heading or an item) in the region into headings. If you
20739 want to convert only the first line of this region, use one
20740 universal prefix argument.
20742 - If it is a plain list item, turn all plain list items into headings.
20744 When converting a line into a heading, the number of stars is chosen
20745 such that the lines become children of the current entry. However,
20746 when a numeric prefix argument is given, its value determines the
20747 number of stars to add."
20748 (interactive "P")
20749 (let ((skip-blanks
20750 (function
20751 ;; Return beginning of first non-blank line, starting from
20752 ;; line at POS.
20753 (lambda (pos)
20754 (save-excursion
20755 (goto-char pos)
20756 (while (org-at-comment-p) (forward-line))
20757 (skip-chars-forward " \r\t\n")
20758 (point-at-bol)))))
20759 beg end toggled)
20760 ;; Determine boundaries of changes. If a universal prefix has
20761 ;; been given, put the list in a region. If region ends at a bol,
20762 ;; do not consider the last line to be in the region.
20764 (when (and current-prefix-arg (org-at-item-p))
20765 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20766 (org-mark-element))
20768 (if (org-region-active-p)
20769 (setq beg (funcall skip-blanks (region-beginning))
20770 end (copy-marker (save-excursion
20771 (goto-char (region-end))
20772 (if (bolp) (point) (point-at-eol)))))
20773 (setq beg (funcall skip-blanks (point-at-bol))
20774 end (copy-marker (point-at-eol))))
20775 ;; Ensure inline tasks don't count as headings.
20776 (org-with-limited-levels
20777 (save-excursion
20778 (goto-char beg)
20779 (cond
20780 ;; Case 1. Started at an heading: de-star headings.
20781 ((org-at-heading-p)
20782 (while (< (point) end)
20783 (when (org-at-heading-p t)
20784 (looking-at org-outline-regexp) (replace-match "")
20785 (setq toggled t))
20786 (forward-line)))
20787 ;; Case 2. Started at an item: change items into headlines.
20788 ;; One star will be added by `org-list-to-subtree'.
20789 ((org-at-item-p)
20790 (let* ((stars (make-string
20791 ;; subtract the star that will be added again by
20792 ;; `org-list-to-subtree'
20793 (if (numberp nstars) (1- nstars)
20794 (or (org-current-level) 0))
20795 ?*))
20796 (add-stars
20797 (cond (nstars "") ; stars from prefix only
20798 ((equal stars "") "") ; before first heading
20799 (org-odd-levels-only "*") ; inside heading, odd
20800 (t "")))) ; inside heading, oddeven
20801 (while (< (point) end)
20802 (when (org-at-item-p)
20803 ;; Pay attention to cases when region ends before list.
20804 (let* ((struct (org-list-struct))
20805 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20806 (save-restriction
20807 (narrow-to-region (point) list-end)
20808 (insert
20809 (org-list-to-subtree
20810 (org-list-parse-list t)
20811 '(:istart (concat stars add-stars (funcall get-stars depth))
20812 :icount (concat stars add-stars (funcall get-stars depth)))))))
20813 (setq toggled t))
20814 (forward-line))))
20815 ;; Case 3. Started at normal text: make every line an heading,
20816 ;; skipping headlines and items.
20817 (t (let* ((stars
20818 (make-string
20819 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20820 (add-stars
20821 (cond (nstars "") ; stars from prefix only
20822 ((equal stars "") "*") ; before first heading
20823 (org-odd-levels-only "**") ; inside heading, odd
20824 (t "*"))) ; inside heading, oddeven
20825 (rpl (concat stars add-stars " "))
20826 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20827 (while (< (point) (if (equal nstars '(4)) lend end))
20828 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20829 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20830 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20831 (forward-line)))))))
20832 (unless toggled (message "Cannot toggle heading from here"))))
20834 (defun org-meta-return (&optional arg)
20835 "Insert a new heading or wrap a region in a table.
20836 Calls `org-insert-heading' or `org-table-wrap-region', depending
20837 on context. See the individual commands for more information."
20838 (interactive "P")
20839 (org-check-before-invisible-edit 'insert)
20840 (or (run-hook-with-args-until-success 'org-metareturn-hook)
20841 (let* ((element (org-element-at-point))
20842 (type (org-element-type element)))
20843 (when (eq type 'table-row)
20844 (setq element (org-element-property :parent element))
20845 (setq type 'table))
20846 (if (and (eq type 'table)
20847 (eq (org-element-property :type element) 'org)
20848 (>= (point) (org-element-property :contents-begin element))
20849 (< (point) (org-element-property :contents-end element)))
20850 (call-interactively 'org-table-wrap-region)
20851 (call-interactively 'org-insert-heading)))))
20853 ;;; Menu entries
20855 (defsubst org-in-subtree-not-table-p ()
20856 "Are we in a subtree and not in a table?"
20857 (and (not (org-before-first-heading-p))
20858 (not (org-at-table-p))))
20860 ;; Define the Org-mode menus
20861 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20862 '("Tbl"
20863 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20864 ["Next Field" org-cycle (org-at-table-p)]
20865 ["Previous Field" org-shifttab (org-at-table-p)]
20866 ["Next Row" org-return (org-at-table-p)]
20867 "--"
20868 ["Blank Field" org-table-blank-field (org-at-table-p)]
20869 ["Edit Field" org-table-edit-field (org-at-table-p)]
20870 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20871 "--"
20872 ("Column"
20873 ["Move Column Left" org-metaleft (org-at-table-p)]
20874 ["Move Column Right" org-metaright (org-at-table-p)]
20875 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20876 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20877 ("Row"
20878 ["Move Row Up" org-metaup (org-at-table-p)]
20879 ["Move Row Down" org-metadown (org-at-table-p)]
20880 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20881 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20882 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20883 "--"
20884 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20885 ("Rectangle"
20886 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20887 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20888 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20889 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20890 "--"
20891 ("Calculate"
20892 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20893 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20894 ["Edit Formulas" org-edit-special (org-at-table-p)]
20895 "--"
20896 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20897 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20898 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20899 "--"
20900 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20901 "--"
20902 ["Sum Column/Rectangle" org-table-sum
20903 (or (org-at-table-p) (org-region-active-p))]
20904 ["Which Column?" org-table-current-column (org-at-table-p)])
20905 ["Debug Formulas"
20906 org-table-toggle-formula-debugger
20907 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20908 ["Show Col/Row Numbers"
20909 org-table-toggle-coordinate-overlays
20910 :style toggle
20911 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20912 "--"
20913 ["Create" org-table-create (and (not (org-at-table-p))
20914 org-enable-table-editor)]
20915 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20916 ["Import from File" org-table-import (not (org-at-table-p))]
20917 ["Export to File" org-table-export (org-at-table-p)]
20918 "--"
20919 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20921 (easy-menu-define org-org-menu org-mode-map "Org menu"
20922 '("Org"
20923 ("Show/Hide"
20924 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20925 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20926 ["Sparse Tree..." org-sparse-tree t]
20927 ["Reveal Context" org-reveal t]
20928 ["Show All" show-all t]
20929 "--"
20930 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20931 "--"
20932 ["New Heading" org-insert-heading t]
20933 ("Navigate Headings"
20934 ["Up" outline-up-heading t]
20935 ["Next" outline-next-visible-heading t]
20936 ["Previous" outline-previous-visible-heading t]
20937 ["Next Same Level" outline-forward-same-level t]
20938 ["Previous Same Level" outline-backward-same-level t]
20939 "--"
20940 ["Jump" org-goto t])
20941 ("Edit Structure"
20942 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20943 "--"
20944 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20945 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20946 "--"
20947 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20948 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20949 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20950 "--"
20951 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20952 "--"
20953 ["Copy visible text" org-copy-visible t]
20954 "--"
20955 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20956 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20957 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20958 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20959 "--"
20960 ["Sort Region/Children" org-sort t]
20961 "--"
20962 ["Convert to odd levels" org-convert-to-odd-levels t]
20963 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20964 ("Editing"
20965 ["Emphasis..." org-emphasize t]
20966 ["Edit Source Example" org-edit-special t]
20967 "--"
20968 ["Footnote new/jump" org-footnote-action t]
20969 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20970 ("Archive"
20971 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20972 "--"
20973 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20974 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20975 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20977 "--"
20978 ("Hyperlinks"
20979 ["Store Link (Global)" org-store-link t]
20980 ["Find existing link to here" org-occur-link-in-agenda-files t]
20981 ["Insert Link" org-insert-link t]
20982 ["Follow Link" org-open-at-point t]
20983 "--"
20984 ["Next link" org-next-link t]
20985 ["Previous link" org-previous-link t]
20986 "--"
20987 ["Descriptive Links"
20988 org-toggle-link-display
20989 :style radio
20990 :selected org-descriptive-links
20992 ["Literal Links"
20993 org-toggle-link-display
20994 :style radio
20995 :selected (not org-descriptive-links)])
20996 "--"
20997 ("TODO Lists"
20998 ["TODO/DONE/-" org-todo t]
20999 ("Select keyword"
21000 ["Next keyword" org-shiftright (org-at-heading-p)]
21001 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21002 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21003 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21004 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21005 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21006 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21007 "--"
21008 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21009 :selected org-enforce-todo-dependencies :style toggle :active t]
21010 "Settings for tree at point"
21011 ["Do Children sequentially" org-toggle-ordered-property :style radio
21012 :selected (org-entry-get nil "ORDERED")
21013 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21014 ["Do Children parallel" org-toggle-ordered-property :style radio
21015 :selected (not (org-entry-get nil "ORDERED"))
21016 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21017 "--"
21018 ["Set Priority" org-priority t]
21019 ["Priority Up" org-shiftup t]
21020 ["Priority Down" org-shiftdown t]
21021 "--"
21022 ["Get news from all feeds" org-feed-update-all t]
21023 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21024 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21025 ("TAGS and Properties"
21026 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21027 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21028 "--"
21029 ["Set property" org-set-property (not (org-before-first-heading-p))]
21030 ["Column view of properties" org-columns t]
21031 ["Insert Column View DBlock" org-insert-columns-dblock t])
21032 ("Dates and Scheduling"
21033 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21034 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21035 ("Change Date"
21036 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21037 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21038 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21039 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21040 ["Compute Time Range" org-evaluate-time-range t]
21041 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21042 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21043 "--"
21044 ["Custom time format" org-toggle-time-stamp-overlays
21045 :style radio :selected org-display-custom-times]
21046 "--"
21047 ["Goto Calendar" org-goto-calendar t]
21048 ["Date from Calendar" org-date-from-calendar t]
21049 "--"
21050 ["Start/Restart Timer" org-timer-start t]
21051 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21052 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21053 ["Insert Timer String" org-timer t]
21054 ["Insert Timer Item" org-timer-item t])
21055 ("Logging work"
21056 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21057 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21058 ["Clock out" org-clock-out t]
21059 ["Clock cancel" org-clock-cancel t]
21060 "--"
21061 ["Mark as default task" org-clock-mark-default-task t]
21062 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21063 ["Goto running clock" org-clock-goto t]
21064 "--"
21065 ["Display times" org-clock-display t]
21066 ["Create clock table" org-clock-report t]
21067 "--"
21068 ["Record DONE time"
21069 (progn (setq org-log-done (not org-log-done))
21070 (message "Switching to %s will %s record a timestamp"
21071 (car org-done-keywords)
21072 (if org-log-done "automatically" "not")))
21073 :style toggle :selected org-log-done])
21074 "--"
21075 ["Agenda Command..." org-agenda t]
21076 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21077 ("File List for Agenda")
21078 ("Special views current file"
21079 ["TODO Tree" org-show-todo-tree t]
21080 ["Check Deadlines" org-check-deadlines t]
21081 ["Timeline" org-timeline t]
21082 ["Tags/Property tree" org-match-sparse-tree t])
21083 "--"
21084 ["Export/Publish..." org-export-dispatch t]
21085 ("LaTeX"
21086 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21087 :selected org-cdlatex-mode]
21088 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21089 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21090 ["Modify math symbol" org-cdlatex-math-modify
21091 (org-inside-LaTeX-fragment-p)]
21092 ["Insert citation" org-reftex-citation t]
21093 "--"
21094 ["Template for BEAMER" (org-beamer-insert-options-template) t])
21095 "--"
21096 ("MobileOrg"
21097 ["Push Files and Views" org-mobile-push t]
21098 ["Get Captured and Flagged" org-mobile-pull t]
21099 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21100 "--"
21101 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21102 "--"
21103 ("Documentation"
21104 ["Show Version" org-version t]
21105 ["Info Documentation" org-info t])
21106 ("Customize"
21107 ["Browse Org Group" org-customize t]
21108 "--"
21109 ["Expand This Menu" org-create-customize-menu
21110 (fboundp 'customize-menu-create)])
21111 ["Send bug report" org-submit-bug-report t]
21112 "--"
21113 ("Refresh/Reload"
21114 ["Refresh setup current buffer" org-mode-restart t]
21115 ["Reload Org (after update)" org-reload t]
21116 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21119 (defun org-info (&optional node)
21120 "Read documentation for Org-mode in the info system.
21121 With optional NODE, go directly to that node."
21122 (interactive)
21123 (info (format "(org)%s" (or node ""))))
21125 ;;;###autoload
21126 (defun org-submit-bug-report ()
21127 "Submit a bug report on Org-mode via mail.
21129 Don't hesitate to report any problems or inaccurate documentation.
21131 If you don't have setup sending mail from (X)Emacs, please copy the
21132 output buffer into your mail program, as it gives us important
21133 information about your Org-mode version and configuration."
21134 (interactive)
21135 (require 'reporter)
21136 (org-load-modules-maybe)
21137 (org-require-autoloaded-modules)
21138 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21139 (reporter-submit-bug-report
21140 "emacs-orgmode@gnu.org"
21141 (org-version nil 'full)
21142 (let (list)
21143 (save-window-excursion
21144 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21145 (delete-other-windows)
21146 (erase-buffer)
21147 (insert "You are about to submit a bug report to the Org-mode mailing list.
21149 We would like to add your full Org-mode and Outline configuration to the
21150 bug report. This greatly simplifies the work of the maintainer and
21151 other experts on the mailing list.
21153 HOWEVER, some variables you have customized may contain private
21154 information. The names of customers, colleagues, or friends, might
21155 appear in the form of file names, tags, todo states, or search strings.
21156 If you answer yes to the prompt, you might want to check and remove
21157 such private information before sending the email.")
21158 (add-text-properties (point-min) (point-max) '(face org-warning))
21159 (when (yes-or-no-p "Include your Org-mode configuration ")
21160 (mapatoms
21161 (lambda (v)
21162 (and (boundp v)
21163 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21164 (or (and (symbol-value v)
21165 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21166 (and
21167 (get v 'custom-type) (get v 'standard-value)
21168 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21169 (push v list)))))
21170 (kill-buffer (get-buffer "*Warn about privacy*"))
21171 list))
21172 nil nil
21173 "Remember to cover the basics, that is, what you expected to happen and
21174 what in fact did happen. You don't know how to make a good report? See
21176 http://orgmode.org/manual/Feedback.html#Feedback
21178 Your bug report will be posted to the Org-mode mailing list.
21179 ------------------------------------------------------------------------")
21180 (save-excursion
21181 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21182 (replace-match "\\1Bug: \\3 [\\2]")))))
21185 (defun org-install-agenda-files-menu ()
21186 (let ((bl (buffer-list)))
21187 (save-excursion
21188 (while bl
21189 (set-buffer (pop bl))
21190 (if (derived-mode-p 'org-mode) (setq bl nil)))
21191 (when (derived-mode-p 'org-mode)
21192 (easy-menu-change
21193 '("Org") "File List for Agenda"
21194 (append
21195 (list
21196 ["Edit File List" (org-edit-agenda-file-list) t]
21197 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21198 ["Remove Current File from List" org-remove-file t]
21199 ["Cycle through agenda files" org-cycle-agenda-files t]
21200 ["Occur in all agenda files" org-occur-in-agenda-files t]
21201 "--")
21202 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21204 ;;;; Documentation
21206 (defun org-require-autoloaded-modules ()
21207 (interactive)
21208 (mapc 'require
21209 '(org-agenda org-archive org-attach org-clock org-colview org-id
21210 org-table org-timer)))
21212 ;;;###autoload
21213 (defun org-reload (&optional uncompiled)
21214 "Reload all org lisp files.
21215 With prefix arg UNCOMPILED, load the uncompiled versions."
21216 (interactive "P")
21217 (require 'loadhist)
21218 (let* ((org-dir (org-find-library-dir "org"))
21219 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21220 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21221 (remove-re (mapconcat 'identity
21222 (mapcar (lambda (f) (concat "^" f "$"))
21223 (list (if (featurep 'xemacs)
21224 "org-colview"
21225 "org-colview-xemacs")
21226 "org" "org-loaddefs" "org-version"))
21227 "\\|"))
21228 (feats (delete-dups
21229 (mapcar 'file-name-sans-extension
21230 (mapcar 'file-name-nondirectory
21231 (delq nil
21232 (mapcar 'feature-file
21233 features))))))
21234 (lfeat (append
21235 (sort
21236 (setq feats
21237 (delq nil (mapcar
21238 (lambda (f)
21239 (if (and (string-match feature-re f)
21240 (not (string-match remove-re f)))
21241 f nil))
21242 feats)))
21243 'string-lessp)
21244 (list "org-version" "org")))
21245 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21246 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21247 load-uncore load-misses)
21248 (setq load-misses
21249 (delq 't
21250 (mapcar (lambda (f)
21251 (or (org-load-noerror-mustsuffix (concat org-dir f))
21252 (and (string= org-dir contrib-dir)
21253 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21254 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21255 (add-to-list 'load-uncore f 'append)
21258 lfeat)))
21259 (if load-uncore
21260 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21261 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21262 (if load-misses
21263 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21264 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21265 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21267 ;;;###autoload
21268 (defun org-customize ()
21269 "Call the customize function with org as argument."
21270 (interactive)
21271 (org-load-modules-maybe)
21272 (org-require-autoloaded-modules)
21273 (customize-browse 'org))
21275 (defun org-create-customize-menu ()
21276 "Create a full customization menu for Org-mode, insert it into the menu."
21277 (interactive)
21278 (org-load-modules-maybe)
21279 (org-require-autoloaded-modules)
21280 (if (fboundp 'customize-menu-create)
21281 (progn
21282 (easy-menu-change
21283 '("Org") "Customize"
21284 `(["Browse Org group" org-customize t]
21285 "--"
21286 ,(customize-menu-create 'org)
21287 ["Set" Custom-set t]
21288 ["Save" Custom-save t]
21289 ["Reset to Current" Custom-reset-current t]
21290 ["Reset to Saved" Custom-reset-saved t]
21291 ["Reset to Standard Settings" Custom-reset-standard t]))
21292 (message "\"Org\"-menu now contains full customization menu"))
21293 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21295 ;;;; Miscellaneous stuff
21297 ;;; Generally useful functions
21299 (defun org-get-at-bol (property)
21300 "Get text property PROPERTY at beginning of line."
21301 (get-text-property (point-at-bol) property))
21303 (defun org-find-text-property-in-string (prop s)
21304 "Return the first non-nil value of property PROP in string S."
21305 (or (get-text-property 0 prop s)
21306 (get-text-property (or (next-single-property-change 0 prop s) 0)
21307 prop s)))
21309 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21310 "Display the given MESSAGE as a warning."
21311 (if (fboundp 'display-warning)
21312 (display-warning 'org message
21313 (if (featurep 'xemacs) 'warning :warning))
21314 (let ((buf (get-buffer-create "*Org warnings*")))
21315 (with-current-buffer buf
21316 (goto-char (point-max))
21317 (insert "Warning (Org): " message)
21318 (unless (bolp)
21319 (newline)))
21320 (display-buffer buf)
21321 (sit-for 0))))
21323 (defun org-eval (form)
21324 "Eval FORM and return result."
21325 (condition-case error
21326 (eval form)
21327 (error (format "%%![Error: %s]" error))))
21329 (defun org-in-clocktable-p ()
21330 "Check if the cursor is in a clocktable."
21331 (let ((pos (point)) start)
21332 (save-excursion
21333 (end-of-line 1)
21334 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21335 (setq start (match-beginning 0))
21336 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21337 (>= (match-end 0) pos)
21338 start))))
21340 (defun org-in-commented-line ()
21341 "Is point in a line starting with `#'?"
21342 (equal (char-after (point-at-bol)) ?#))
21344 (defun org-in-indented-comment-line ()
21345 "Is point in a line starting with `#' after some white space?"
21346 (save-excursion
21347 (save-match-data
21348 (goto-char (point-at-bol))
21349 (looking-at "[ \t]*#"))))
21351 (defun org-in-verbatim-emphasis ()
21352 (save-match-data
21353 (and (org-in-regexp org-emph-re 2)
21354 (>= (point) (match-beginning 3))
21355 (<= (point) (match-end 4))
21356 (member (match-string 3) '("=" "~")))))
21358 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21359 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21360 (if (and marker (marker-buffer marker)
21361 (buffer-live-p (marker-buffer marker)))
21362 (progn
21363 (org-pop-to-buffer-same-window (marker-buffer marker))
21364 (if (or (> marker (point-max)) (< marker (point-min)))
21365 (widen))
21366 (goto-char marker)
21367 (org-show-context 'org-goto))
21368 (if bookmark
21369 (bookmark-jump bookmark)
21370 (error "Cannot find location"))))
21372 (defun org-quote-csv-field (s)
21373 "Quote field for inclusion in CSV material."
21374 (if (string-match "[\",]" s)
21375 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21378 (defun org-force-self-insert (N)
21379 "Needed to enforce self-insert under remapping."
21380 (interactive "p")
21381 (self-insert-command N))
21383 (defun org-string-width (s)
21384 "Compute width of string, ignoring invisible characters.
21385 This ignores character with invisibility property `org-link', and also
21386 characters with property `org-cwidth', because these will become invisible
21387 upon the next fontification round."
21388 (let (b l)
21389 (when (or (eq t buffer-invisibility-spec)
21390 (assq 'org-link buffer-invisibility-spec))
21391 (while (setq b (text-property-any 0 (length s)
21392 'invisible 'org-link s))
21393 (setq s (concat (substring s 0 b)
21394 (substring s (or (next-single-property-change
21395 b 'invisible s) (length s)))))))
21396 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21397 (setq s (concat (substring s 0 b)
21398 (substring s (or (next-single-property-change
21399 b 'org-cwidth s) (length s))))))
21400 (setq l (string-width s) b -1)
21401 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21402 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21405 (defun org-shorten-string (s maxlength)
21406 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21407 If the string is shorter or has length MAXLENGTH, just return the
21408 original string. If it is longer, the functions finds a space in the
21409 string, breaks this string off at that locations and adds three dots
21410 as ellipsis. Including the ellipsis, the string will not be longer
21411 than MAXLENGTH. If finding a good breaking point in the string does
21412 not work, the string is just chopped off in the middle of a word
21413 if necessary."
21414 (if (<= (length s) maxlength)
21416 (let* ((n (max (- maxlength 4) 1))
21417 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21418 (if (string-match re s)
21419 (concat (match-string 1 s) "...")
21420 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21422 (defun org-get-indentation (&optional line)
21423 "Get the indentation of the current line, interpreting tabs.
21424 When LINE is given, assume it represents a line and compute its indentation."
21425 (if line
21426 (if (string-match "^ *" (org-remove-tabs line))
21427 (match-end 0))
21428 (save-excursion
21429 (beginning-of-line 1)
21430 (skip-chars-forward " \t")
21431 (current-column))))
21433 (defun org-get-string-indentation (s)
21434 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21435 (let ((n -1) (i 0) (w tab-width) c)
21436 (catch 'exit
21437 (while (< (setq n (1+ n)) (length s))
21438 (setq c (aref s n))
21439 (cond ((= c ?\ ) (setq i (1+ i)))
21440 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21441 (t (throw 'exit t)))))
21444 (defun org-remove-tabs (s &optional width)
21445 "Replace tabulators in S with spaces.
21446 Assumes that s is a single line, starting in column 0."
21447 (setq width (or width tab-width))
21448 (while (string-match "\t" s)
21449 (setq s (replace-match
21450 (make-string
21451 (- (* width (/ (+ (match-beginning 0) width) width))
21452 (match-beginning 0)) ?\ )
21453 t t s)))
21456 (defun org-fix-indentation (line ind)
21457 "Fix indentation in LINE.
21458 IND is a cons cell with target and minimum indentation.
21459 If the current indentation in LINE is smaller than the minimum,
21460 leave it alone. If it is larger than ind, set it to the target."
21461 (let* ((l (org-remove-tabs line))
21462 (i (org-get-indentation l))
21463 (i1 (car ind)) (i2 (cdr ind)))
21464 (if (>= i i2) (setq l (substring line i2)))
21465 (if (> i1 0)
21466 (concat (make-string i1 ?\ ) l)
21467 l)))
21469 (defun org-remove-indentation (code &optional n)
21470 "Remove the maximum common indentation from the lines in CODE.
21471 N may optionally be the number of spaces to remove."
21472 (with-temp-buffer
21473 (insert code)
21474 (org-do-remove-indentation n)
21475 (buffer-string)))
21477 (defun org-do-remove-indentation (&optional n)
21478 "Remove the maximum common indentation from the buffer."
21479 (untabify (point-min) (point-max))
21480 (let ((min 10000) re)
21481 (if n
21482 (setq min n)
21483 (goto-char (point-min))
21484 (while (re-search-forward "^ *[^ \n]" nil t)
21485 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21486 (unless (or (= min 0) (= min 10000))
21487 (setq re (format "^ \\{%d\\}" min))
21488 (goto-char (point-min))
21489 (while (re-search-forward re nil t)
21490 (replace-match "")
21491 (end-of-line 1))
21492 min)))
21494 (defun org-fill-template (template alist)
21495 "Find each %key of ALIST in TEMPLATE and replace it."
21496 (let ((case-fold-search nil)
21497 entry key value)
21498 (setq alist (sort (copy-sequence alist)
21499 (lambda (a b) (< (length (car a)) (length (car b))))))
21500 (while (setq entry (pop alist))
21501 (setq template
21502 (replace-regexp-in-string
21503 (concat "%" (regexp-quote (car entry)))
21504 (or (cdr entry) "") template t t)))
21505 template))
21507 (defun org-base-buffer (buffer)
21508 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21509 (if (not buffer)
21510 buffer
21511 (or (buffer-base-buffer buffer)
21512 buffer)))
21514 (defun org-trim (s)
21515 "Remove whitespace at beginning and end of string."
21516 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
21517 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
21520 (defun org-wrap (string &optional width lines)
21521 "Wrap string to either a number of lines, or a width in characters.
21522 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21523 that costs. If there is a word longer than WIDTH, the text is actually
21524 wrapped to the length of that word.
21525 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21526 many lines, whatever width that takes.
21527 The return value is a list of lines, without newlines at the end."
21528 (let* ((words (org-split-string string "[ \t\n]+"))
21529 (maxword (apply 'max (mapcar 'org-string-width words)))
21530 w ll)
21531 (cond (width
21532 (org-do-wrap words (max maxword width)))
21533 (lines
21534 (setq w maxword)
21535 (setq ll (org-do-wrap words maxword))
21536 (if (<= (length ll) lines)
21538 (setq ll words)
21539 (while (> (length ll) lines)
21540 (setq w (1+ w))
21541 (setq ll (org-do-wrap words w)))
21542 ll))
21543 (t (error "Cannot wrap this")))))
21545 (defun org-do-wrap (words width)
21546 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21547 (let (lines line)
21548 (while words
21549 (setq line (pop words))
21550 (while (and words (< (+ (length line) (length (car words))) width))
21551 (setq line (concat line " " (pop words))))
21552 (setq lines (push line lines)))
21553 (nreverse lines)))
21555 (defun org-split-string (string &optional separators)
21556 "Splits STRING into substrings at SEPARATORS.
21557 No empty strings are returned if there are matches at the beginning
21558 and end of string."
21559 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21560 (start 0)
21561 notfirst
21562 (list nil))
21563 (while (and (string-match rexp string
21564 (if (and notfirst
21565 (= start (match-beginning 0))
21566 (< start (length string)))
21567 (1+ start) start))
21568 (< (match-beginning 0) (length string)))
21569 (setq notfirst t)
21570 (or (eq (match-beginning 0) 0)
21571 (and (eq (match-beginning 0) (match-end 0))
21572 (eq (match-beginning 0) start))
21573 (setq list
21574 (cons (substring string start (match-beginning 0))
21575 list)))
21576 (setq start (match-end 0)))
21577 (or (eq start (length string))
21578 (setq list
21579 (cons (substring string start)
21580 list)))
21581 (nreverse list)))
21583 (defun org-quote-vert (s)
21584 "Replace \"|\" with \"\\vert\"."
21585 (while (string-match "|" s)
21586 (setq s (replace-match "\\vert" t t s)))
21589 (defun org-uuidgen-p (s)
21590 "Is S an ID created by UUIDGEN?"
21591 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21593 (defun org-in-src-block-p (&optional inside)
21594 "Whether point is in a code source block.
21595 When INSIDE is non-nil, don't consider we are within a src block
21596 when point is at #+BEGIN_SRC or #+END_SRC."
21597 (let ((case-fold-search t) ov)
21598 (or (and (setq ov (overlays-at (point)))
21599 (memq 'org-block-background
21600 (overlay-properties (car ov))))
21601 (and (not inside)
21602 (save-match-data
21603 (save-excursion
21604 (beginning-of-line)
21605 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21607 (defun org-context ()
21608 "Return a list of contexts of the current cursor position.
21609 If several contexts apply, all are returned.
21610 Each context entry is a list with a symbol naming the context, and
21611 two positions indicating start and end of the context. Possible
21612 contexts are:
21614 :headline anywhere in a headline
21615 :headline-stars on the leading stars in a headline
21616 :todo-keyword on a TODO keyword (including DONE) in a headline
21617 :tags on the TAGS in a headline
21618 :priority on the priority cookie in a headline
21619 :item on the first line of a plain list item
21620 :item-bullet on the bullet/number of a plain list item
21621 :checkbox on the checkbox in a plain list item
21622 :table in an org-mode table
21623 :table-special on a special filed in a table
21624 :table-table in a table.el table
21625 :clocktable in a clocktable
21626 :src-block in a source block
21627 :link on a hyperlink
21628 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21629 :target on a <<target>>
21630 :radio-target on a <<<radio-target>>>
21631 :latex-fragment on a LaTeX fragment
21632 :latex-preview on a LaTeX fragment with overlaid preview image
21634 This function expects the position to be visible because it uses font-lock
21635 faces as a help to recognize the following contexts: :table-special, :link,
21636 and :keyword."
21637 (let* ((f (get-text-property (point) 'face))
21638 (faces (if (listp f) f (list f)))
21639 (case-fold-search t)
21640 (p (point)) clist o)
21641 ;; First the large context
21642 (cond
21643 ((org-at-heading-p t)
21644 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21645 (when (progn
21646 (beginning-of-line 1)
21647 (looking-at org-todo-line-tags-regexp))
21648 (push (org-point-in-group p 1 :headline-stars) clist)
21649 (push (org-point-in-group p 2 :todo-keyword) clist)
21650 (push (org-point-in-group p 4 :tags) clist))
21651 (goto-char p)
21652 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21653 (if (looking-at "\\[#[A-Z0-9]\\]")
21654 (push (org-point-in-group p 0 :priority) clist)))
21656 ((org-at-item-p)
21657 (push (org-point-in-group p 2 :item-bullet) clist)
21658 (push (list :item (point-at-bol)
21659 (save-excursion (org-end-of-item) (point)))
21660 clist)
21661 (and (org-at-item-checkbox-p)
21662 (push (org-point-in-group p 0 :checkbox) clist)))
21664 ((org-at-table-p)
21665 (push (list :table (org-table-begin) (org-table-end)) clist)
21666 (if (memq 'org-formula faces)
21667 (push (list :table-special
21668 (previous-single-property-change p 'face)
21669 (next-single-property-change p 'face)) clist)))
21670 ((org-at-table-p 'any)
21671 (push (list :table-table) clist)))
21672 (goto-char p)
21674 (let ((case-fold-search t))
21675 ;; New the "medium" contexts: clocktables, source blocks
21676 (cond ((org-in-clocktable-p)
21677 (push (list :clocktable
21678 (and (or (looking-at "#\\+BEGIN: clocktable")
21679 (search-backward "#+BEGIN: clocktable" nil t))
21680 (match-beginning 0))
21681 (and (re-search-forward "#\\+END:?" nil t)
21682 (match-end 0))) clist))
21683 ((org-in-src-block-p)
21684 (push (list :src-block
21685 (and (or (looking-at "#\\+BEGIN_SRC")
21686 (search-backward "#+BEGIN_SRC" nil t))
21687 (match-beginning 0))
21688 (and (search-forward "#+END_SRC" nil t)
21689 (match-beginning 0))) clist))))
21690 (goto-char p)
21692 ;; Now the small context
21693 (cond
21694 ((org-at-timestamp-p)
21695 (push (org-point-in-group p 0 :timestamp) clist))
21696 ((memq 'org-link faces)
21697 (push (list :link
21698 (previous-single-property-change p 'face)
21699 (next-single-property-change p 'face)) clist))
21700 ((memq 'org-special-keyword faces)
21701 (push (list :keyword
21702 (previous-single-property-change p 'face)
21703 (next-single-property-change p 'face)) clist))
21704 ((org-at-target-p)
21705 (push (org-point-in-group p 0 :target) clist)
21706 (goto-char (1- (match-beginning 0)))
21707 (if (looking-at org-radio-target-regexp)
21708 (push (org-point-in-group p 0 :radio-target) clist))
21709 (goto-char p))
21710 ((setq o (car (delq nil
21711 (mapcar
21712 (lambda (x)
21713 (if (memq x org-latex-fragment-image-overlays) x))
21714 (overlays-at (point))))))
21715 (push (list :latex-fragment
21716 (overlay-start o) (overlay-end o)) clist)
21717 (push (list :latex-preview
21718 (overlay-start o) (overlay-end o)) clist))
21719 ((org-inside-LaTeX-fragment-p)
21720 ;; FIXME: positions wrong.
21721 (push (list :latex-fragment (point) (point)) clist)))
21723 (setq clist (nreverse (delq nil clist)))
21724 clist))
21726 ;; FIXME: Compare with at-regexp-p Do we need both?
21727 (defun org-in-regexp (re &optional nlines visually)
21728 "Check if point is inside a match of regexp.
21729 Normally only the current line is checked, but you can include NLINES extra
21730 lines both before and after point into the search.
21731 If VISUALLY is set, require that the cursor is not after the match but
21732 really on, so that the block visually is on the match."
21733 (catch 'exit
21734 (let ((pos (point))
21735 (eol (point-at-eol (+ 1 (or nlines 0))))
21736 (inc (if visually 1 0)))
21737 (save-excursion
21738 (beginning-of-line (- 1 (or nlines 0)))
21739 (while (re-search-forward re eol t)
21740 (if (and (<= (match-beginning 0) pos)
21741 (>= (+ inc (match-end 0)) pos))
21742 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21744 (defun org-at-regexp-p (regexp)
21745 "Is point inside a match of REGEXP in the current line?"
21746 (catch 'exit
21747 (save-excursion
21748 (let ((pos (point)) (end (point-at-eol)))
21749 (beginning-of-line 1)
21750 (while (re-search-forward regexp end t)
21751 (if (and (<= (match-beginning 0) pos)
21752 (>= (match-end 0) pos))
21753 (throw 'exit t)))
21754 nil))))
21756 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21757 "Non-nil when point is between matches of START-RE and END-RE.
21759 Also return a non-nil value when point is on one of the matches.
21761 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21762 buffer positions. Default values are the positions of headlines
21763 surrounding the point.
21765 The functions returns a cons cell whose car (resp. cdr) is the
21766 position before START-RE (resp. after END-RE)."
21767 (save-match-data
21768 (let ((pos (point))
21769 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21770 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21771 beg end)
21772 (save-excursion
21773 ;; Point is on a block when on START-RE or if START-RE can be
21774 ;; found before it...
21775 (and (or (org-at-regexp-p start-re)
21776 (re-search-backward start-re limit-up t))
21777 (setq beg (match-beginning 0))
21778 ;; ... and END-RE after it...
21779 (goto-char (match-end 0))
21780 (re-search-forward end-re limit-down t)
21781 (> (setq end (match-end 0)) pos)
21782 ;; ... without another START-RE in-between.
21783 (goto-char (match-beginning 0))
21784 (not (re-search-backward start-re (1+ beg) t))
21785 ;; Return value.
21786 (cons beg end))))))
21788 (defun org-in-block-p (names)
21789 "Non-nil when point belongs to a block whose name belongs to NAMES.
21791 NAMES is a list of strings containing names of blocks.
21793 Return first block name matched, or nil. Beware that in case of
21794 nested blocks, the returned name may not belong to the closest
21795 block from point."
21796 (save-match-data
21797 (catch 'exit
21798 (let ((case-fold-search t)
21799 (lim-up (save-excursion (outline-previous-heading)))
21800 (lim-down (save-excursion (outline-next-heading))))
21801 (mapc (lambda (name)
21802 (let ((n (regexp-quote name)))
21803 (when (org-between-regexps-p
21804 (concat "^[ \t]*#\\+begin_" n)
21805 (concat "^[ \t]*#\\+end_" n)
21806 lim-up lim-down)
21807 (throw 'exit n))))
21808 names))
21809 nil)))
21811 (defun org-in-drawer-p ()
21812 "Non-nil if point is within a drawer.
21813 If point is within a drawer, return it, as parsed data."
21814 (let ((element (save-match-data (org-element-at-point))))
21815 (while (and element (not (memq (org-element-type element)
21816 '(drawer property-drawer))))
21817 (setq element (org-element-property :parent element)))
21818 element))
21820 (defun org-occur-in-agenda-files (regexp &optional nlines)
21821 "Call `multi-occur' with buffers for all agenda files."
21822 (interactive "sOrg-files matching: \np")
21823 (let* ((files (org-agenda-files))
21824 (tnames (mapcar 'file-truename files))
21825 (extra org-agenda-text-search-extra-files)
21827 (when (eq (car extra) 'agenda-archives)
21828 (setq extra (cdr extra))
21829 (setq files (org-add-archive-files files)))
21830 (while (setq f (pop extra))
21831 (unless (member (file-truename f) tnames)
21832 (add-to-list 'files f 'append)
21833 (add-to-list 'tnames (file-truename f) 'append)))
21834 (multi-occur
21835 (mapcar (lambda (x)
21836 (with-current-buffer
21837 (or (get-file-buffer x) (find-file-noselect x))
21838 (widen)
21839 (current-buffer)))
21840 files)
21841 regexp)))
21843 (if (boundp 'occur-mode-find-occurrence-hook)
21844 ;; Emacs 23
21845 (add-hook 'occur-mode-find-occurrence-hook
21846 (lambda ()
21847 (when (derived-mode-p 'org-mode)
21848 (org-reveal))))
21849 ;; Emacs 22
21850 (defadvice occur-mode-goto-occurrence
21851 (after org-occur-reveal activate)
21852 (and (derived-mode-p 'org-mode) (org-reveal)))
21853 (defadvice occur-mode-goto-occurrence-other-window
21854 (after org-occur-reveal activate)
21855 (and (derived-mode-p 'org-mode) (org-reveal)))
21856 (defadvice occur-mode-display-occurrence
21857 (after org-occur-reveal activate)
21858 (when (derived-mode-p 'org-mode)
21859 (let ((pos (occur-mode-find-occurrence)))
21860 (with-current-buffer (marker-buffer pos)
21861 (save-excursion
21862 (goto-char pos)
21863 (org-reveal)))))))
21865 (defun org-occur-link-in-agenda-files ()
21866 "Create a link and search for it in the agendas.
21867 The link is not stored in `org-stored-links', it is just created
21868 for the search purpose."
21869 (interactive)
21870 (let ((link (condition-case nil
21871 (org-store-link nil)
21872 (error "Unable to create a link to here"))))
21873 (org-occur-in-agenda-files (regexp-quote link))))
21875 (defun org-reverse-string (string)
21876 "Return the reverse of STRING."
21877 (apply 'string (reverse (string-to-list string))))
21879 (defun org-uniquify-alist (alist)
21880 "Merge elements of ALIST with the same key.
21882 For example, in this alist:
21884 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
21885 => '((a 1 3) (b 2))
21887 merge (a 1) and (a 3) into (a 1 3).
21889 The function returns the new ALIST."
21890 (let (rtn)
21891 (mapc
21892 (lambda (e)
21893 (let (n)
21894 (if (not (assoc (car e) rtn))
21895 (push e rtn)
21896 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
21897 (setq rtn (assq-delete-all (car e) rtn))
21898 (push n rtn))))
21899 alist)
21900 rtn))
21902 (defun org-delete-all (elts list)
21903 "Remove all elements in ELTS from LIST."
21904 (while elts
21905 (setq list (delete (pop elts) list)))
21906 list)
21908 (defun org-count (cl-item cl-seq)
21909 "Count the number of occurrences of ITEM in SEQ.
21910 Taken from `count' in cl-seq.el with all keyword arguments removed."
21911 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21912 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21913 (while (< cl-start cl-end)
21914 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21915 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21916 (setq cl-start (1+ cl-start)))
21917 cl-count))
21919 (defun org-remove-if (predicate seq)
21920 "Remove everything from SEQ that fulfills PREDICATE."
21921 (let (res e)
21922 (while seq
21923 (setq e (pop seq))
21924 (if (not (funcall predicate e)) (push e res)))
21925 (nreverse res)))
21927 (defun org-remove-if-not (predicate seq)
21928 "Remove everything from SEQ that does not fulfill PREDICATE."
21929 (let (res e)
21930 (while seq
21931 (setq e (pop seq))
21932 (if (funcall predicate e) (push e res)))
21933 (nreverse res)))
21935 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21936 "Reduce two-argument FUNCTION across SEQ.
21937 Taken from `reduce' in cl-seq.el with all keyword arguments but
21938 \":initial-value\" removed."
21939 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21940 (cadr (memq :initial-value cl-keys)))
21941 (cl-seq (pop cl-seq))
21942 (t (funcall cl-func)))))
21943 (while cl-seq
21944 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21945 cl-accum))
21947 (defun org-every (pred seq)
21948 "Return true if PREDICATE is true of every element of SEQ.
21949 Adapted from `every' in cl.el."
21950 (catch 'org-every
21951 (mapc (lambda (e) (unless (funcall pred e) (throw 'org-every nil))) seq)
21954 (defun org-some (pred seq)
21955 "Return true if PREDICATE is true of any element of SEQ.
21956 Adapted from `some' in cl.el."
21957 (catch 'org-some
21958 (mapc (lambda (e) (when (funcall pred e) (throw 'org-some t))) seq)
21959 nil))
21961 (defun org-back-over-empty-lines ()
21962 "Move backwards over whitespace, to the beginning of the first empty line.
21963 Returns the number of empty lines passed."
21964 (let ((pos (point)))
21965 (if (cdr (assoc 'heading org-blank-before-new-entry))
21966 (skip-chars-backward " \t\n\r")
21967 (unless (eobp)
21968 (forward-line -1)))
21969 (beginning-of-line 2)
21970 (goto-char (min (point) pos))
21971 (count-lines (point) pos)))
21973 (defun org-skip-whitespace ()
21974 (skip-chars-forward " \t\n\r"))
21976 (defun org-point-in-group (point group &optional context)
21977 "Check if POINT is in match-group GROUP.
21978 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21979 match. If the match group does not exist or point is not inside it,
21980 return nil."
21981 (and (match-beginning group)
21982 (>= point (match-beginning group))
21983 (<= point (match-end group))
21984 (if context
21985 (list context (match-beginning group) (match-end group))
21986 t)))
21988 (defun org-switch-to-buffer-other-window (&rest args)
21989 "Switch to buffer in a second window on the current frame.
21990 In particular, do not allow pop-up frames.
21991 Returns the newly created buffer."
21992 (org-no-popups
21993 (apply 'switch-to-buffer-other-window args)))
21995 (defun org-combine-plists (&rest plists)
21996 "Create a single property list from all plists in PLISTS.
21997 The process starts by copying the first list, and then setting properties
21998 from the other lists. Settings in the last list are the most significant
21999 ones and overrule settings in the other lists."
22000 (let ((rtn (copy-sequence (pop plists)))
22001 p v ls)
22002 (while plists
22003 (setq ls (pop plists))
22004 (while ls
22005 (setq p (pop ls) v (pop ls))
22006 (setq rtn (plist-put rtn p v))))
22007 rtn))
22009 (defun org-replace-escapes (string table)
22010 "Replace %-escapes in STRING with values in TABLE.
22011 TABLE is an association list with keys like \"%a\" and string values.
22012 The sequences in STRING may contain normal field width and padding information,
22013 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22014 so values can contain further %-escapes if they are define later in TABLE."
22015 (let ((tbl (copy-alist table))
22016 (case-fold-search nil)
22017 (pchg 0)
22018 e re rpl)
22019 (while (setq e (pop tbl))
22020 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22021 (when (and (cdr e) (string-match re (cdr e)))
22022 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22023 (safe "SREF"))
22024 (add-text-properties 0 3 (list 'sref sref) safe)
22025 (setcdr e (replace-match safe t t (cdr e)))))
22026 (while (string-match re string)
22027 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22028 (cdr e)))
22029 (setq string (replace-match rpl t t string))))
22030 (while (setq pchg (next-property-change pchg string))
22031 (let ((sref (get-text-property pchg 'sref string)))
22032 (when (and sref (string-match "SREF" string pchg))
22033 (setq string (replace-match sref t t string)))))
22034 string))
22036 (defun org-sublist (list start end)
22037 "Return a section of LIST, from START to END.
22038 Counting starts at 1."
22039 (let (rtn (c start))
22040 (setq list (nthcdr (1- start) list))
22041 (while (and list (<= c end))
22042 (push (pop list) rtn)
22043 (setq c (1+ c)))
22044 (nreverse rtn)))
22046 (defun org-find-base-buffer-visiting (file)
22047 "Like `find-buffer-visiting' but always return the base buffer and
22048 not an indirect buffer."
22049 (let ((buf (or (get-file-buffer file)
22050 (find-buffer-visiting file))))
22051 (if buf
22052 (or (buffer-base-buffer buf) buf)
22053 nil)))
22055 (defun org-image-file-name-regexp (&optional extensions)
22056 "Return regexp matching the file names of images.
22057 If EXTENSIONS is given, only match these."
22058 (if (and (not extensions) (fboundp 'image-file-name-regexp))
22059 (image-file-name-regexp)
22060 (let ((image-file-name-extensions
22061 (or extensions
22062 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
22063 "xbm" "xpm" "pbm" "pgm" "ppm"))))
22064 (concat "\\."
22065 (regexp-opt (nconc (mapcar 'upcase
22066 image-file-name-extensions)
22067 image-file-name-extensions)
22069 "\\'"))))
22071 (defun org-file-image-p (file &optional extensions)
22072 "Return non-nil if FILE is an image."
22073 (save-match-data
22074 (string-match (org-image-file-name-regexp extensions) file)))
22076 (defun org-get-cursor-date (&optional with-time)
22077 "Return the date at cursor in as a time.
22078 This works in the calendar and in the agenda, anywhere else it just
22079 returns the current time.
22080 If WITH-TIME is non-nil, returns the time of the event at point (in
22081 the agenda) or the current time of the day."
22082 (let (date day defd tp tm hod mod)
22083 (when with-time
22084 (setq tp (get-text-property (point) 'time))
22085 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22086 (setq hod (string-to-number (match-string 1 tp))
22087 mod (string-to-number (match-string 2 tp))))
22088 (or tp (setq hod (nth 2 (decode-time (current-time)))
22089 mod (nth 1 (decode-time (current-time))))))
22090 (cond
22091 ((eq major-mode 'calendar-mode)
22092 (setq date (calendar-cursor-to-date)
22093 defd (encode-time 0 (or mod 0) (or hod 0)
22094 (nth 1 date) (nth 0 date) (nth 2 date))))
22095 ((eq major-mode 'org-agenda-mode)
22096 (setq day (get-text-property (point) 'day))
22097 (if day
22098 (setq date (calendar-gregorian-from-absolute day)
22099 defd (encode-time 0 (or mod 0) (or hod 0)
22100 (nth 1 date) (nth 0 date) (nth 2 date))))))
22101 (or defd (current-time))))
22103 (defun org-mark-subtree (&optional up)
22104 "Mark the current subtree.
22105 This puts point at the start of the current subtree, and mark at
22106 the end. If a numeric prefix UP is given, move up into the
22107 hierarchy of headlines by UP levels before marking the subtree."
22108 (interactive "P")
22109 (org-with-limited-levels
22110 (cond ((org-at-heading-p) (beginning-of-line))
22111 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22112 (t (outline-previous-visible-heading 1))))
22113 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
22114 (if (org-called-interactively-p 'any)
22115 (call-interactively 'org-mark-element)
22116 (org-mark-element)))
22119 ;;; Indentation
22121 (defun org-indent-line ()
22122 "Indent line depending on context."
22123 (interactive)
22124 (let* ((pos (point))
22125 (itemp (org-at-item-p))
22126 (case-fold-search t)
22127 (org-drawer-regexp (or org-drawer-regexp "\000"))
22128 (inline-task-p (and (featurep 'org-inlinetask)
22129 (org-inlinetask-in-task-p)))
22130 (inline-re (and inline-task-p
22131 (org-inlinetask-outline-regexp)))
22132 column)
22133 (if (and orgstruct-is-++ (eq pos (point)))
22134 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
22135 (indent-according-to-mode))
22136 (beginning-of-line 1)
22137 (cond
22138 ;; Headings
22139 ((looking-at org-outline-regexp) (setq column 0))
22140 ;; Footnote definition
22141 ((looking-at org-footnote-definition-re) (setq column 0))
22142 ;; Literal examples
22143 ((looking-at "[ \t]*:\\( \\|$\\)")
22144 (setq column (org-get-indentation))) ; do nothing
22145 ;; Lists
22146 ((ignore-errors (goto-char (org-in-item-p)))
22147 (setq column (if itemp
22148 (org-get-indentation)
22149 (org-list-item-body-column (point))))
22150 (goto-char pos))
22151 ;; Drawers
22152 ((and (looking-at "[ \t]*:END:")
22153 (save-excursion (re-search-backward org-drawer-regexp nil t)))
22154 (save-excursion
22155 (goto-char (1- (match-beginning 1)))
22156 (setq column (current-column))))
22157 ;; Special blocks
22158 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
22159 (save-excursion
22160 (re-search-backward
22161 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
22162 (setq column (org-get-indentation (match-string 0))))
22163 ((and (not (looking-at "[ \t]*#\\+begin_"))
22164 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
22165 (save-excursion
22166 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
22167 (setq column
22168 (cond ((equal (downcase (match-string 1)) "src")
22169 ;; src blocks: let `org-edit-src-exit' handle them
22170 (org-get-indentation))
22171 ((equal (downcase (match-string 1)) "example")
22172 (max (org-get-indentation)
22173 (org-get-indentation (match-string 0))))
22175 (org-get-indentation (match-string 0))))))
22176 ;; This line has nothing special, look at the previous relevant
22177 ;; line to compute indentation
22179 (beginning-of-line 0)
22180 (while (and (not (bobp))
22181 (not (looking-at org-table-line-regexp))
22182 (not (looking-at org-drawer-regexp))
22183 ;; When point started in an inline task, do not move
22184 ;; above task starting line.
22185 (not (and inline-task-p (looking-at inline-re)))
22186 ;; Skip drawers, blocks, empty lines, verbatim,
22187 ;; comments, tables, footnotes definitions, lists,
22188 ;; inline tasks.
22189 (or (and (looking-at "[ \t]*:END:")
22190 (re-search-backward org-drawer-regexp nil t))
22191 (and (looking-at "[ \t]*#\\+end_")
22192 (re-search-backward "[ \t]*#\\+begin_"nil t))
22193 (looking-at "[ \t]*[\n:#|]")
22194 (looking-at org-footnote-definition-re)
22195 (and (not inline-task-p)
22196 (featurep 'org-inlinetask)
22197 (org-inlinetask-in-task-p)
22198 (or (org-inlinetask-goto-beginning) t))))
22199 (beginning-of-line 0))
22200 (cond
22201 ;; There was a list item above.
22202 ((ignore-errors (goto-char (org-in-item-p)))
22203 (goto-char (org-list-get-top-point (org-list-struct)))
22204 (setq column (org-get-indentation)))
22205 ;; There was an heading above.
22206 ((looking-at "\\*+[ \t]+")
22207 (if (not org-adapt-indentation)
22208 (setq column 0)
22209 (goto-char (match-end 0))
22210 (setq column (current-column))))
22211 ;; A drawer had started and is unfinished
22212 ((looking-at org-drawer-regexp)
22213 (goto-char (1- (match-beginning 1)))
22214 (setq column (current-column)))
22215 ;; Else, nothing noticeable found: get indentation and go on.
22216 (t (setq column (org-get-indentation))))))
22217 ;; Now apply indentation and move cursor accordingly
22218 (goto-char pos)
22219 (if (<= (current-column) (current-indentation))
22220 (org-indent-line-to column)
22221 (save-excursion (org-indent-line-to column)))
22222 ;; Special polishing for properties, see `org-property-format'
22223 (setq column (current-column))
22224 (beginning-of-line 1)
22225 (if (looking-at org-property-re)
22226 (replace-match (concat (match-string 4)
22227 (format org-property-format
22228 (match-string 1) (match-string 3)))
22229 t t))
22230 (org-move-to-column column))))
22232 (defun org-indent-drawer ()
22233 "Indent the drawer at point."
22234 (interactive)
22235 (let ((p (point))
22236 (e (and (save-excursion (re-search-forward ":END:" nil t))
22237 (match-end 0)))
22238 (folded
22239 (save-excursion
22240 (end-of-line)
22241 (when (overlays-at (point))
22242 (member 'invisible (overlay-properties
22243 (car (overlays-at (point)))))))))
22244 (when folded (org-cycle))
22245 (indent-for-tab-command)
22246 (while (and (move-beginning-of-line 2) (< (point) e))
22247 (indent-for-tab-command))
22248 (goto-char p)
22249 (when folded (org-cycle)))
22250 (message "Drawer at point indented"))
22252 (defun org-indent-block ()
22253 "Indent the block at point."
22254 (interactive)
22255 (let ((p (point))
22256 (case-fold-search t)
22257 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
22258 (match-end 0)))
22259 (folded
22260 (save-excursion
22261 (end-of-line)
22262 (when (overlays-at (point))
22263 (member 'invisible (overlay-properties
22264 (car (overlays-at (point)))))))))
22265 (when folded (org-cycle))
22266 (indent-for-tab-command)
22267 (while (and (move-beginning-of-line 2) (< (point) e))
22268 (indent-for-tab-command))
22269 (goto-char p)
22270 (when folded (org-cycle)))
22271 (message "Block at point indented"))
22273 (defun org-indent-region (start end)
22274 "Indent region."
22275 (interactive "r")
22276 (save-excursion
22277 (let ((line-end (org-current-line end)))
22278 (goto-char start)
22279 (while (< (org-current-line) line-end)
22280 (cond ((org-in-src-block-p t) (org-src-native-tab-command-maybe))
22281 (t (call-interactively 'org-indent-line)))
22282 (move-beginning-of-line 2)))))
22285 ;;; Filling
22287 ;; We use our own fill-paragraph and auto-fill functions.
22289 ;; `org-fill-paragraph' relies on adaptive filling and context
22290 ;; checking. Appropriate `fill-prefix' is computed with
22291 ;; `org-adaptive-fill-function'.
22293 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22294 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22295 ;; `org-adaptive-fill-function' value. Internally,
22296 ;; `org-comment-line-break-function' breaks the line.
22298 ;; `org-setup-filling' installs filling and auto-filling related
22299 ;; variables during `org-mode' initialization.
22301 (defvar org-element-paragraph-separate) ; org-element.el
22302 (defun org-setup-filling ()
22303 (require 'org-element)
22304 ;; Prevent auto-fill from inserting unwanted new items.
22305 (when (boundp 'fill-nobreak-predicate)
22306 (org-set-local
22307 'fill-nobreak-predicate
22308 (org-uniquify
22309 (append fill-nobreak-predicate
22310 '(org-fill-line-break-nobreak-p
22311 org-fill-paragraph-with-timestamp-nobreak-p)))))
22312 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22313 (org-set-local 'paragraph-start paragraph-ending)
22314 (org-set-local 'paragraph-separate paragraph-ending))
22315 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22316 (org-set-local 'auto-fill-inhibit-regexp nil)
22317 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22318 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22319 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22321 (defun org-fill-line-break-nobreak-p ()
22322 "Non-nil when a new line at point would create an Org line break."
22323 (save-excursion
22324 (skip-chars-backward "[ \t]")
22325 (skip-chars-backward "\\\\")
22326 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22328 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22329 "Non-nil when a new line at point would split a timestamp."
22330 (and (org-at-timestamp-p t)
22331 (not (looking-at org-ts-regexp-both))))
22333 (declare-function message-in-body-p "message" ())
22334 (defvar orgtbl-line-start-regexp) ; From org-table.el
22335 (defun org-adaptive-fill-function ()
22336 "Compute a fill prefix for the current line.
22337 Return fill prefix, as a string, or nil if current line isn't
22338 meant to be filled. For convenience, if `adaptive-fill-regexp'
22339 matches in paragraphs or comments, use it."
22340 (catch 'exit
22341 (when (derived-mode-p 'message-mode)
22342 (save-excursion
22343 (beginning-of-line)
22344 (cond ((or (not (message-in-body-p))
22345 (looking-at orgtbl-line-start-regexp))
22346 (throw 'exit nil))
22347 ((looking-at message-cite-prefix-regexp)
22348 (throw 'exit (match-string-no-properties 0)))
22349 ((looking-at org-outline-regexp)
22350 (throw 'exit (make-string (length (match-string 0)) ? ))))))
22351 (org-with-wide-buffer
22352 (let* ((p (line-beginning-position))
22353 (element (save-excursion
22354 (beginning-of-line)
22355 (or (ignore-errors (org-element-at-point))
22356 (user-error "An element cannot be parsed line %d"
22357 (line-number-at-pos (point))))))
22358 (type (org-element-type element))
22359 (post-affiliated (org-element-property :post-affiliated element)))
22360 (unless (and post-affiliated (< p post-affiliated))
22361 (case type
22362 (comment
22363 (save-excursion
22364 (beginning-of-line)
22365 (looking-at "[ \t]*")
22366 (concat (match-string 0) "# ")))
22367 (footnote-definition "")
22368 ((item plain-list)
22369 (make-string (org-list-item-body-column
22370 (or post-affiliated
22371 (org-element-property :begin element)))
22372 ? ))
22373 (paragraph
22374 ;; Fill prefix is usually the same as the current line,
22375 ;; unless the paragraph is at the beginning of an item.
22376 (let ((parent (org-element-property :parent element)))
22377 (save-excursion
22378 (beginning-of-line)
22379 (cond ((eq (org-element-type parent) 'item)
22380 (make-string (org-list-item-body-column
22381 (org-element-property :begin parent))
22382 ? ))
22383 ((and adaptive-fill-regexp
22384 ;; Locally disable
22385 ;; `adaptive-fill-function' to let
22386 ;; `fill-context-prefix' handle
22387 ;; `adaptive-fill-regexp' variable.
22388 (let (adaptive-fill-function)
22389 (fill-context-prefix
22390 post-affiliated
22391 (org-element-property :end element)))))
22392 ((looking-at "[ \t]+") (match-string 0))
22393 (t "")))))
22394 (comment-block
22395 ;; Only fill contents if P is within block boundaries.
22396 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22397 (forward-line)
22398 (point)))
22399 (cend (save-excursion
22400 (goto-char (org-element-property :end element))
22401 (skip-chars-backward " \r\t\n")
22402 (line-beginning-position))))
22403 (when (and (>= p cbeg) (< p cend))
22404 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22405 (match-string 0)
22406 ""))))))))))
22408 (declare-function message-goto-body "message" ())
22409 (defvar message-cite-prefix-regexp) ; From message.el
22410 (defun org-fill-paragraph (&optional justify)
22411 "Fill element at point, when applicable.
22413 This function only applies to comment blocks, comments, example
22414 blocks and paragraphs. Also, as a special case, re-align table
22415 when point is at one.
22417 If JUSTIFY is non-nil (interactively, with prefix argument),
22418 justify as well. If `sentence-end-double-space' is non-nil, then
22419 period followed by one space does not end a sentence, so don't
22420 break a line there. The variable `fill-column' controls the
22421 width for filling.
22423 For convenience, when point is at a plain list, an item or
22424 a footnote definition, try to fill the first paragraph within."
22425 (interactive)
22426 (if (and (derived-mode-p 'message-mode)
22427 (or (not (message-in-body-p))
22428 (save-excursion (move-beginning-of-line 1)
22429 (looking-at message-cite-prefix-regexp))))
22430 ;; First ensure filling is correct in message-mode.
22431 (let ((fill-paragraph-function
22432 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22433 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22434 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22435 (paragraph-separate
22436 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22437 (fill-paragraph nil))
22438 (with-syntax-table org-mode-transpose-word-syntax-table
22439 ;; Move to end of line in order to get the first paragraph
22440 ;; within a plain list or a footnote definition.
22441 (let ((element (save-excursion
22442 (end-of-line)
22443 (or (ignore-errors (org-element-at-point))
22444 (user-error "An element cannot be parsed line %d"
22445 (line-number-at-pos (point)))))))
22446 ;; First check if point is in a blank line at the beginning of
22447 ;; the buffer. In that case, ignore filling.
22448 (case (org-element-type element)
22449 ;; Use major mode filling function is src blocks.
22450 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22451 ;; Align Org tables, leave table.el tables as-is.
22452 (table-row (org-table-align) t)
22453 (table
22454 (when (eq (org-element-property :type element) 'org)
22455 (save-excursion
22456 (goto-char (org-element-property :post-affiliated element))
22457 (org-table-align)))
22459 (paragraph
22460 ;; Paragraphs may contain `line-break' type objects.
22461 (let ((beg (max (point-min)
22462 (org-element-property :contents-begin element)))
22463 (end (min (point-max)
22464 (org-element-property :contents-end element))))
22465 ;; Do nothing if point is at an affiliated keyword.
22466 (if (< (line-end-position) beg) t
22467 (when (derived-mode-p 'message-mode)
22468 ;; In `message-mode', do not fill following citation
22469 ;; in current paragraph nor text before message body.
22470 (let ((body-start (save-excursion (message-goto-body))))
22471 (when body-start (setq beg (max body-start beg))))
22472 (when (save-excursion
22473 (re-search-forward
22474 (concat "^" message-cite-prefix-regexp) end t))
22475 (setq end (match-beginning 0))))
22476 ;; Fill paragraph, taking line breaks into account.
22477 ;; For that, slice the paragraph using line breaks as
22478 ;; separators, and fill the parts in reverse order to
22479 ;; avoid messing with markers.
22480 (save-excursion
22481 (goto-char end)
22482 (mapc
22483 (lambda (pos)
22484 (fill-region-as-paragraph pos (point) justify)
22485 (goto-char pos))
22486 ;; Find the list of ending positions for line breaks
22487 ;; in the current paragraph. Add paragraph
22488 ;; beginning to include first slice.
22489 (nreverse
22490 (cons beg
22491 (org-element-map
22492 (org-element--parse-objects
22493 beg end nil (org-element-restriction 'paragraph))
22494 'line-break
22495 (lambda (lb) (org-element-property :end lb)))))))
22496 t)))
22497 ;; Contents of `comment-block' type elements should be
22498 ;; filled as plain text, but only if point is within block
22499 ;; markers.
22500 (comment-block
22501 (let* ((case-fold-search t)
22502 (beg (save-excursion
22503 (goto-char (org-element-property :begin element))
22504 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22505 (forward-line)
22506 (point)))
22507 (end (save-excursion
22508 (goto-char (org-element-property :end element))
22509 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22510 (line-beginning-position))))
22511 (if (or (< (point) beg) (> (point) end)) t
22512 (fill-region-as-paragraph
22513 (save-excursion (end-of-line)
22514 (re-search-backward "^[ \t]*$" beg 'move)
22515 (line-beginning-position))
22516 (save-excursion (beginning-of-line)
22517 (re-search-forward "^[ \t]*$" end 'move)
22518 (line-beginning-position))
22519 justify))))
22520 ;; Fill comments.
22521 (comment
22522 (let ((begin (org-element-property :post-affiliated element))
22523 (end (org-element-property :end element)))
22524 (when (and (>= (point) begin) (<= (point) end))
22525 (let ((begin (save-excursion
22526 (end-of-line)
22527 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22528 (progn (forward-line) (point))
22529 begin)))
22530 (end (save-excursion
22531 (end-of-line)
22532 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22533 (1- (line-beginning-position))
22534 (skip-chars-backward " \r\t\n")
22535 (line-end-position)))))
22536 ;; Do not fill comments when at a blank line.
22537 (when (> end begin)
22538 (let ((fill-prefix
22539 (save-excursion
22540 (beginning-of-line)
22541 (looking-at "[ \t]*#")
22542 (let ((comment-prefix (match-string 0)))
22543 (goto-char (match-end 0))
22544 (if (looking-at adaptive-fill-regexp)
22545 (concat comment-prefix (match-string 0))
22546 (concat comment-prefix " "))))))
22547 (save-excursion
22548 (fill-region-as-paragraph begin end justify))))))
22550 ;; Ignore every other element.
22551 (otherwise t))))))
22553 (defun org-auto-fill-function ()
22554 "Auto-fill function."
22555 ;; Check if auto-filling is meaningful.
22556 (let ((fc (current-fill-column)))
22557 (when (and fc (> (current-column) fc))
22558 (let* ((fill-prefix (org-adaptive-fill-function))
22559 ;; Enforce empty fill prefix, if required. Otherwise, it
22560 ;; will be computed again.
22561 (adaptive-fill-mode (not (equal fill-prefix ""))))
22562 (when fill-prefix (do-auto-fill))))))
22564 (defun org-comment-line-break-function (&optional soft)
22565 "Break line at point and indent, continuing comment if within one.
22566 The inserted newline is marked hard if variable
22567 `use-hard-newlines' is true, unless optional argument SOFT is
22568 non-nil."
22569 (if soft (insert-and-inherit ?\n) (newline 1))
22570 (save-excursion (forward-char -1) (delete-horizontal-space))
22571 (delete-horizontal-space)
22572 (indent-to-left-margin)
22573 (insert-before-markers-and-inherit fill-prefix))
22576 ;;; Comments
22578 ;; Org comments syntax is quite complex. It requires the entire line
22579 ;; to be just a comment. Also, even with the right syntax at the
22580 ;; beginning of line, some some elements (i.e. verse-block or
22581 ;; example-block) don't accept comments. Usual Emacs comment commands
22582 ;; cannot cope with those requirements. Therefore, Org replaces them.
22584 ;; Org still relies on `comment-dwim', but cannot trust
22585 ;; `comment-only-p'. So, `comment-region-function' and
22586 ;; `uncomment-region-function' both point
22587 ;; to`org-comment-or-uncomment-region'. Eventually,
22588 ;; `org-insert-comment' takes care of insertion of comments at the
22589 ;; beginning of line.
22591 ;; `org-setup-comments-handling' install comments related variables
22592 ;; during `org-mode' initialization.
22594 (defun org-setup-comments-handling ()
22595 (interactive)
22596 (org-set-local 'comment-use-syntax nil)
22597 (org-set-local 'comment-start "# ")
22598 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22599 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22600 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22601 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22603 (defun org-insert-comment ()
22604 "Insert an empty comment above current line.
22605 If the line is empty, insert comment at its beginning. When
22606 point is within a source block, comment according to the related
22607 major mode."
22608 (if (let ((element (org-element-at-point)))
22609 (and (eq (org-element-type element) 'src-block)
22610 (< (save-excursion
22611 (goto-char (org-element-property :post-affiliated element))
22612 (line-end-position))
22613 (point))
22614 (> (save-excursion
22615 (goto-char (org-element-property :end element))
22616 (skip-chars-backward " \r\t\n")
22617 (line-beginning-position))
22618 (point))))
22619 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim))
22620 (beginning-of-line)
22621 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
22622 (open-line 1))
22623 (org-indent-line)
22624 (insert "# ")))
22626 (defvar comment-empty-lines) ; From newcomment.el.
22627 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22628 "Comment or uncomment each non-blank line in the region.
22629 Uncomment each non-blank line between BEG and END if it only
22630 contains commented lines. Otherwise, comment them. If region is
22631 strictly within a source block, use appropriate comment syntax."
22632 (if (let ((element (org-element-at-point)))
22633 (and (eq (org-element-type element) 'src-block)
22634 (< (save-excursion
22635 (goto-char (org-element-property :post-affiliated element))
22636 (line-end-position))
22637 beg)
22638 (>= (save-excursion
22639 (goto-char (org-element-property :end element))
22640 (skip-chars-backward " \r\t\n")
22641 (line-beginning-position))
22642 end)))
22643 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim))
22644 (save-restriction
22645 ;; Restrict region
22646 (narrow-to-region (save-excursion (goto-char beg)
22647 (skip-chars-forward " \r\t\n" end)
22648 (line-beginning-position))
22649 (save-excursion (goto-char end)
22650 (skip-chars-backward " \r\t\n" beg)
22651 (line-end-position)))
22652 (let ((uncommentp
22653 ;; UNCOMMENTP is non-nil when every non blank line between
22654 ;; BEG and END is a comment.
22655 (save-excursion
22656 (goto-char (point-min))
22657 (while (and (not (eobp))
22658 (let ((element (org-element-at-point)))
22659 (and (eq (org-element-type element) 'comment)
22660 (goto-char (min (point-max)
22661 (org-element-property
22662 :end element)))))))
22663 (eobp))))
22664 (if uncommentp
22665 ;; Only blank lines and comments in region: uncomment it.
22666 (save-excursion
22667 (goto-char (point-min))
22668 (while (not (eobp))
22669 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22670 (replace-match "" nil nil nil 1))
22671 (forward-line)))
22672 ;; Comment each line in region.
22673 (let ((min-indent (point-max)))
22674 ;; First find the minimum indentation across all lines.
22675 (save-excursion
22676 (goto-char (point-min))
22677 (while (and (not (eobp)) (not (zerop min-indent)))
22678 (unless (looking-at "[ \t]*$")
22679 (setq min-indent (min min-indent (current-indentation))))
22680 (forward-line)))
22681 ;; Then loop over all lines.
22682 (save-excursion
22683 (goto-char (point-min))
22684 (while (not (eobp))
22685 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22686 ;; Don't get fooled by invisible text (e.g. link path)
22687 ;; when moving to column MIN-INDENT.
22688 (let ((buffer-invisibility-spec nil))
22689 (org-move-to-column min-indent t))
22690 (insert comment-start))
22691 (forward-line)))))))))
22693 (defun org-comment-dwim (arg)
22694 (interactive "*P")
22695 "Call `comment-dwim' within a source edit buffer if needed."
22696 (if (org-in-src-block-p)
22697 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim))
22698 (call-interactively #'comment-dwim)))
22701 ;;; Planning
22703 ;; This section contains tools to operate on timestamp objects, as
22704 ;; returned by, e.g. `org-element-context'.
22706 (defun org-timestamp-has-time-p (timestamp)
22707 "Non-nil when TIMESTAMP has a time specified."
22708 (org-element-property :hour-start timestamp))
22710 (defun org-timestamp-format (timestamp format &optional end utc)
22711 "Format a TIMESTAMP element into a string.
22713 FORMAT is a format specifier to be passed to
22714 `format-time-string'.
22716 When optional argument END is non-nil, use end of date-range or
22717 time-range, if possible.
22719 When optional argument UTC is non-nil, time will be expressed as
22720 Universal Time."
22721 (format-time-string
22722 format
22723 (apply 'encode-time
22724 (cons 0
22725 (mapcar
22726 (lambda (prop) (or (org-element-property prop timestamp) 0))
22727 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22728 '(:minute-start :hour-start :day-start :month-start
22729 :year-start)))))
22730 utc))
22732 (defun org-timestamp-split-range (timestamp &optional end)
22733 "Extract a timestamp object from a date or time range.
22735 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22736 the end of the range. Otherwise, extract its start.
22738 Return a new timestamp object sharing the same parent as
22739 TIMESTAMP."
22740 (let ((type (org-element-property :type timestamp)))
22741 (if (memq type '(active inactive diary)) timestamp
22742 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22743 ;; Set new type.
22744 (org-element-put-property
22745 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22746 ;; Copy start properties over end properties if END is
22747 ;; non-nil. Otherwise, copy end properties over `start' ones.
22748 (let ((p-alist '((:minute-start . :minute-end)
22749 (:hour-start . :hour-end)
22750 (:day-start . :day-end)
22751 (:month-start . :month-end)
22752 (:year-start . :year-end))))
22753 (dolist (p-cell p-alist)
22754 (org-element-put-property
22755 split-ts
22756 (funcall (if end 'car 'cdr) p-cell)
22757 (org-element-property
22758 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22759 ;; Eventually refresh `:raw-value'.
22760 (org-element-put-property split-ts :raw-value nil)
22761 (org-element-put-property
22762 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22764 (defun org-timestamp-translate (timestamp &optional boundary)
22765 "Apply `org-translate-time' on a TIMESTAMP object.
22766 When optional argument BOUNDARY is non-nil, it is either the
22767 symbol `start' or `end'. In this case, only translate the
22768 starting or ending part of TIMESTAMP if it is a date or time
22769 range. Otherwise, translate both parts."
22770 (if (and (not boundary)
22771 (memq (org-element-property :type timestamp)
22772 '(active-range inactive-range)))
22773 (concat
22774 (org-translate-time
22775 (org-element-property :raw-value
22776 (org-timestamp-split-range timestamp)))
22777 "--"
22778 (org-translate-time
22779 (org-element-property :raw-value
22780 (org-timestamp-split-range timestamp t))))
22781 (org-translate-time
22782 (org-element-property
22783 :raw-value
22784 (if (not boundary) timestamp
22785 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22789 ;;; Other stuff.
22791 (defun org-toggle-fixed-width-section (arg)
22792 "Toggle the fixed-width export.
22793 If there is no active region, the QUOTE keyword at the current headline is
22794 inserted or removed. When present, it causes the text between this headline
22795 and the next to be exported as fixed-width text, and unmodified.
22796 If there is an active region, this command adds or removes a colon as the
22797 first character of this line. If the first character of a line is a colon,
22798 this line is also exported in fixed-width font."
22799 (interactive "P")
22800 (let* ((cc 0)
22801 (regionp (org-region-active-p))
22802 (beg (if regionp (region-beginning) (point)))
22803 (end (if regionp (region-end)))
22804 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22805 (case-fold-search nil)
22806 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22807 off)
22808 (if regionp
22809 (save-excursion
22810 (goto-char beg)
22811 (setq cc (current-column))
22812 (beginning-of-line 1)
22813 (setq off (looking-at re))
22814 (while (> nlines 0)
22815 (setq nlines (1- nlines))
22816 (beginning-of-line 1)
22817 (cond
22818 (arg
22819 (org-move-to-column cc t)
22820 (insert ": \n")
22821 (forward-line -1))
22822 ((and off (looking-at re))
22823 (replace-match "" t t nil 1))
22824 ((not off) (org-move-to-column cc t) (insert ": ")))
22825 (forward-line 1)))
22826 (save-excursion
22827 (org-back-to-heading)
22828 (cond
22829 ((looking-at (format org-heading-keyword-regexp-format
22830 org-quote-string))
22831 (goto-char (match-end 1))
22832 (looking-at (concat " +" org-quote-string))
22833 (replace-match "" t t)
22834 (when (eolp) (insert " ")))
22835 ((looking-at org-outline-regexp)
22836 (goto-char (match-end 0))
22837 (insert org-quote-string " ")))))))
22839 (defun org-reftex-citation ()
22840 "Use reftex-citation to insert a citation into the buffer.
22841 This looks for a line like
22843 #+BIBLIOGRAPHY: foo plain option:-d
22845 and derives from it that foo.bib is the bibliography file relevant
22846 for this document. It then installs the necessary environment for RefTeX
22847 to work in this buffer and calls `reftex-citation' to insert a citation
22848 into the buffer.
22850 Export of such citations to both LaTeX and HTML is handled by the contributed
22851 package ox-bibtex by Taru Karttunen."
22852 (interactive)
22853 (let ((reftex-docstruct-symbol 'rds)
22854 (reftex-cite-format "\\cite{%l}")
22855 rds bib)
22856 (save-excursion
22857 (save-restriction
22858 (widen)
22859 (let ((case-fold-search t)
22860 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22861 (if (not (save-excursion
22862 (or (re-search-forward re nil t)
22863 (re-search-backward re nil t))))
22864 (error "No bibliography defined in file")
22865 (setq bib (concat (match-string 1) ".bib")
22866 rds (list (list 'bib bib)))))))
22867 (call-interactively 'reftex-citation)))
22869 ;;;; Functions extending outline functionality
22871 (defun org-beginning-of-line (&optional arg)
22872 "Go to the beginning of the current line. If that is invisible, continue
22873 to a visible line beginning. This makes the function of C-a more intuitive.
22874 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22875 first attempt, and only move to after the tags when the cursor is already
22876 beyond the end of the headline."
22877 (interactive "P")
22878 (let ((pos (point))
22879 (special (if (consp org-special-ctrl-a/e)
22880 (car org-special-ctrl-a/e)
22881 org-special-ctrl-a/e))
22882 deactivate-mark refpos)
22883 (if (org-bound-and-true-p visual-line-mode)
22884 (beginning-of-visual-line 1)
22885 (beginning-of-line 1))
22886 (if (and arg (fboundp 'move-beginning-of-line))
22887 (call-interactively 'move-beginning-of-line)
22888 (if (bobp)
22890 (backward-char 1)
22891 (if (org-truely-invisible-p)
22892 (while (and (not (bobp)) (org-truely-invisible-p))
22893 (backward-char 1)
22894 (beginning-of-line 1))
22895 (forward-char 1))))
22896 (when special
22897 (cond
22898 ((and (looking-at org-complex-heading-regexp)
22899 (= (char-after (match-end 1)) ?\ ))
22900 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22901 (point-at-eol)))
22902 (goto-char
22903 (if (eq special t)
22904 (cond ((> pos refpos) refpos)
22905 ((= pos (point)) refpos)
22906 (t (point)))
22907 (cond ((> pos (point)) (point))
22908 ((not (eq last-command this-command)) (point))
22909 (t refpos)))))
22910 ((org-at-item-p)
22911 ;; Being at an item and not looking at an the item means point
22912 ;; was previously moved to beginning of a visual line, which
22913 ;; doesn't contain the item. Therefore, do nothing special,
22914 ;; just stay here.
22915 (when (looking-at org-list-full-item-re)
22916 ;; Set special position at first white space character after
22917 ;; bullet, and check-box, if any.
22918 (let ((after-bullet
22919 (let ((box (match-end 3)))
22920 (if (not box) (match-end 1)
22921 (let ((after (char-after box)))
22922 (if (and after (= after ? )) (1+ box) box))))))
22923 ;; Special case: Move point to special position when
22924 ;; currently after it or at beginning of line.
22925 (if (eq special t)
22926 (when (or (> pos after-bullet) (= (point) pos))
22927 (goto-char after-bullet))
22928 ;; Reversed case: Move point to special position when
22929 ;; point was already at beginning of line and command is
22930 ;; repeated.
22931 (when (and (= (point) pos) (eq last-command this-command))
22932 (goto-char after-bullet))))))))
22933 (org-no-warnings
22934 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22935 (setq disable-point-adjustment
22936 (or (not (invisible-p (point)))
22937 (not (invisible-p (max (point-min) (1- (point))))))))
22939 (defun org-end-of-line (&optional arg)
22940 "Go to the end of the line.
22941 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22942 tags on the first attempt, and only move to after the tags when
22943 the cursor is already beyond the end of the headline."
22944 (interactive "P")
22945 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22946 org-special-ctrl-a/e))
22947 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22948 'end-of-visual-line)
22949 ((fboundp 'move-end-of-line) 'move-end-of-line)
22950 (t 'end-of-line)))
22951 deactivate-mark)
22952 (if (or (not special) arg) (call-interactively move-fun)
22953 (let* ((element (save-excursion (beginning-of-line)
22954 (org-element-at-point)))
22955 (type (org-element-type element)))
22956 (cond
22957 ((memq type '(headline inlinetask))
22958 (let ((pos (point)))
22959 (beginning-of-line 1)
22960 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22961 (if (eq special t)
22962 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22963 (goto-char (match-beginning 1))
22964 (goto-char (match-end 0)))
22965 (if (or (< pos (match-end 0))
22966 (not (eq this-command last-command)))
22967 (goto-char (match-end 0))
22968 (goto-char (match-beginning 1))))
22969 (call-interactively move-fun))))
22970 ((outline-invisible-p (line-end-position))
22971 ;; If element is hidden, `move-end-of-line' would put point
22972 ;; after it. Use `end-of-line' to stay on current line.
22973 (call-interactively 'end-of-line))
22974 (t (call-interactively move-fun)))))
22975 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22976 (setq disable-point-adjustment
22977 (or (not (invisible-p (point)))
22978 (not (invisible-p (max (point-min) (1- (point))))))))
22980 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22981 (define-key org-mode-map "\C-e" 'org-end-of-line)
22983 (defun org-backward-sentence (&optional arg)
22984 "Go to beginning of sentence, or beginning of table field.
22985 This will call `backward-sentence' or `org-table-beginning-of-field',
22986 depending on context."
22987 (interactive "P")
22988 (cond
22989 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22990 (t (call-interactively 'backward-sentence))))
22992 (defun org-forward-sentence (&optional arg)
22993 "Go to end of sentence, or end of table field.
22994 This will call `forward-sentence' or `org-table-end-of-field',
22995 depending on context."
22996 (interactive "P")
22997 (cond
22998 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22999 (t (call-interactively 'forward-sentence))))
23001 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23002 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23004 (defun org-kill-line (&optional arg)
23005 "Kill line, to tags or end of line."
23006 (interactive "P")
23007 (cond
23008 ((or (not org-special-ctrl-k)
23009 (bolp)
23010 (not (org-at-heading-p)))
23011 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23012 org-ctrl-k-protect-subtree)
23013 (if (or (eq org-ctrl-k-protect-subtree 'error)
23014 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
23015 (user-error "C-k aborted as it would kill a hidden subtree")))
23016 (call-interactively
23017 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23018 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
23019 (kill-region (point) (match-beginning 1))
23020 (org-set-tags nil t))
23021 (t (kill-region (point) (point-at-eol)))))
23023 (define-key org-mode-map "\C-k" 'org-kill-line)
23025 (defun org-yank (&optional arg)
23026 "Yank. If the kill is a subtree, treat it specially.
23027 This command will look at the current kill and check if is a single
23028 subtree, or a series of subtrees[1]. If it passes the test, and if the
23029 cursor is at the beginning of a line or after the stars of a currently
23030 empty headline, then the yank is handled specially. How exactly depends
23031 on the value of the following variables, both set by default.
23033 org-yank-folded-subtrees
23034 When set, the subtree(s) will be folded after insertion, but only
23035 if doing so would now swallow text after the yanked text.
23037 org-yank-adjusted-subtrees
23038 When set, the subtree will be promoted or demoted in order to
23039 fit into the local outline tree structure, which means that the level
23040 will be adjusted so that it becomes the smaller one of the two
23041 *visible* surrounding headings.
23043 Any prefix to this command will cause `yank' to be called directly with
23044 no special treatment. In particular, a simple \\[universal-argument] prefix \
23045 will just
23046 plainly yank the text as it is.
23048 \[1] The test checks if the first non-white line is a heading
23049 and if there are no other headings with fewer stars."
23050 (interactive "P")
23051 (org-yank-generic 'yank arg))
23053 (defun org-yank-generic (command arg)
23054 "Perform some yank-like command.
23056 This function implements the behavior described in the `org-yank'
23057 documentation. However, it has been generalized to work for any
23058 interactive command with similar behavior."
23060 ;; pretend to be command COMMAND
23061 (setq this-command command)
23063 (if arg
23064 (call-interactively command)
23066 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23067 (and (org-kill-is-subtree-p)
23068 (or (bolp)
23069 (and (looking-at "[ \t]*$")
23070 (string-match
23071 "\\`\\*+\\'"
23072 (buffer-substring (point-at-bol) (point)))))))
23073 swallowp)
23074 (cond
23075 ((and subtreep org-yank-folded-subtrees)
23076 (let ((beg (point))
23077 end)
23078 (if (and subtreep org-yank-adjusted-subtrees)
23079 (org-paste-subtree nil nil 'for-yank)
23080 (call-interactively command))
23082 (setq end (point))
23083 (goto-char beg)
23084 (when (and (bolp) subtreep
23085 (not (setq swallowp
23086 (org-yank-folding-would-swallow-text beg end))))
23087 (org-with-limited-levels
23088 (or (looking-at org-outline-regexp)
23089 (re-search-forward org-outline-regexp-bol end t))
23090 (while (and (< (point) end) (looking-at org-outline-regexp))
23091 (hide-subtree)
23092 (org-cycle-show-empty-lines 'folded)
23093 (condition-case nil
23094 (outline-forward-same-level 1)
23095 (error (goto-char end))))))
23096 (when swallowp
23097 (message
23098 "Inserted text not folded because that would swallow text"))
23100 (goto-char end)
23101 (skip-chars-forward " \t\n\r")
23102 (beginning-of-line 1)
23103 (push-mark beg 'nomsg)))
23104 ((and subtreep org-yank-adjusted-subtrees)
23105 (let ((beg (point-at-bol)))
23106 (org-paste-subtree nil nil 'for-yank)
23107 (push-mark beg 'nomsg)))
23109 (call-interactively command))))))
23111 (defun org-yank-folding-would-swallow-text (beg end)
23112 "Would hide-subtree at BEG swallow any text after END?"
23113 (let (level)
23114 (org-with-limited-levels
23115 (save-excursion
23116 (goto-char beg)
23117 (when (or (looking-at org-outline-regexp)
23118 (re-search-forward org-outline-regexp-bol end t))
23119 (setq level (org-outline-level)))
23120 (goto-char end)
23121 (skip-chars-forward " \t\r\n\v\f")
23122 (if (or (eobp)
23123 (and (bolp) (looking-at org-outline-regexp)
23124 (<= (org-outline-level) level)))
23125 nil ; Nothing would be swallowed
23126 t))))) ; something would swallow
23128 (define-key org-mode-map "\C-y" 'org-yank)
23130 (defun org-truely-invisible-p ()
23131 "Check if point is at a character currently not visible.
23132 This version does not only check the character property, but also
23133 `visible-mode'."
23134 ;; Early versions of noutline don't have `outline-invisible-p'.
23135 (if (org-bound-and-true-p visible-mode)
23137 (outline-invisible-p)))
23139 (defun org-invisible-p2 ()
23140 "Check if point is at a character currently not visible."
23141 (save-excursion
23142 (if (and (eolp) (not (bobp))) (backward-char 1))
23143 ;; Early versions of noutline don't have `outline-invisible-p'.
23144 (outline-invisible-p)))
23146 (defun org-back-to-heading (&optional invisible-ok)
23147 "Call `outline-back-to-heading', but provide a better error message."
23148 (condition-case nil
23149 (outline-back-to-heading invisible-ok)
23150 (error (error "Before first headline at position %d in buffer %s"
23151 (point) (current-buffer)))))
23153 (defun org-before-first-heading-p ()
23154 "Before first heading?"
23155 (save-excursion
23156 (end-of-line)
23157 (null (re-search-backward org-outline-regexp-bol nil t))))
23159 (defun org-at-heading-p (&optional ignored)
23160 (outline-on-heading-p t))
23161 ;; Compatibility alias with Org versions < 7.8.03
23162 (defalias 'org-on-heading-p 'org-at-heading-p)
23164 (defun org-at-comment-p nil
23165 "Is cursor in a line starting with a # character?"
23166 (save-excursion
23167 (beginning-of-line)
23168 (looking-at "^#")))
23170 (defun org-at-drawer-p nil
23171 "Is cursor at a drawer keyword?"
23172 (save-excursion
23173 (move-beginning-of-line 1)
23174 (looking-at org-drawer-regexp)))
23176 (defun org-at-block-p nil
23177 "Is cursor at a block keyword?"
23178 (save-excursion
23179 (move-beginning-of-line 1)
23180 (looking-at org-block-regexp)))
23182 (defun org-point-at-end-of-empty-headline ()
23183 "If point is at the end of an empty headline, return t, else nil.
23184 If the heading only contains a TODO keyword, it is still still considered
23185 empty."
23186 (and (looking-at "[ \t]*$")
23187 (when org-todo-line-regexp
23188 (save-excursion
23189 (beginning-of-line 1)
23190 (let ((case-fold-search nil))
23191 (looking-at org-todo-line-regexp)
23192 (string= (match-string 3) ""))))))
23194 (defun org-at-heading-or-item-p ()
23195 (or (org-at-heading-p) (org-at-item-p)))
23197 (defun org-at-target-p ()
23198 (or (org-in-regexp org-radio-target-regexp)
23199 (org-in-regexp org-target-regexp)))
23200 ;; Compatibility alias with Org versions < 7.8.03
23201 (defalias 'org-on-target-p 'org-at-target-p)
23203 (defun org-up-heading-all (arg)
23204 "Move to the heading line of which the present line is a subheading.
23205 This function considers both visible and invisible heading lines.
23206 With argument, move up ARG levels."
23207 (if (fboundp 'outline-up-heading-all)
23208 (outline-up-heading-all arg) ; emacs 21 version of outline.el
23209 (outline-up-heading arg t))) ; emacs 22 version of outline.el
23211 (defun org-up-heading-safe ()
23212 "Move to the heading line of which the present line is a subheading.
23213 This version will not throw an error. It will return the level of the
23214 headline found, or nil if no higher level is found.
23216 Also, this function will be a lot faster than `outline-up-heading',
23217 because it relies on stars being the outline starters. This can really
23218 make a significant difference in outlines with very many siblings."
23219 (let (start-level re)
23220 (org-back-to-heading t)
23221 (setq start-level (funcall outline-level))
23222 (if (equal start-level 1)
23224 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
23225 (if (re-search-backward re nil t)
23226 (funcall outline-level)))))
23228 (defun org-first-sibling-p ()
23229 "Is this heading the first child of its parents?"
23230 (interactive)
23231 (let ((re org-outline-regexp-bol)
23232 level l)
23233 (unless (org-at-heading-p t)
23234 (user-error "Not at a heading"))
23235 (setq level (funcall outline-level))
23236 (save-excursion
23237 (if (not (re-search-backward re nil t))
23239 (setq l (funcall outline-level))
23240 (< l level)))))
23242 (defun org-goto-sibling (&optional previous)
23243 "Goto the next sibling, even if it is invisible.
23244 When PREVIOUS is set, go to the previous sibling instead. Returns t
23245 when a sibling was found. When none is found, return nil and don't
23246 move point."
23247 (let ((fun (if previous 're-search-backward 're-search-forward))
23248 (pos (point))
23249 (re org-outline-regexp-bol)
23250 level l)
23251 (when (condition-case nil (org-back-to-heading t) (error nil))
23252 (setq level (funcall outline-level))
23253 (catch 'exit
23254 (or previous (forward-char 1))
23255 (while (funcall fun re nil t)
23256 (setq l (funcall outline-level))
23257 (when (< l level) (goto-char pos) (throw 'exit nil))
23258 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23259 (goto-char pos)
23260 nil))))
23262 (defun org-show-siblings ()
23263 "Show all siblings of the current headline."
23264 (save-excursion
23265 (while (org-goto-sibling) (org-flag-heading nil)))
23266 (save-excursion
23267 (while (org-goto-sibling 'previous)
23268 (org-flag-heading nil))))
23270 (defun org-goto-first-child ()
23271 "Goto the first child, even if it is invisible.
23272 Return t when a child was found. Otherwise don't move point and
23273 return nil."
23274 (let (level (pos (point)) (re org-outline-regexp-bol))
23275 (when (condition-case nil (org-back-to-heading t) (error nil))
23276 (setq level (outline-level))
23277 (forward-char 1)
23278 (if (and (re-search-forward re nil t) (> (outline-level) level))
23279 (progn (goto-char (match-beginning 0)) t)
23280 (goto-char pos) nil))))
23282 (defun org-show-hidden-entry ()
23283 "Show an entry where even the heading is hidden."
23284 (save-excursion
23285 (org-show-entry)))
23287 (defun org-flag-heading (flag &optional entry)
23288 "Flag the current heading. FLAG non-nil means make invisible.
23289 When ENTRY is non-nil, show the entire entry."
23290 (save-excursion
23291 (org-back-to-heading t)
23292 ;; Check if we should show the entire entry
23293 (if entry
23294 (progn
23295 (org-show-entry)
23296 (save-excursion
23297 (and (outline-next-heading)
23298 (org-flag-heading nil))))
23299 (outline-flag-region (max (point-min) (1- (point)))
23300 (save-excursion (outline-end-of-heading) (point))
23301 flag))))
23303 (defun org-get-next-sibling ()
23304 "Move to next heading of the same level, and return point.
23305 If there is no such heading, return nil.
23306 This is like outline-next-sibling, but invisible headings are ok."
23307 (let ((level (funcall outline-level)))
23308 (outline-next-heading)
23309 (while (and (not (eobp)) (> (funcall outline-level) level))
23310 (outline-next-heading))
23311 (if (or (eobp) (< (funcall outline-level) level))
23313 (point))))
23315 (defun org-get-last-sibling ()
23316 "Move to previous heading of the same level, and return point.
23317 If there is no such heading, return nil."
23318 (let ((opoint (point))
23319 (level (funcall outline-level)))
23320 (outline-previous-heading)
23321 (when (and (/= (point) opoint) (outline-on-heading-p t))
23322 (while (and (> (funcall outline-level) level)
23323 (not (bobp)))
23324 (outline-previous-heading))
23325 (if (< (funcall outline-level) level)
23327 (point)))))
23329 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23330 "Goto to the end of a subtree."
23331 ;; This contains an exact copy of the original function, but it uses
23332 ;; `org-back-to-heading', to make it work also in invisible
23333 ;; trees. And is uses an invisible-ok argument.
23334 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23335 ;; Furthermore, when used inside Org, finding the end of a large subtree
23336 ;; with many children and grandchildren etc, this can be much faster
23337 ;; than the outline version.
23338 (org-back-to-heading invisible-ok)
23339 (let ((first t)
23340 (level (funcall outline-level)))
23341 (if (and (derived-mode-p 'org-mode) (< level 1000))
23342 ;; A true heading (not a plain list item), in Org-mode
23343 ;; This means we can easily find the end by looking
23344 ;; only for the right number of stars. Using a regexp to do
23345 ;; this is so much faster than using a Lisp loop.
23346 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23347 (forward-char 1)
23348 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23349 ;; something else, do it the slow way
23350 (while (and (not (eobp))
23351 (or first (> (funcall outline-level) level)))
23352 (setq first nil)
23353 (outline-next-heading)))
23354 (unless to-heading
23355 (if (memq (preceding-char) '(?\n ?\^M))
23356 (progn
23357 ;; Go to end of line before heading
23358 (forward-char -1)
23359 (if (memq (preceding-char) '(?\n ?\^M))
23360 ;; leave blank line before heading
23361 (forward-char -1))))))
23362 (point))
23364 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
23365 "Use Org version in org-mode, for dramatic speed-up."
23366 (if (derived-mode-p 'org-mode)
23367 (progn
23368 (org-end-of-subtree nil t)
23369 (unless (eobp) (backward-char 1)))
23370 ad-do-it))
23372 (defun org-end-of-meta-data-and-drawers ()
23373 "Jump to the first text after meta data and drawers in the current entry.
23374 This will move over empty lines, lines with planning time stamps,
23375 clocking lines, and drawers."
23376 (org-back-to-heading t)
23377 (let ((end (save-excursion (outline-next-heading) (point)))
23378 (re (concat "\\(" org-drawer-regexp "\\)"
23379 "\\|" "[ \t]*" org-keyword-time-regexp)))
23380 (forward-line 1)
23381 (while (re-search-forward re end t)
23382 (if (not (match-end 1))
23383 ;; empty or planning line
23384 (forward-line 1)
23385 ;; a drawer, find the end
23386 (re-search-forward "^[ \t]*:END:" end 'move)
23387 (forward-line 1)))
23388 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23389 (point)))
23391 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23392 "Move forward to the ARG'th subheading at same level as this one.
23393 Stop at the first and last subheadings of a superior heading.
23394 Normally this only looks at visible headings, but when INVISIBLE-OK is
23395 non-nil it will also look at invisible ones."
23396 (interactive "p")
23397 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23398 (if (and arg (< arg 0))
23399 (goto-char (point-min))
23400 (outline-next-heading))
23401 (org-at-heading-p)
23402 (let ((level (- (match-end 0) (match-beginning 0) 1))
23403 (f (if (and arg (< arg 0))
23404 're-search-backward
23405 're-search-forward))
23406 (count (if arg (abs arg) 1))
23407 (result (point)))
23408 (while (and (prog1 (> count 0)
23409 (forward-char (if (and arg (< arg 0)) -1 1)))
23410 (funcall f org-outline-regexp-bol nil 'move))
23411 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23412 (cond ((< l level) (setq count 0))
23413 ((and (= l level)
23414 (or invisible-ok
23415 (progn
23416 (goto-char (line-beginning-position))
23417 (not (outline-invisible-p)))))
23418 (setq count (1- count))
23419 (when (eq l level)
23420 (setq result (point)))))))
23421 (goto-char result))
23422 (beginning-of-line 1)))
23424 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23425 "Move backward to the ARG'th subheading at same level as this one.
23426 Stop at the first and last subheadings of a superior heading."
23427 (interactive "p")
23428 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23430 (defun org-next-block (arg &optional backward block-regexp)
23431 "Jump to the next block.
23432 With a prefix argument ARG, jump forward ARG many source blocks.
23433 When BACKWARD is non-nil, jump to the previous block.
23434 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23435 (interactive "p")
23436 (let ((re (or block-regexp org-block-regexp))
23437 (re-search-fn (or (and backward 're-search-backward)
23438 're-search-forward)))
23439 (if (looking-at re) (forward-char 1))
23440 (condition-case nil
23441 (funcall re-search-fn re nil nil arg)
23442 (error (error "No %s code blocks" (if backward "previous" "further" ))))
23443 (goto-char (match-beginning 0)) (org-show-context)))
23445 (defun org-previous-block (arg &optional block-regexp)
23446 "Jump to the previous block.
23447 With a prefix argument ARG, jump backward ARG many source blocks.
23448 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23449 (interactive "p")
23450 (org-next-block arg t block-regexp))
23452 (defun org-forward-paragraph ()
23453 "Move forward to beginning of next paragraph or equivalent.
23455 The function moves point to the beginning of the next visible
23456 structural element, which can be a paragraph, a table, a list
23457 item, etc. It also provides some special moves for convenience:
23459 - On an affiliated keyword, jump to the beginning of the
23460 relative element.
23461 - On an item or a footnote definition, move to the second
23462 element inside, if any.
23463 - On a table or a property drawer, jump after it.
23464 - On a verse or source block, stop after blank lines."
23465 (interactive)
23466 (when (eobp) (user-error "Cannot move further down"))
23467 (let* ((deactivate-mark nil)
23468 (element (org-element-at-point))
23469 (type (org-element-type element))
23470 (post-affiliated (org-element-property :post-affiliated element))
23471 (contents-begin (org-element-property :contents-begin element))
23472 (contents-end (org-element-property :contents-end element))
23473 (end (let ((end (org-element-property :end element)) (parent element))
23474 (while (and (setq parent (org-element-property :parent parent))
23475 (= (org-element-property :contents-end parent) end))
23476 (setq end (org-element-property :end parent)))
23477 end)))
23478 (cond ((not element)
23479 (skip-chars-forward " \r\t\n")
23480 (or (eobp) (beginning-of-line)))
23481 ;; On affiliated keywords, move to element's beginning.
23482 ((and post-affiliated (< (point) post-affiliated))
23483 (goto-char post-affiliated))
23484 ;; At a table row, move to the end of the table. Similarly,
23485 ;; at a node property, move to the end of the property
23486 ;; drawer.
23487 ((memq type '(node-property table-row))
23488 (goto-char (org-element-property
23489 :end (org-element-property :parent element))))
23490 ((memq type '(property-drawer table)) (goto-char end))
23491 ;; Consider blank lines as separators in verse and source
23492 ;; blocks to ease editing.
23493 ((memq type '(src-block verse-block))
23494 (when (eq type 'src-block)
23495 (setq contents-end
23496 (save-excursion (goto-char end)
23497 (skip-chars-backward " \r\t\n")
23498 (line-beginning-position))))
23499 (beginning-of-line)
23500 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23501 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23502 (goto-char end)
23503 (skip-chars-forward " \r\t\n")
23504 (if (= (point) contents-end) (goto-char end)
23505 (beginning-of-line))))
23506 ;; With no contents, just skip element.
23507 ((not contents-begin) (goto-char end))
23508 ;; If contents are invisible, skip the element altogether.
23509 ((outline-invisible-p (line-end-position))
23510 (case type
23511 (headline
23512 (org-with-limited-levels (outline-next-visible-heading 1)))
23513 ;; At a plain list, make sure we move to the next item
23514 ;; instead of skipping the whole list.
23515 (plain-list (forward-char)
23516 (org-forward-paragraph))
23517 (otherwise (goto-char end))))
23518 ((>= (point) contents-end) (goto-char end))
23519 ((>= (point) contents-begin)
23520 ;; This can only happen on paragraphs and plain lists.
23521 (case type
23522 (paragraph (goto-char end))
23523 ;; At a plain list, try to move to second element in
23524 ;; first item, if possible.
23525 (plain-list (end-of-line)
23526 (org-forward-paragraph))))
23527 ;; When contents start on the middle of a line (e.g. in
23528 ;; items and footnote definitions), try to reach first
23529 ;; element starting after current line.
23530 ((> (line-end-position) contents-begin)
23531 (end-of-line)
23532 (org-forward-paragraph))
23533 (t (goto-char contents-begin)))))
23535 (defun org-backward-paragraph ()
23536 "Move backward to start of previous paragraph or equivalent.
23538 The function moves point to the beginning of the current
23539 structural element, which can be a paragraph, a table, a list
23540 item, etc., or to the beginning of the previous visible one if
23541 point is already there. It also provides some special moves for
23542 convenience:
23544 - On an affiliated keyword, jump to the first one.
23545 - On a table or a property drawer, move to its beginning.
23546 - On a verse or source block, stop before blank lines."
23547 (interactive)
23548 (when (bobp) (user-error "Cannot move further up"))
23549 (let* ((deactivate-mark nil)
23550 (element (org-element-at-point))
23551 (type (org-element-type element))
23552 (contents-begin (org-element-property :contents-begin element))
23553 (contents-end (org-element-property :contents-end element))
23554 (post-affiliated (org-element-property :post-affiliated element))
23555 (begin (org-element-property :begin element)))
23556 (cond
23557 ((not element) (goto-char (point-min)))
23558 ((= (point) begin)
23559 (backward-char)
23560 (org-backward-paragraph))
23561 ((and post-affiliated (<= (point) post-affiliated)) (goto-char begin))
23562 ((memq type '(node-property table-row))
23563 (goto-char (org-element-property
23564 :post-affiliated (org-element-property :parent element))))
23565 ((memq type '(property-drawer table)) (goto-char begin))
23566 ((memq type '(src-block verse-block))
23567 (when (eq type 'src-block)
23568 (setq contents-begin
23569 (save-excursion (goto-char begin) (forward-line) (point))))
23570 (if (= (point) contents-begin) (goto-char post-affiliated)
23571 ;; Inside a verse block, see blank lines as paragraph
23572 ;; separators.
23573 (let ((origin (point)))
23574 (skip-chars-backward " \r\t\n" contents-begin)
23575 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
23576 (skip-chars-forward " \r\t\n" origin)
23577 (if (= (point) origin) (goto-char contents-begin)
23578 (beginning-of-line))))))
23579 ((not contents-begin) (goto-char (or post-affiliated begin)))
23580 ((eq type 'paragraph)
23581 (goto-char contents-begin)
23582 ;; When at first paragraph in an item or a footnote definition,
23583 ;; move directly to beginning of line.
23584 (let ((parent-contents
23585 (org-element-property
23586 :contents-begin (org-element-property :parent element))))
23587 (when (and parent-contents (= parent-contents contents-begin))
23588 (beginning-of-line))))
23589 ;; At the end of a greater element, move to the beginning of the
23590 ;; last element within.
23591 ((>= (point) contents-end)
23592 (goto-char (1- contents-end))
23593 (org-backward-paragraph))
23594 (t (goto-char (or post-affiliated begin))))
23595 ;; Ensure we never leave point invisible.
23596 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
23598 (defun org-forward-element ()
23599 "Move forward by one element.
23600 Move to the next element at the same level, when possible."
23601 (interactive)
23602 (cond ((eobp) (user-error "Cannot move further down"))
23603 ((org-with-limited-levels (org-at-heading-p))
23604 (let ((origin (point)))
23605 (goto-char (org-end-of-subtree nil t))
23606 (unless (org-with-limited-levels (org-at-heading-p))
23607 (goto-char origin)
23608 (user-error "Cannot move further down"))))
23610 (let* ((elem (org-element-at-point))
23611 (end (org-element-property :end elem))
23612 (parent (org-element-property :parent elem)))
23613 (cond ((and parent (= (org-element-property :contents-end parent) end))
23614 (goto-char (org-element-property :end parent)))
23615 ((integer-or-marker-p end) (goto-char end))
23616 (t (message "No element at point")))))))
23618 (defun org-backward-element ()
23619 "Move backward by one element.
23620 Move to the previous element at the same level, when possible."
23621 (interactive)
23622 (cond ((bobp) (user-error "Cannot move further up"))
23623 ((org-with-limited-levels (org-at-heading-p))
23624 ;; At a headline, move to the previous one, if any, or stay
23625 ;; here.
23626 (let ((origin (point)))
23627 (org-with-limited-levels (org-backward-heading-same-level 1))
23628 ;; When current headline has no sibling above, move to its
23629 ;; parent.
23630 (when (= (point) origin)
23631 (or (org-with-limited-levels (org-up-heading-safe))
23632 (progn (goto-char origin)
23633 (user-error "Cannot move further up"))))))
23635 (let* ((elem (org-element-at-point))
23636 (beg (org-element-property :begin elem)))
23637 (cond
23638 ;; Move to beginning of current element if point isn't
23639 ;; there already.
23640 ((null beg) (message "No element at point"))
23641 ((/= (point) beg) (goto-char beg))
23642 (t (goto-char beg)
23643 (skip-chars-backward " \r\t\n")
23644 (unless (bobp)
23645 (let ((prev (org-element-at-point)))
23646 (goto-char (org-element-property :begin prev))
23647 (while (and (setq prev (org-element-property :parent prev))
23648 (<= (org-element-property :end prev) beg))
23649 (goto-char (org-element-property :begin prev)))))))))))
23651 (defun org-up-element ()
23652 "Move to upper element."
23653 (interactive)
23654 (if (org-with-limited-levels (org-at-heading-p))
23655 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23656 (let* ((elem (org-element-at-point))
23657 (parent (org-element-property :parent elem)))
23658 (if parent (goto-char (org-element-property :begin parent))
23659 (if (org-with-limited-levels (org-before-first-heading-p))
23660 (user-error "No surrounding element")
23661 (org-with-limited-levels (org-back-to-heading)))))))
23663 (defvar org-element-greater-elements)
23664 (defun org-down-element ()
23665 "Move to inner element."
23666 (interactive)
23667 (let ((element (org-element-at-point)))
23668 (cond
23669 ((memq (org-element-type element) '(plain-list table))
23670 (goto-char (org-element-property :contents-begin element))
23671 (forward-char))
23672 ((memq (org-element-type element) org-element-greater-elements)
23673 ;; If contents are hidden, first disclose them.
23674 (when (outline-invisible-p (line-end-position)) (org-cycle))
23675 (goto-char (or (org-element-property :contents-begin element)
23676 (user-error "No content for this element"))))
23677 (t (user-error "No inner element")))))
23679 (defun org-drag-element-backward ()
23680 "Move backward element at point."
23681 (interactive)
23682 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
23683 (let* ((elem (org-element-at-point))
23684 (prev-elem
23685 (save-excursion
23686 (goto-char (org-element-property :begin elem))
23687 (skip-chars-backward " \r\t\n")
23688 (unless (bobp)
23689 (let* ((beg (org-element-property :begin elem))
23690 (prev (org-element-at-point))
23691 (up prev))
23692 (while (and (setq up (org-element-property :parent up))
23693 (<= (org-element-property :end prev) beg))
23694 (setq prev up))
23695 prev)))))
23696 ;; Error out if no previous element or previous element is
23697 ;; a parent of the current one.
23698 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23699 (user-error "Cannot drag element backward")
23700 (let ((pos (point)))
23701 (org-element-swap-A-B prev-elem elem)
23702 (goto-char (+ (org-element-property :begin prev-elem)
23703 (- pos (org-element-property :begin elem)))))))))
23705 (defun org-drag-element-forward ()
23706 "Move forward element at point."
23707 (interactive)
23708 (let* ((pos (point))
23709 (elem (org-element-at-point)))
23710 (when (= (point-max) (org-element-property :end elem))
23711 (user-error "Cannot drag element forward"))
23712 (goto-char (org-element-property :end elem))
23713 (let ((next-elem (org-element-at-point)))
23714 (when (or (org-element-nested-p elem next-elem)
23715 (and (eq (org-element-type next-elem) 'headline)
23716 (not (eq (org-element-type elem) 'headline))))
23717 (goto-char pos)
23718 (user-error "Cannot drag element forward"))
23719 ;; Compute new position of point: it's shifted by NEXT-ELEM
23720 ;; body's length (without final blanks) and by the length of
23721 ;; blanks between ELEM and NEXT-ELEM.
23722 (let ((size-next (- (save-excursion
23723 (goto-char (org-element-property :end next-elem))
23724 (skip-chars-backward " \r\t\n")
23725 (forward-line)
23726 ;; Small correction if buffer doesn't end
23727 ;; with a newline character.
23728 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23729 (org-element-property :begin next-elem)))
23730 (size-blank (- (org-element-property :end elem)
23731 (save-excursion
23732 (goto-char (org-element-property :end elem))
23733 (skip-chars-backward " \r\t\n")
23734 (forward-line)
23735 (point)))))
23736 (org-element-swap-A-B elem next-elem)
23737 (goto-char (+ pos size-next size-blank))))))
23739 (defun org-drag-line-forward (arg)
23740 "Drag the line at point ARG lines forward."
23741 (interactive "p")
23742 (dotimes (n (abs arg))
23743 (let ((c (current-column)))
23744 (if (< 0 arg)
23745 (progn
23746 (beginning-of-line 2)
23747 (transpose-lines 1)
23748 (beginning-of-line 0))
23749 (transpose-lines 1)
23750 (beginning-of-line -1))
23751 (org-move-to-column c))))
23753 (defun org-drag-line-backward (arg)
23754 "Drag the line at point ARG lines backward."
23755 (interactive "p")
23756 (org-drag-line-forward (- arg)))
23758 (defun org-mark-element ()
23759 "Put point at beginning of this element, mark at end.
23761 Interactively, if this command is repeated or (in Transient Mark
23762 mode) if the mark is active, it marks the next element after the
23763 ones already marked."
23764 (interactive)
23765 (let (deactivate-mark)
23766 (if (and (org-called-interactively-p 'any)
23767 (or (and (eq last-command this-command) (mark t))
23768 (and transient-mark-mode mark-active)))
23769 (set-mark
23770 (save-excursion
23771 (goto-char (mark))
23772 (goto-char (org-element-property :end (org-element-at-point)))))
23773 (let ((element (org-element-at-point)))
23774 (end-of-line)
23775 (push-mark (org-element-property :end element) t t)
23776 (goto-char (org-element-property :begin element))))))
23778 (defun org-narrow-to-element ()
23779 "Narrow buffer to current element."
23780 (interactive)
23781 (let ((elem (org-element-at-point)))
23782 (cond
23783 ((eq (car elem) 'headline)
23784 (narrow-to-region
23785 (org-element-property :begin elem)
23786 (org-element-property :end elem)))
23787 ((memq (car elem) org-element-greater-elements)
23788 (narrow-to-region
23789 (org-element-property :contents-begin elem)
23790 (org-element-property :contents-end elem)))
23792 (narrow-to-region
23793 (org-element-property :begin elem)
23794 (org-element-property :end elem))))))
23796 (defun org-transpose-element ()
23797 "Transpose current and previous elements, keeping blank lines between.
23798 Point is moved after both elements."
23799 (interactive)
23800 (org-skip-whitespace)
23801 (let ((end (org-element-property :end (org-element-at-point))))
23802 (org-drag-element-backward)
23803 (goto-char end)))
23805 (defun org-unindent-buffer ()
23806 "Un-indent the visible part of the buffer.
23807 Relative indentation (between items, inside blocks, etc.) isn't
23808 modified."
23809 (interactive)
23810 (unless (eq major-mode 'org-mode)
23811 (user-error "Cannot un-indent a buffer not in Org mode"))
23812 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23813 unindent-tree ; For byte-compiler.
23814 (unindent-tree
23815 (function
23816 (lambda (contents)
23817 (mapc
23818 (lambda (element)
23819 (if (memq (org-element-type element) '(headline section))
23820 (funcall unindent-tree (org-element-contents element))
23821 (save-excursion
23822 (save-restriction
23823 (narrow-to-region
23824 (org-element-property :begin element)
23825 (org-element-property :end element))
23826 (org-do-remove-indentation)))))
23827 (reverse contents))))))
23828 (funcall unindent-tree (org-element-contents parse-tree))))
23830 (defun org-show-subtree ()
23831 "Show everything after this heading at deeper levels."
23832 (interactive)
23833 (outline-flag-region
23834 (point)
23835 (save-excursion
23836 (org-end-of-subtree t t))
23837 nil))
23839 (defun org-show-entry ()
23840 "Show the body directly following this heading.
23841 Show the heading too, if it is currently invisible."
23842 (interactive)
23843 (save-excursion
23844 (condition-case nil
23845 (progn
23846 (org-back-to-heading t)
23847 (outline-flag-region
23848 (max (point-min) (1- (point)))
23849 (save-excursion
23850 (if (re-search-forward
23851 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23852 (match-beginning 1)
23853 (point-max)))
23854 nil)
23855 (org-cycle-hide-drawers 'children))
23856 (error nil))))
23858 (defun org-make-options-regexp (kwds &optional extra)
23859 "Make a regular expression for keyword lines."
23860 (concat
23861 "^#\\+\\("
23862 (mapconcat 'regexp-quote kwds "\\|")
23863 (if extra (concat "\\|" extra))
23864 "\\):[ \t]*\\(.*\\)"))
23866 ;; Make isearch reveal the necessary context
23867 (defun org-isearch-end ()
23868 "Reveal context after isearch exits."
23869 (when isearch-success ; only if search was successful
23870 (if (featurep 'xemacs)
23871 ;; Under XEmacs, the hook is run in the correct place,
23872 ;; we directly show the context.
23873 (org-show-context 'isearch)
23874 ;; In Emacs the hook runs *before* restoring the overlays.
23875 ;; So we have to use a one-time post-command-hook to do this.
23876 ;; (Emacs 22 has a special variable, see function `org-mode')
23877 (unless (and (boundp 'isearch-mode-end-hook-quit)
23878 isearch-mode-end-hook-quit)
23879 ;; Only when the isearch was not quitted.
23880 (org-add-hook 'post-command-hook 'org-isearch-post-command
23881 'append 'local)))
23882 (org-fix-ellipsis-at-bol)))
23884 (defun org-isearch-post-command ()
23885 "Remove self from hook, and show context."
23886 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23887 (org-show-context 'isearch))
23890 ;;;; Integration with and fixes for other packages
23892 ;;; Imenu support
23894 (defvar org-imenu-markers nil
23895 "All markers currently used by Imenu.")
23896 (make-variable-buffer-local 'org-imenu-markers)
23898 (defun org-imenu-new-marker (&optional pos)
23899 "Return a new marker for use by Imenu, and remember the marker."
23900 (let ((m (make-marker)))
23901 (move-marker m (or pos (point)))
23902 (push m org-imenu-markers)
23905 (defun org-imenu-get-tree ()
23906 "Produce the index for Imenu."
23907 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23908 (setq org-imenu-markers nil)
23909 (let* ((n org-imenu-depth)
23910 (re (concat "^" (org-get-limited-outline-regexp)))
23911 (subs (make-vector (1+ n) nil))
23912 (last-level 0)
23913 m level head0 head)
23914 (save-excursion
23915 (save-restriction
23916 (widen)
23917 (goto-char (point-max))
23918 (while (re-search-backward re nil t)
23919 (setq level (org-reduced-level (funcall outline-level)))
23920 (when (and (<= level n)
23921 (looking-at org-complex-heading-regexp)
23922 (setq head0 (org-match-string-no-properties 4)))
23923 (setq head (org-link-display-format head0)
23924 m (org-imenu-new-marker))
23925 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23926 (if (>= level last-level)
23927 (push (cons head m) (aref subs level))
23928 (push (cons head (aref subs (1+ level))) (aref subs level))
23929 (loop for i from (1+ level) to n do (aset subs i nil)))
23930 (setq last-level level)))))
23931 (aref subs 1)))
23933 (eval-after-load "imenu"
23934 '(progn
23935 (add-hook 'imenu-after-jump-hook
23936 (lambda ()
23937 (if (derived-mode-p 'org-mode)
23938 (org-show-context 'org-goto))))))
23940 (defun org-link-display-format (link)
23941 "Replace a link with its the description.
23942 If there is no description, use the link target."
23943 (save-match-data
23944 (if (string-match org-bracket-link-analytic-regexp link)
23945 (replace-match (if (match-end 5)
23946 (match-string 5 link)
23947 (concat (match-string 1 link)
23948 (match-string 3 link)))
23949 nil t link)
23950 link)))
23952 (defun org-toggle-link-display ()
23953 "Toggle the literal or descriptive display of links."
23954 (interactive)
23955 (if org-descriptive-links
23956 (progn (org-remove-from-invisibility-spec '(org-link))
23957 (org-restart-font-lock)
23958 (setq org-descriptive-links nil))
23959 (progn (add-to-invisibility-spec '(org-link))
23960 (org-restart-font-lock)
23961 (setq org-descriptive-links t))))
23963 ;; Speedbar support
23965 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23966 "Overlay marking the agenda restriction line in speedbar.")
23967 (overlay-put org-speedbar-restriction-lock-overlay
23968 'face 'org-agenda-restriction-lock)
23969 (overlay-put org-speedbar-restriction-lock-overlay
23970 'help-echo "Agendas are currently limited to this item.")
23971 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23973 (defun org-speedbar-set-agenda-restriction ()
23974 "Restrict future agenda commands to the location at point in speedbar.
23975 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23976 (interactive)
23977 (require 'org-agenda)
23978 (let (p m tp np dir txt)
23979 (cond
23980 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23981 'org-imenu t))
23982 (setq m (get-text-property p 'org-imenu-marker))
23983 (with-current-buffer (marker-buffer m)
23984 (goto-char m)
23985 (org-agenda-set-restriction-lock 'subtree)))
23986 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23987 'speedbar-function 'speedbar-find-file))
23988 (setq tp (previous-single-property-change
23989 (1+ p) 'speedbar-function)
23990 np (next-single-property-change
23991 tp 'speedbar-function)
23992 dir (speedbar-line-directory)
23993 txt (buffer-substring-no-properties (or tp (point-min))
23994 (or np (point-max))))
23995 (with-current-buffer (find-file-noselect
23996 (let ((default-directory dir))
23997 (expand-file-name txt)))
23998 (unless (derived-mode-p 'org-mode)
23999 (user-error "Cannot restrict to non-Org-mode file"))
24000 (org-agenda-set-restriction-lock 'file)))
24001 (t (user-error "Don't know how to restrict Org-mode's agenda")))
24002 (move-overlay org-speedbar-restriction-lock-overlay
24003 (point-at-bol) (point-at-eol))
24004 (setq current-prefix-arg nil)
24005 (org-agenda-maybe-redo)))
24007 (defvar speedbar-file-key-map)
24008 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24009 (eval-after-load "speedbar"
24010 '(progn
24011 (speedbar-add-supported-extension ".org")
24012 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24013 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24014 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24015 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24016 (add-hook 'speedbar-visiting-tag-hook
24017 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24019 ;;; Fixes and Hacks for problems with other packages
24021 (defun org-mode-flyspell-verify ()
24022 "Function used for `flyspell-generic-check-word-predicate'."
24023 (if (org-at-heading-p)
24024 ;; At a headline or an inlinetask, check title only. This is
24025 ;; faster than relying on `org-element-at-point'.
24026 (and (save-excursion (beginning-of-line)
24027 (and (let ((case-fold-search t))
24028 (not (looking-at "\\*+ END[ \t]*$")))
24029 (looking-at org-complex-heading-regexp)))
24030 (match-beginning 4)
24031 (>= (point) (match-beginning 4))
24032 (or (not (match-beginning 5))
24033 (< (point) (match-beginning 5))))
24034 (let* ((element (org-element-at-point))
24035 (post-affiliated (org-element-property :post-affiliated element))
24036 (object-check
24037 (function
24038 ;; Non-nil if checks can be done for object at point.
24039 (lambda ()
24040 (let ((object (save-excursion
24041 (when (org-looking-at-p "\\>") (backward-char))
24042 (org-element-context element))))
24043 (case (org-element-type object)
24044 ;; Prevent checks in links due to keybinding conflict
24045 ;; with Flyspell.
24046 ((code entity export-snippet inline-babel-call
24047 inline-src-block line-break latex-fragment link macro
24048 statistics-cookie target timestamp verbatim)
24049 nil)
24050 (footnote-reference
24051 ;; Only in inline footnotes, within the definition.
24052 (and (eq (org-element-property :type object) 'inline)
24053 (< (save-excursion
24054 (goto-char (org-element-property :begin object))
24055 (search-forward ":" nil t 2))
24056 (point))))
24057 (otherwise t)))))))
24058 (cond
24059 ;; Ignore checks in all affiliated keywords but captions.
24060 ((and post-affiliated (< (point) post-affiliated))
24061 (and (save-excursion
24062 (beginning-of-line)
24063 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
24064 (> (point) (match-end 0))
24065 (funcall object-check)))
24066 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
24067 ((and org-log-into-drawer
24068 (let ((log (or (org-string-nw-p org-log-into-drawer) "LOGBOOK"))
24069 (parent element))
24070 (while (and parent (not (eq (org-element-type parent) 'drawer)))
24071 (setq parent (org-element-property :parent parent)))
24072 (and parent
24073 (eq (compare-strings
24074 log nil nil
24075 (org-element-property :drawer-name parent) nil nil t)
24076 t))))
24077 nil)
24079 (case (org-element-type element)
24080 ((comment quote-section) t)
24081 (comment-block
24082 ;; Allow checks between block markers, not on them.
24083 (and (> (line-beginning-position)
24084 (org-element-property :post-affiliated element))
24085 (save-excursion
24086 (end-of-line)
24087 (skip-chars-forward " \r\t\n")
24088 (< (point) (org-element-property :end element)))))
24089 ;; Arbitrary list of keywords where checks are meaningful.
24090 ;; Make sure point is on the value part of the element.
24091 (keyword
24092 (and (member (org-element-property :key element)
24093 '("DESCRIPTION" "TITLE"))
24094 (< (save-excursion
24095 (beginning-of-line) (search-forward ":") (point))
24096 (point))))
24097 ;; Check is globally allowed in paragraphs verse blocks and
24098 ;; table rows (after affiliated keywords) but some objects
24099 ;; must not be affected.
24100 ((paragraph table-row verse-block)
24101 (and (>= (point) (org-element-property :contents-begin element))
24102 (< (point) (org-element-property :contents-end element))
24103 (funcall object-check)))))))))
24104 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
24106 (defun org-remove-flyspell-overlays-in (beg end)
24107 "Remove flyspell overlays in region."
24108 (and (org-bound-and-true-p flyspell-mode)
24109 (fboundp 'flyspell-delete-region-overlays)
24110 (flyspell-delete-region-overlays beg end)))
24112 (eval-after-load "flyspell"
24113 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
24115 ;; Make `bookmark-jump' shows the jump location if it was hidden.
24116 (eval-after-load "bookmark"
24117 '(if (boundp 'bookmark-after-jump-hook)
24118 ;; We can use the hook
24119 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
24120 ;; Hook not available, use advice
24121 (defadvice bookmark-jump (after org-make-visible activate)
24122 "Make the position visible."
24123 (org-bookmark-jump-unhide))))
24125 ;; Make sure saveplace shows the location if it was hidden
24126 (eval-after-load "saveplace"
24127 '(defadvice save-place-find-file-hook (after org-make-visible activate)
24128 "Make the position visible."
24129 (org-bookmark-jump-unhide)))
24131 ;; Make sure ecb shows the location if it was hidden
24132 (eval-after-load "ecb"
24133 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
24134 "Make hierarchy visible when jumping into location from ECB tree buffer."
24135 (if (derived-mode-p 'org-mode)
24136 (org-show-context))))
24138 (defun org-bookmark-jump-unhide ()
24139 "Unhide the current position, to show the bookmark location."
24140 (and (derived-mode-p 'org-mode)
24141 (or (outline-invisible-p)
24142 (save-excursion (goto-char (max (point-min) (1- (point))))
24143 (outline-invisible-p)))
24144 (org-show-context 'bookmark-jump)))
24146 ;; Make session.el ignore our circular variable
24147 (defvar session-globals-exclude)
24148 (eval-after-load "session"
24149 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24151 ;;;; Finish up
24153 (provide 'org)
24155 (run-hooks 'org-load-hook)
24157 ;;; org.el ends here