Merge branch 'maint'
[org-mode.git] / lisp / org.el
blobf7a038eac1c0a1e5c2b10a0be38d070832d8e574
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2013 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
29 ;; project planning with a fast and effective plain-text system.
31 ;; Org-mode develops organizational tasks around NOTES files that contain
32 ;; information about projects as plain text. Org-mode is implemented on
33 ;; top of outline-mode, which makes it possible to keep the content of
34 ;; large files well structured. Visibility cycling and structure editing
35 ;; help to work with the tree. Tables are easily created with a built-in
36 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
37 ;; and scheduling. It dynamically compiles entries into an agenda that
38 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
39 ;; Plain text URL-like links connect to websites, emails, Usenet
40 ;; messages, BBDB entries, and any files related to the projects. For
41 ;; printing and sharing of notes, an Org-mode file can be exported as a
42 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
43 ;; iCalendar file. It can also serve as a publishing tool for a set of
44 ;; linked webpages.
46 ;; Installation and Activation
47 ;; ---------------------------
48 ;; See the corresponding sections in the manual at
50 ;; http://orgmode.org/org.html#Installation
52 ;; Documentation
53 ;; -------------
54 ;; The documentation of Org-mode can be found in the TeXInfo file. The
55 ;; distribution also contains a PDF version of it. At the homepage of
56 ;; Org-mode, you can read the same text online as HTML. There is also an
57 ;; excellent reference card made by Philip Rooke. This card can be found
58 ;; in the etc/ directory of Emacs 22.
60 ;; A list of recent changes can be found at
61 ;; http://orgmode.org/Changes.html
63 ;;; Code:
65 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
66 (defvar org-table-formula-constants-local nil
67 "Local version of `org-table-formula-constants'.")
68 (make-variable-buffer-local 'org-table-formula-constants-local)
70 ;;;; Require other packages
72 (eval-when-compile
73 (require 'cl)
74 (require 'gnus-sum))
76 (require 'calendar)
77 (require 'find-func)
78 (require 'format-spec)
80 (load "org-loaddefs.el" t t t)
82 (require 'org-macs)
83 (require 'org-compat)
85 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
86 ;; some places -- e.g. see the macro `org-with-limited-levels'.
88 ;; In Org buffers, the value of `outline-regexp' is that of
89 ;; `org-outline-regexp'. The only function still directly relying on
90 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
91 ;; job when `orgstruct-mode' is active.
92 (defvar org-outline-regexp "\\*+ "
93 "Regexp to match Org headlines.")
95 (defvar org-outline-regexp-bol "^\\*+ "
96 "Regexp to match Org headlines.
97 This is similar to `org-outline-regexp' but additionally makes
98 sure that we are at the beginning of the line.")
100 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
101 "Matches a headline, putting stars and text into groups.
102 Stars are put in group 1 and the trimmed body in group 2.")
104 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
105 (unless (boundp 'calendar-view-holidays-initially-flag)
106 (org-defvaralias 'calendar-view-holidays-initially-flag
107 'view-calendar-holidays-initially))
108 (unless (boundp 'calendar-view-diary-initially-flag)
109 (org-defvaralias 'calendar-view-diary-initially-flag
110 'view-diary-entries-initially))
111 (unless (boundp 'diary-fancy-buffer)
112 (org-defvaralias 'diary-fancy-buffer 'fancy-diary-buffer))
114 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
115 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
116 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
117 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
118 (declare-function org-clocktable-shift "org-clock" (dir n))
119 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
120 (declare-function org-clock-update-time-maybe "org-clock" ())
121 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
122 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
123 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
124 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
126 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
127 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body))
128 (declare-function orgtbl-mode "org-table" (&optional arg))
129 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
130 (declare-function org-beamer-mode "ox-beamer" ())
131 (declare-function org-table-blank-field "org-table" ())
132 (declare-function org-table-edit-field "org-table" (arg))
133 (declare-function org-table-insert-row "org-table" (&optional arg))
134 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
135 (declare-function org-table-set-constants "org-table" ())
136 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
137 (declare-function org-id-get-create "org-id" (&optional force))
138 (declare-function org-add-archive-files "org-archive" (files))
139 (declare-function org-id-find-id-file "org-id" (id))
140 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
141 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
142 (declare-function org-agenda-redo "org-agenda" (&optional all))
143 (declare-function org-table-align "org-table" ())
144 (declare-function org-table-begin "org-table" (&optional table-type))
145 (declare-function org-table-end "org-table" (&optional table-type))
146 (declare-function org-table-paste-rectangle "org-table" ())
147 (declare-function org-table-maybe-eval-formula "org-table" ())
148 (declare-function org-table-maybe-recalculate-line "org-table" ())
150 (declare-function org-element--parse-objects "org-element"
151 (beg end acc restriction))
152 (declare-function org-element-at-point "org-element" ())
153 (declare-function org-element-cache-reset "org-element" (&optional all))
154 (declare-function org-element-contents "org-element" (element))
155 (declare-function org-element-context "org-element" (&optional element))
156 (declare-function org-element-interpret-data "org-element"
157 (data &optional parent))
158 (declare-function org-element-map "org-element"
159 (data types fun &optional info first-match no-recursion))
160 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
161 (declare-function org-element-parse-buffer "org-element"
162 (&optional granularity visible-only))
163 (declare-function org-element-property "org-element" (property element))
164 (declare-function org-element-put-property "org-element"
165 (element property value))
166 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
167 (declare-function org-element--parse-objects "org-element"
168 (beg end acc restriction))
169 (declare-function org-element-parse-buffer "org-element"
170 (&optional granularity visible-only))
171 (declare-function org-element-restriction "org-element" (element))
172 (declare-function org-element-type "org-element" (element))
174 (defsubst org-uniquify (list)
175 "Non-destructively remove duplicate elements from LIST."
176 (let ((res (copy-sequence list))) (delete-dups res)))
178 ;; load languages based on value of `org-babel-load-languages'
179 (defvar org-babel-load-languages)
181 ;;;###autoload
182 (defun org-babel-do-load-languages (sym value)
183 "Load the languages defined in `org-babel-load-languages'."
184 (set-default sym value)
185 (mapc (lambda (pair)
186 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
187 (if active
188 (progn
189 (require (intern (concat "ob-" lang))))
190 (progn
191 (funcall 'fmakunbound
192 (intern (concat "org-babel-execute:" lang)))
193 (funcall 'fmakunbound
194 (intern (concat "org-babel-expand-body:" lang)))))))
195 org-babel-load-languages))
197 ;;;###autoload
198 (defun org-babel-load-file (file &optional compile)
199 "Load Emacs Lisp source code blocks in the Org-mode FILE.
200 This function exports the source code using `org-babel-tangle'
201 and then loads the resulting file using `load-file'. With prefix
202 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
203 file to byte-code before it is loaded."
204 (interactive "fFile to load: \nP")
205 (let* ((age (lambda (file)
206 (float-time
207 (time-subtract (current-time)
208 (nth 5 (or (file-attributes (file-truename file))
209 (file-attributes file)))))))
210 (base-name (file-name-sans-extension file))
211 (exported-file (concat base-name ".el")))
212 ;; tangle if the org-mode file is newer than the elisp file
213 (unless (and (file-exists-p exported-file)
214 (> (funcall age file) (funcall age exported-file)))
215 (setq exported-file
216 (car (org-babel-tangle-file file exported-file "emacs-lisp"))))
217 (message "%s %s"
218 (if compile
219 (progn (byte-compile-file exported-file 'load)
220 "Compiled and loaded")
221 (progn (load-file exported-file) "Loaded"))
222 exported-file)))
224 (defcustom org-babel-load-languages '((emacs-lisp . t))
225 "Languages which can be evaluated in Org-mode buffers.
226 This list can be used to load support for any of the languages
227 below, note that each language will depend on a different set of
228 system executables and/or Emacs modes. When a language is
229 \"loaded\", then code blocks in that language can be evaluated
230 with `org-babel-execute-src-block' bound by default to C-c
231 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
232 be set to remove code block evaluation from the C-c C-c
233 keybinding. By default only Emacs Lisp (which has no
234 requirements) is loaded."
235 :group 'org-babel
236 :set 'org-babel-do-load-languages
237 :version "24.1"
238 :type '(alist :tag "Babel Languages"
239 :key-type
240 (choice
241 (const :tag "Awk" awk)
242 (const :tag "C" C)
243 (const :tag "R" R)
244 (const :tag "Asymptote" asymptote)
245 (const :tag "Calc" calc)
246 (const :tag "Clojure" clojure)
247 (const :tag "CSS" css)
248 (const :tag "Ditaa" ditaa)
249 (const :tag "Dot" dot)
250 (const :tag "Emacs Lisp" emacs-lisp)
251 (const :tag "Fortran" fortran)
252 (const :tag "Gnuplot" gnuplot)
253 (const :tag "Haskell" haskell)
254 (const :tag "IO" io)
255 (const :tag "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-cycle '(4)))
6898 ((eq org-startup-folded 'content)
6899 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6900 (org-cycle '(4)) (org-cycle '(4)))))
6901 (unless (eq org-startup-folded 'showeverything)
6902 (if org-hide-block-startup (org-hide-block-all))
6903 (org-set-visibility-according-to-property 'no-cleanup)
6904 (org-cycle-hide-archived-subtrees 'all)
6905 (org-cycle-hide-drawers 'all)
6906 (org-cycle-show-empty-lines t)))
6908 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6909 "Switch subtree visibilities according to :VISIBILITY: property."
6910 (interactive)
6911 (let (org-show-entry-below state)
6912 (save-excursion
6913 (goto-char (point-min))
6914 (while (re-search-forward
6915 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6916 nil t)
6917 (setq state (match-string 1))
6918 (save-excursion
6919 (org-back-to-heading t)
6920 (hide-subtree)
6921 (org-reveal)
6922 (cond
6923 ((equal state '("fold" "folded"))
6924 (hide-subtree))
6925 ((equal state "children")
6926 (org-show-hidden-entry)
6927 (show-children))
6928 ((equal state "content")
6929 (save-excursion
6930 (save-restriction
6931 (org-narrow-to-subtree)
6932 (org-content))))
6933 ((member state '("all" "showall"))
6934 (show-subtree)))))
6935 (unless no-cleanup
6936 (org-cycle-hide-archived-subtrees 'all)
6937 (org-cycle-hide-drawers 'all)
6938 (org-cycle-show-empty-lines 'all)))))
6940 ;; This function uses outline-regexp instead of the more fundamental
6941 ;; org-outline-regexp so that org-cycle-global works outside of Org
6942 ;; buffers, where outline-regexp is needed.
6943 (defun org-overview ()
6944 "Switch to overview mode, showing only top-level headlines.
6945 Really, this shows all headlines with level equal or greater than the level
6946 of the first headline in the buffer. This is important, because if the
6947 first headline is not level one, then (hide-sublevels 1) gives confusing
6948 results."
6949 (interactive)
6950 (let ((pos (point))
6951 (level (save-excursion
6952 (goto-char (point-min))
6953 (if (re-search-forward (concat "^" outline-regexp) nil t)
6954 (progn
6955 (goto-char (match-beginning 0))
6956 (funcall outline-level))))))
6957 (and level (hide-sublevels level))
6958 (recenter '(4))
6959 (goto-char pos)))
6961 (defun org-content (&optional arg)
6962 "Show all headlines in the buffer, like a table of contents.
6963 With numerical argument N, show content up to level N."
6964 (interactive "P")
6965 (save-excursion
6966 ;; Visit all headings and show their offspring
6967 (and (integerp arg) (org-overview))
6968 (goto-char (point-max))
6969 (catch 'exit
6970 (while (and (progn (condition-case nil
6971 (outline-previous-visible-heading 1)
6972 (error (goto-char (point-min))))
6974 (looking-at org-outline-regexp))
6975 (if (integerp arg)
6976 (show-children (1- arg))
6977 (show-branches))
6978 (if (bobp) (throw 'exit nil))))))
6981 (defun org-optimize-window-after-visibility-change (state)
6982 "Adjust the window after a change in outline visibility.
6983 This function is the default value of the hook `org-cycle-hook'."
6984 (when (get-buffer-window (current-buffer))
6985 (cond
6986 ((eq state 'content) nil)
6987 ((eq state 'all) nil)
6988 ((eq state 'folded) nil)
6989 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6990 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6992 (defun org-remove-empty-overlays-at (pos)
6993 "Remove outline overlays that do not contain non-white stuff."
6994 (mapc
6995 (lambda (o)
6996 (and (eq 'outline (overlay-get o 'invisible))
6997 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6998 (overlay-end o))))
6999 (delete-overlay o)))
7000 (overlays-at pos)))
7002 (defun org-clean-visibility-after-subtree-move ()
7003 "Fix visibility issues after moving a subtree."
7004 ;; First, find a reasonable region to look at:
7005 ;; Start two siblings above, end three below
7006 (let* ((beg (save-excursion
7007 (and (org-get-last-sibling)
7008 (org-get-last-sibling))
7009 (point)))
7010 (end (save-excursion
7011 (and (org-get-next-sibling)
7012 (org-get-next-sibling)
7013 (org-get-next-sibling))
7014 (if (org-at-heading-p)
7015 (point-at-eol)
7016 (point))))
7017 (level (looking-at "\\*+"))
7018 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
7019 (save-excursion
7020 (save-restriction
7021 (narrow-to-region beg end)
7022 (when re
7023 ;; Properly fold already folded siblings
7024 (goto-char (point-min))
7025 (while (re-search-forward re nil t)
7026 (if (and (not (outline-invisible-p))
7027 (save-excursion
7028 (goto-char (point-at-eol)) (outline-invisible-p)))
7029 (hide-entry))))
7030 (org-cycle-show-empty-lines 'overview)
7031 (org-cycle-hide-drawers 'overview)))))
7033 (defun org-cycle-show-empty-lines (state)
7034 "Show empty lines above all visible headlines.
7035 The region to be covered depends on STATE when called through
7036 `org-cycle-hook'. Lisp program can use t for STATE to get the
7037 entire buffer covered. Note that an empty line is only shown if there
7038 are at least `org-cycle-separator-lines' empty lines before the headline."
7039 (when (not (= org-cycle-separator-lines 0))
7040 (save-excursion
7041 (let* ((n (abs org-cycle-separator-lines))
7042 (re (cond
7043 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7044 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7045 (t (let ((ns (number-to-string (- n 2))))
7046 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7047 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7048 beg end b e)
7049 (cond
7050 ((memq state '(overview contents t))
7051 (setq beg (point-min) end (point-max)))
7052 ((memq state '(children folded))
7053 (setq beg (point) end (progn (org-end-of-subtree t t)
7054 (beginning-of-line 2)
7055 (point)))))
7056 (when beg
7057 (goto-char beg)
7058 (while (re-search-forward re end t)
7059 (unless (get-char-property (match-end 1) 'invisible)
7060 (setq e (match-end 1))
7061 (if (< org-cycle-separator-lines 0)
7062 (setq b (save-excursion
7063 (goto-char (match-beginning 0))
7064 (org-back-over-empty-lines)
7065 (if (save-excursion
7066 (goto-char (max (point-min) (1- (point))))
7067 (org-at-heading-p))
7068 (1- (point))
7069 (point))))
7070 (setq b (match-beginning 1)))
7071 (outline-flag-region b e nil)))))))
7072 ;; Never hide empty lines at the end of the file.
7073 (save-excursion
7074 (goto-char (point-max))
7075 (outline-previous-heading)
7076 (outline-end-of-heading)
7077 (if (and (looking-at "[ \t\n]+")
7078 (= (match-end 0) (point-max)))
7079 (outline-flag-region (point) (match-end 0) nil))))
7081 (defun org-show-empty-lines-in-parent ()
7082 "Move to the parent and re-show empty lines before visible headlines."
7083 (save-excursion
7084 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7085 (org-cycle-show-empty-lines context))))
7087 (defun org-files-list ()
7088 "Return `org-agenda-files' list, plus all open org-mode files.
7089 This is useful for operations that need to scan all of a user's
7090 open and agenda-wise Org files."
7091 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7092 (dolist (buf (buffer-list))
7093 (with-current-buffer buf
7094 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7095 (let ((file (expand-file-name (buffer-file-name))))
7096 (unless (member file files)
7097 (push file files))))))
7098 files))
7100 (defsubst org-entry-beginning-position ()
7101 "Return the beginning position of the current entry."
7102 (save-excursion (outline-back-to-heading t) (point)))
7104 (defsubst org-entry-end-position ()
7105 "Return the end position of the current entry."
7106 (save-excursion (outline-next-heading) (point)))
7108 (defun org-cycle-hide-drawers (state &optional exceptions)
7109 "Re-hide all drawers after a visibility state change.
7110 When non-nil, optional argument EXCEPTIONS is a list of strings
7111 specifying which drawers should not be hidden."
7112 (when (and (derived-mode-p 'org-mode)
7113 (not (memq state '(overview folded contents))))
7114 (save-excursion
7115 (let* ((globalp (memq state '(contents all)))
7116 (beg (if globalp (point-min) (point)))
7117 (end (if globalp (point-max)
7118 (if (eq state 'children)
7119 (save-excursion (outline-next-heading) (point))
7120 (org-end-of-subtree t)))))
7121 (goto-char beg)
7122 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7123 (unless (member-ignore-case (match-string 1) exceptions)
7124 (let ((drawer (org-element-at-point)))
7125 (when (memq (org-element-type drawer) '(drawer property-drawer))
7126 (org-flag-drawer t drawer)
7127 ;; Make sure to skip drawer entirely or we might flag
7128 ;; it another time when matching its ending line with
7129 ;; `org-drawer-regexp'.
7130 (goto-char (org-element-property :end drawer))))))))))
7132 (defun org-cycle-hide-inline-tasks (state)
7133 "Re-hide inline tasks when switching to 'contents or 'children
7134 visibility state."
7135 (case state
7136 (contents
7137 (when (org-bound-and-true-p org-inlinetask-min-level)
7138 (hide-sublevels (1- org-inlinetask-min-level))))
7139 (children
7140 (when (featurep 'org-inlinetask)
7141 (save-excursion
7142 (while (and (outline-next-heading)
7143 (org-inlinetask-at-task-p))
7144 (org-inlinetask-toggle-visibility)
7145 (org-inlinetask-goto-end)))))))
7147 (defun org-flag-drawer (flag &optional element)
7148 "When FLAG is non-nil, hide the drawer we are at.
7149 Otherwise make it visible. When optional argument ELEMENT is
7150 a parsed drawer, as returned by `org-element-at-point', hide or
7151 show that drawer instead."
7152 (let ((drawer (or element (org-element-at-point))))
7153 (when (memq (org-element-type drawer) '(drawer property-drawer))
7154 (save-excursion
7155 (goto-char (org-element-property :post-affiliated drawer))
7156 (outline-flag-region
7157 (line-end-position)
7158 (progn (goto-char (org-element-property :end drawer))
7159 (skip-chars-backward " \r\t\n")
7160 (line-end-position))
7161 flag)))))
7163 (defun org-subtree-end-visible-p ()
7164 "Is the end of the current subtree visible?"
7165 (pos-visible-in-window-p
7166 (save-excursion (org-end-of-subtree t) (point))))
7168 (defun org-first-headline-recenter (&optional N)
7169 "Move cursor to the first headline and recenter the headline.
7170 Optional argument N means put the headline into the Nth line of the window."
7171 (goto-char (point-min))
7172 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7173 (beginning-of-line)
7174 (recenter (prefix-numeric-value N))))
7176 ;;; Saving and restoring visibility
7178 (defun org-outline-overlay-data (&optional use-markers)
7179 "Return a list of the locations of all outline overlays.
7180 These are overlays with the `invisible' property value `outline'.
7181 The return value is a list of cons cells, with start and stop
7182 positions for each overlay.
7183 If USE-MARKERS is set, return the positions as markers."
7184 (let (beg end)
7185 (save-excursion
7186 (save-restriction
7187 (widen)
7188 (delq nil
7189 (mapcar (lambda (o)
7190 (when (eq (overlay-get o 'invisible) 'outline)
7191 (setq beg (overlay-start o)
7192 end (overlay-end o))
7193 (and beg end (> end beg)
7194 (if use-markers
7195 (cons (move-marker (make-marker) beg)
7196 (move-marker (make-marker) end))
7197 (cons beg end)))))
7198 (overlays-in (point-min) (point-max))))))))
7200 (defun org-set-outline-overlay-data (data)
7201 "Create visibility overlays for all positions in DATA.
7202 DATA should have been made by `org-outline-overlay-data'."
7203 (let (o)
7204 (save-excursion
7205 (save-restriction
7206 (widen)
7207 (show-all)
7208 (mapc (lambda (c)
7209 (outline-flag-region (car c) (cdr c) t))
7210 data)))))
7212 ;;; Folding of blocks
7214 (defvar org-hide-block-overlays nil
7215 "Overlays hiding blocks.")
7216 (make-variable-buffer-local 'org-hide-block-overlays)
7218 (defun org-block-map (function &optional start end)
7219 "Call FUNCTION at the head of all source blocks in the current buffer.
7220 Optional arguments START and END can be used to limit the range."
7221 (let ((start (or start (point-min)))
7222 (end (or end (point-max))))
7223 (save-excursion
7224 (goto-char start)
7225 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7226 (save-excursion
7227 (save-match-data
7228 (goto-char (match-beginning 0))
7229 (funcall function)))))))
7231 (defun org-hide-block-toggle-all ()
7232 "Toggle the visibility of all blocks in the current buffer."
7233 (org-block-map #'org-hide-block-toggle))
7235 (defun org-hide-block-all ()
7236 "Fold all blocks in the current buffer."
7237 (interactive)
7238 (org-show-block-all)
7239 (org-block-map #'org-hide-block-toggle-maybe))
7241 (defun org-show-block-all ()
7242 "Unfold all blocks in the current buffer."
7243 (interactive)
7244 (mapc 'delete-overlay org-hide-block-overlays)
7245 (setq org-hide-block-overlays nil))
7247 (defun org-hide-block-toggle-maybe ()
7248 "Toggle visibility of block at point."
7249 (interactive)
7250 (let ((case-fold-search t))
7251 (if (save-excursion
7252 (beginning-of-line 1)
7253 (looking-at org-block-regexp))
7254 (progn (org-hide-block-toggle)
7255 t) ;; to signal that we took action
7256 nil))) ;; to signal that we did not
7258 (defun org-hide-block-toggle (&optional force)
7259 "Toggle the visibility of the current block."
7260 (interactive)
7261 (save-excursion
7262 (beginning-of-line)
7263 (if (re-search-forward org-block-regexp nil t)
7264 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7265 (end (match-end 0)) ;; end of entire body
7267 (if (memq t (mapcar (lambda (overlay)
7268 (eq (overlay-get overlay 'invisible)
7269 'org-hide-block))
7270 (overlays-at start)))
7271 (if (or (not force) (eq force 'off))
7272 (mapc (lambda (ov)
7273 (when (member ov org-hide-block-overlays)
7274 (setq org-hide-block-overlays
7275 (delq ov org-hide-block-overlays)))
7276 (when (eq (overlay-get ov 'invisible)
7277 'org-hide-block)
7278 (delete-overlay ov)))
7279 (overlays-at start)))
7280 (setq ov (make-overlay start end))
7281 (overlay-put ov 'invisible 'org-hide-block)
7282 ;; make the block accessible to isearch
7283 (overlay-put
7284 ov 'isearch-open-invisible
7285 (lambda (ov)
7286 (when (member ov org-hide-block-overlays)
7287 (setq org-hide-block-overlays
7288 (delq ov org-hide-block-overlays)))
7289 (when (eq (overlay-get ov 'invisible)
7290 'org-hide-block)
7291 (delete-overlay ov))))
7292 (push ov org-hide-block-overlays)))
7293 (user-error "Not looking at a source block"))))
7295 ;; org-tab-after-check-for-cycling-hook
7296 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7297 ;; Remove overlays when changing major mode
7298 (add-hook 'org-mode-hook
7299 (lambda () (org-add-hook 'change-major-mode-hook
7300 'org-show-block-all 'append 'local)))
7302 ;;; Org-goto
7304 (defvar org-goto-window-configuration nil)
7305 (defvar org-goto-marker nil)
7306 (defvar org-goto-map)
7307 (defun org-goto-map ()
7308 "Set the keymap `org-goto'."
7309 (setq org-goto-map
7310 (let ((map (make-sparse-keymap)))
7311 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7312 mouse-drag-region universal-argument org-occur))
7313 cmd)
7314 (while (setq cmd (pop cmds))
7315 (substitute-key-definition cmd cmd map global-map)))
7316 (suppress-keymap map)
7317 (org-defkey map "\C-m" 'org-goto-ret)
7318 (org-defkey map [(return)] 'org-goto-ret)
7319 (org-defkey map [(left)] 'org-goto-left)
7320 (org-defkey map [(right)] 'org-goto-right)
7321 (org-defkey map [(control ?g)] 'org-goto-quit)
7322 (org-defkey map "\C-i" 'org-cycle)
7323 (org-defkey map [(tab)] 'org-cycle)
7324 (org-defkey map [(down)] 'outline-next-visible-heading)
7325 (org-defkey map [(up)] 'outline-previous-visible-heading)
7326 (if org-goto-auto-isearch
7327 (if (fboundp 'define-key-after)
7328 (define-key-after map [t] 'org-goto-local-auto-isearch)
7329 nil)
7330 (org-defkey map "q" 'org-goto-quit)
7331 (org-defkey map "n" 'outline-next-visible-heading)
7332 (org-defkey map "p" 'outline-previous-visible-heading)
7333 (org-defkey map "f" 'outline-forward-same-level)
7334 (org-defkey map "b" 'outline-backward-same-level)
7335 (org-defkey map "u" 'outline-up-heading))
7336 (org-defkey map "/" 'org-occur)
7337 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7338 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7339 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7340 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7341 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7342 map)))
7344 (defconst org-goto-help
7345 "Browse buffer copy, to find location or copy text.%s
7346 RET=jump to location C-g=quit and return to previous location
7347 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7349 (defvar org-goto-start-pos) ; dynamically scoped parameter
7351 (defun org-goto (&optional alternative-interface)
7352 "Look up a different location in the current file, keeping current visibility.
7354 When you want look-up or go to a different location in a
7355 document, the fastest way is often to fold the entire buffer and
7356 then dive into the tree. This method has the disadvantage, that
7357 the previous location will be folded, which may not be what you
7358 want.
7360 This command works around this by showing a copy of the current
7361 buffer in an indirect buffer, in overview mode. You can dive
7362 into the tree in that copy, use org-occur and incremental search
7363 to find a location. When pressing RET or `Q', the command
7364 returns to the original buffer in which the visibility is still
7365 unchanged. After RET it will also jump to the location selected
7366 in the indirect buffer and expose the headline hierarchy above.
7368 With a prefix argument, use the alternative interface: e.g. if
7369 `org-goto-interface' is 'outline use 'outline-path-completion."
7370 (interactive "P")
7371 (org-goto-map)
7372 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7373 (org-refile-use-outline-path t)
7374 (org-refile-target-verify-function nil)
7375 (interface
7376 (if (not alternative-interface)
7377 org-goto-interface
7378 (if (eq org-goto-interface 'outline)
7379 'outline-path-completion
7380 'outline)))
7381 (org-goto-start-pos (point))
7382 (selected-point
7383 (if (eq interface 'outline)
7384 (car (org-get-location (current-buffer) org-goto-help))
7385 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7386 (org-refile-check-position pa)
7387 (nth 3 pa)))))
7388 (if selected-point
7389 (progn
7390 (org-mark-ring-push org-goto-start-pos)
7391 (goto-char selected-point)
7392 (if (or (outline-invisible-p) (org-invisible-p2))
7393 (org-show-context 'org-goto)))
7394 (message "Quit"))))
7396 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7397 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7398 (defvar org-goto-local-auto-isearch-map) ; defined below
7400 (defun org-get-location (buf help)
7401 "Let the user select a location in the Org-mode buffer BUF.
7402 This function uses a recursive edit. It returns the selected position
7403 or nil."
7404 (org-no-popups
7405 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7406 (isearch-hide-immediately nil)
7407 (isearch-search-fun-function
7408 (lambda () 'org-goto-local-search-headings))
7409 (org-goto-selected-point org-goto-exit-command))
7410 (save-excursion
7411 (save-window-excursion
7412 (delete-other-windows)
7413 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7414 (org-pop-to-buffer-same-window
7415 (condition-case nil
7416 (make-indirect-buffer (current-buffer) "*org-goto*")
7417 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7418 (with-output-to-temp-buffer "*Org Help*"
7419 (princ (format help (if org-goto-auto-isearch
7420 " Just type for auto-isearch."
7421 " n/p/f/b/u to navigate, q to quit."))))
7422 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7423 (setq buffer-read-only nil)
7424 (let ((org-startup-truncated t)
7425 (org-startup-folded nil)
7426 (org-startup-align-all-tables nil))
7427 (org-mode)
7428 (org-overview))
7429 (setq buffer-read-only t)
7430 (if (and (boundp 'org-goto-start-pos)
7431 (integer-or-marker-p org-goto-start-pos))
7432 (let ((org-show-hierarchy-above t)
7433 (org-show-siblings t)
7434 (org-show-following-heading t))
7435 (goto-char org-goto-start-pos)
7436 (and (outline-invisible-p) (org-show-context)))
7437 (goto-char (point-min)))
7438 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7439 (message "Select location and press RET")
7440 (use-local-map org-goto-map)
7441 (recursive-edit)))
7442 (kill-buffer "*org-goto*")
7443 (cons org-goto-selected-point org-goto-exit-command))))
7445 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7446 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7447 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7448 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7450 (defun org-goto-local-search-headings (string bound noerror)
7451 "Search and make sure that any matches are in headlines."
7452 (catch 'return
7453 (while (if isearch-forward
7454 (search-forward string bound noerror)
7455 (search-backward string bound noerror))
7456 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7457 (and (member :headline context)
7458 (not (member :tags context))))
7459 (throw 'return (point))))))
7461 (defun org-goto-local-auto-isearch ()
7462 "Start isearch."
7463 (interactive)
7464 (goto-char (point-min))
7465 (let ((keys (this-command-keys)))
7466 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7467 (isearch-mode t)
7468 (isearch-process-search-char (string-to-char keys)))))
7470 (defun org-goto-ret (&optional arg)
7471 "Finish `org-goto' by going to the new location."
7472 (interactive "P")
7473 (setq org-goto-selected-point (point)
7474 org-goto-exit-command 'return)
7475 (throw 'exit nil))
7477 (defun org-goto-left ()
7478 "Finish `org-goto' by going to the new location."
7479 (interactive)
7480 (if (org-at-heading-p)
7481 (progn
7482 (beginning-of-line 1)
7483 (setq org-goto-selected-point (point)
7484 org-goto-exit-command 'left)
7485 (throw 'exit nil))
7486 (user-error "Not on a heading")))
7488 (defun org-goto-right ()
7489 "Finish `org-goto' by going to the new location."
7490 (interactive)
7491 (if (org-at-heading-p)
7492 (progn
7493 (setq org-goto-selected-point (point)
7494 org-goto-exit-command 'right)
7495 (throw 'exit nil))
7496 (user-error "Not on a heading")))
7498 (defun org-goto-quit ()
7499 "Finish `org-goto' without cursor motion."
7500 (interactive)
7501 (setq org-goto-selected-point nil)
7502 (setq org-goto-exit-command 'quit)
7503 (throw 'exit nil))
7505 ;;; Indirect buffer display of subtrees
7507 (defvar org-indirect-dedicated-frame nil
7508 "This is the frame being used for indirect tree display.")
7509 (defvar org-last-indirect-buffer nil)
7511 (defun org-tree-to-indirect-buffer (&optional arg)
7512 "Create indirect buffer and narrow it to current subtree.
7513 With a numerical prefix ARG, go up to this level and then take that tree.
7514 If ARG is negative, go up that many levels.
7516 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7517 indirect buffer previously made with this command, to avoid proliferation of
7518 indirect buffers. However, when you call the command with a \
7519 \\[universal-argument] prefix, or
7520 when `org-indirect-buffer-display' is `new-frame', the last buffer
7521 is kept so that you can work with several indirect buffers at the same time.
7522 If `org-indirect-buffer-display' is `dedicated-frame', the \
7523 \\[universal-argument] prefix also
7524 requests that a new frame be made for the new buffer, so that the dedicated
7525 frame is not changed."
7526 (interactive "P")
7527 (let ((cbuf (current-buffer))
7528 (cwin (selected-window))
7529 (pos (point))
7530 beg end level heading ibuf)
7531 (save-excursion
7532 (org-back-to-heading t)
7533 (when (numberp arg)
7534 (setq level (org-outline-level))
7535 (if (< arg 0) (setq arg (+ level arg)))
7536 (while (> (setq level (org-outline-level)) arg)
7537 (org-up-heading-safe)))
7538 (setq beg (point)
7539 heading (org-get-heading))
7540 (org-end-of-subtree t t)
7541 (if (org-at-heading-p) (backward-char 1))
7542 (setq end (point)))
7543 (if (and (buffer-live-p org-last-indirect-buffer)
7544 (not (eq org-indirect-buffer-display 'new-frame))
7545 (not arg))
7546 (kill-buffer org-last-indirect-buffer))
7547 (setq ibuf (org-get-indirect-buffer cbuf heading)
7548 org-last-indirect-buffer ibuf)
7549 (cond
7550 ((or (eq org-indirect-buffer-display 'new-frame)
7551 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7552 (select-frame (make-frame))
7553 (delete-other-windows)
7554 (org-pop-to-buffer-same-window ibuf)
7555 (org-set-frame-title heading))
7556 ((eq org-indirect-buffer-display 'dedicated-frame)
7557 (raise-frame
7558 (select-frame (or (and org-indirect-dedicated-frame
7559 (frame-live-p org-indirect-dedicated-frame)
7560 org-indirect-dedicated-frame)
7561 (setq org-indirect-dedicated-frame (make-frame)))))
7562 (delete-other-windows)
7563 (org-pop-to-buffer-same-window ibuf)
7564 (org-set-frame-title (concat "Indirect: " heading)))
7565 ((eq org-indirect-buffer-display 'current-window)
7566 (org-pop-to-buffer-same-window ibuf))
7567 ((eq org-indirect-buffer-display 'other-window)
7568 (pop-to-buffer ibuf))
7569 (t (error "Invalid value")))
7570 (if (featurep 'xemacs)
7571 (save-excursion (org-mode) (turn-on-font-lock)))
7572 (narrow-to-region beg end)
7573 (show-all)
7574 (goto-char pos)
7575 (run-hook-with-args 'org-cycle-hook 'all)
7576 (and (window-live-p cwin) (select-window cwin))))
7578 (defun org-get-indirect-buffer (&optional buffer heading)
7579 (setq buffer (or buffer (current-buffer)))
7580 (let ((n 1) (base (buffer-name buffer)) bname)
7581 (while (buffer-live-p
7582 (get-buffer
7583 (setq bname
7584 (concat base "-"
7585 (if heading (concat heading "-" (number-to-string n))
7586 (number-to-string n))))))
7587 (setq n (1+ n)))
7588 (condition-case nil
7589 (make-indirect-buffer buffer bname 'clone)
7590 (error (make-indirect-buffer buffer bname)))))
7592 (defun org-set-frame-title (title)
7593 "Set the title of the current frame to the string TITLE."
7594 ;; FIXME: how to name a single frame in XEmacs???
7595 (unless (featurep 'xemacs)
7596 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7598 ;;;; Structure editing
7600 ;;; Inserting headlines
7602 (defun org-previous-line-empty-p (&optional next)
7603 "Is the previous line a blank line?
7604 When NEXT is non-nil, check the next line instead."
7605 (save-excursion
7606 (and (not (bobp))
7607 (or (beginning-of-line (if next 2 0)) t)
7608 (save-match-data
7609 (looking-at "[ \t]*$")))))
7611 (defun org-insert-heading (&optional arg invisible-ok)
7612 "Insert a new heading or item with same depth at point.
7613 If point is in a plain list and ARG is nil, create a new list item.
7614 With one universal prefix argument, insert a heading even in lists.
7615 With two universal prefix arguments, insert the heading at the end
7616 of the parent subtree.
7618 If point is at the beginning of a headline, insert a sibling before
7619 the current headline. If point is not at the beginning, split the line
7620 and create a new headline with the text in the current line after point
7621 \(see `org-M-RET-may-split-line' on how to modify this behavior).
7623 If point is at the beginning of a normal line, turn this line into
7624 a heading.
7626 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7627 This is important for non-interactive uses of the command."
7628 (interactive "P")
7629 (if (org-called-interactively-p 'any) (org-reveal))
7630 (let ((itemp (org-in-item-p))
7631 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7632 (respect-content (or org-insert-heading-respect-content
7633 (equal arg '(16))))
7634 (initial-content "")
7635 (adjust-empty-lines t))
7637 (cond
7639 ((or (= (buffer-size) 0)
7640 (and (not (save-excursion
7641 (and (ignore-errors (org-back-to-heading invisible-ok))
7642 (org-at-heading-p))))
7643 (or arg (not itemp))))
7644 ;; At beginning of buffer or so high up that only a heading
7645 ;; makes sense.
7646 (insert
7647 (if (or (bobp) (org-previous-line-empty-p)) "" "\n")
7648 (if (org-in-src-block-p) ",* " "* "))
7649 (run-hooks 'org-insert-heading-hook))
7651 ((and itemp (not (equal arg '(4))))
7652 ;; Insert an item
7653 (org-insert-item))
7656 ;; Insert a heading
7657 (save-restriction
7658 (widen)
7659 (let* ((level nil)
7660 (on-heading (org-at-heading-p))
7661 (empty-line-p (if on-heading
7662 (org-previous-line-empty-p)
7663 ;; We will decide later
7664 nil))
7665 ;; Get a level string to fall back on
7666 (fix-level
7667 (save-excursion
7668 (org-back-to-heading t)
7669 (if (org-previous-line-empty-p) (setq empty-line-p t))
7670 (looking-at org-outline-regexp)
7671 (make-string (1- (length (match-string 0))) ?*)))
7672 (stars
7673 (save-excursion
7674 (condition-case nil
7675 (progn
7676 (org-back-to-heading invisible-ok)
7677 (when (and (not on-heading)
7678 (featurep 'org-inlinetask)
7679 (integerp org-inlinetask-min-level)
7680 (>= (length (match-string 0))
7681 org-inlinetask-min-level))
7682 ;; Find a heading level before the inline task
7683 (while (and (setq level (org-up-heading-safe))
7684 (>= level org-inlinetask-min-level)))
7685 (if (org-at-heading-p)
7686 (org-back-to-heading invisible-ok)
7687 (error "This should not happen")))
7688 (unless (and (save-excursion
7689 (save-match-data
7690 (org-backward-heading-same-level
7691 1 invisible-ok))
7692 (= (point) (match-beginning 0)))
7693 (not (org-previous-line-empty-p t)))
7694 (setq empty-line-p (or empty-line-p
7695 (org-previous-line-empty-p))))
7696 (match-string 0))
7697 (error (or fix-level "* ")))))
7698 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7699 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7700 pos hide-previous previous-pos)
7702 ;; If we insert after content, move there and clean up whitespace
7703 (when respect-content
7704 (org-end-of-subtree nil t)
7705 (skip-chars-backward " \r\n")
7706 (and (looking-at "[ \t]+") (replace-match ""))
7707 (unless (eobp) (forward-char 1))
7708 (when (looking-at "^\\*")
7709 (unless (bobp) (backward-char 1))
7710 (insert "\n")))
7712 ;; If we are splitting, grab the text that should be moved to the new headline
7713 (when may-split
7714 (if (org-on-heading-p)
7715 ;; This is a heading, we split intelligently (keeping tags)
7716 (let ((pos (point)))
7717 (goto-char (point-at-bol))
7718 (unless (looking-at org-complex-heading-regexp)
7719 (error "This should not happen"))
7720 (when (and (match-beginning 4)
7721 (> pos (match-beginning 4))
7722 (< pos (match-end 4)))
7723 (setq initial-content (buffer-substring pos (match-end 4)))
7724 (goto-char pos)
7725 (delete-region (point) (match-end 4))
7726 (if (looking-at "[ \t]*$")
7727 (replace-match "")
7728 (insert (make-string (length initial-content) ?\ )))
7729 (setq initial-content (org-trim initial-content)))
7730 (goto-char pos))
7731 ;; a normal line
7732 (unless (bolp)
7733 (setq initial-content (buffer-substring (point) (point-at-eol)))
7734 (delete-region (point) (point-at-eol))
7735 (setq initial-content (org-trim initial-content)))))
7737 ;; If we are at the beginning of the line, insert before it. Else after
7738 (cond
7739 ((and (bolp) (looking-at "[ \t]*$")))
7740 ((and (bolp) (not (looking-at "[ \t]*$")))
7741 (open-line 1))
7743 (goto-char (point-at-eol))
7744 (insert "\n")))
7746 ;; Insert the new heading
7747 (insert stars)
7748 (just-one-space)
7749 (insert initial-content)
7750 (when adjust-empty-lines
7751 (if (or (not blank)
7752 (and blank (not (org-previous-line-empty-p))))
7753 (org-N-empty-lines-before-current (if blank 1 0))))
7754 (run-hooks 'org-insert-heading-hook)))))))
7756 (defun org-N-empty-lines-before-current (N)
7757 "Make the number of empty lines before current exactly N.
7758 So this will delete or add empty lines."
7759 (save-excursion
7760 (goto-char (point-at-bol))
7761 (if (looking-back "\\s-+" nil 'greedy)
7762 (replace-match ""))
7763 (or (bobp) (insert "\n"))
7764 (while (> N 0)
7765 (insert "\n")
7766 (setq N (1- N)))))
7768 (defun org-get-heading (&optional no-tags no-todo)
7769 "Return the heading of the current entry, without the stars.
7770 When NO-TAGS is non-nil, don't include tags.
7771 When NO-TODO is non-nil, don't include TODO keywords."
7772 (save-excursion
7773 (org-back-to-heading t)
7774 (cond
7775 ((and no-tags no-todo)
7776 (looking-at org-complex-heading-regexp)
7777 (match-string 4))
7778 (no-tags
7779 (looking-at (concat org-outline-regexp
7780 "\\(.*?\\)"
7781 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7782 (match-string 1))
7783 (no-todo
7784 (looking-at org-todo-line-regexp)
7785 (match-string 3))
7786 (t (looking-at org-heading-regexp)
7787 (match-string 2)))))
7789 (defvar orgstruct-mode) ; defined below
7791 (defun org-heading-components ()
7792 "Return the components of the current heading.
7793 This is a list with the following elements:
7794 - the level as an integer
7795 - the reduced level, different if `org-odd-levels-only' is set.
7796 - the TODO keyword, or nil
7797 - the priority character, like ?A, or nil if no priority is given
7798 - the headline text itself, or the tags string if no headline text
7799 - the tags string, or nil."
7800 (save-excursion
7801 (org-back-to-heading t)
7802 (if (let (case-fold-search)
7803 (looking-at
7804 (if orgstruct-mode
7805 org-heading-regexp
7806 org-complex-heading-regexp)))
7807 (if orgstruct-mode
7808 (list (length (match-string 1))
7809 (org-reduced-level (length (match-string 1)))
7812 (match-string 2)
7813 nil)
7814 (list (length (match-string 1))
7815 (org-reduced-level (length (match-string 1)))
7816 (org-match-string-no-properties 2)
7817 (and (match-end 3) (aref (match-string 3) 2))
7818 (org-match-string-no-properties 4)
7819 (org-match-string-no-properties 5))))))
7821 (defun org-get-entry ()
7822 "Get the entry text, after heading, entire subtree."
7823 (save-excursion
7824 (org-back-to-heading t)
7825 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7827 (defun org-insert-heading-after-current ()
7828 "Insert a new heading with same level as current, after current subtree."
7829 (interactive)
7830 (org-back-to-heading)
7831 (org-insert-heading)
7832 (org-move-subtree-down)
7833 (end-of-line 1))
7835 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7836 "Insert heading with `org-insert-heading-respect-content' set to t."
7837 (interactive "P")
7838 (let ((org-insert-heading-respect-content t))
7839 (org-insert-heading '(4) invisible-ok)))
7841 (defun org-insert-todo-heading-respect-content (&optional force-state)
7842 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7843 (interactive "P")
7844 (let ((org-insert-heading-respect-content t))
7845 (org-insert-todo-heading force-state '(4))))
7847 (defun org-insert-todo-heading (arg &optional force-heading)
7848 "Insert a new heading with the same level and TODO state as current heading.
7849 If the heading has no TODO state, or if the state is DONE, use the first
7850 state (TODO by default). Also one prefix arg, force first state. With two
7851 prefix args, force inserting at the end of the parent subtree."
7852 (interactive "P")
7853 (when (or force-heading (not (org-insert-item 'checkbox)))
7854 (org-insert-heading (or (and (equal arg '(16)) '(16))
7855 force-heading))
7856 (save-excursion
7857 (org-back-to-heading)
7858 (outline-previous-heading)
7859 (looking-at org-todo-line-regexp))
7860 (let*
7861 ((new-mark-x
7862 (if (or arg
7863 (not (match-beginning 2))
7864 (member (match-string 2) org-done-keywords))
7865 (car org-todo-keywords-1)
7866 (match-string 2)))
7867 (new-mark
7869 (run-hook-with-args-until-success
7870 'org-todo-get-default-hook new-mark-x nil)
7871 new-mark-x)))
7872 (beginning-of-line 1)
7873 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7874 (if org-treat-insert-todo-heading-as-state-change
7875 (org-todo new-mark)
7876 (insert new-mark " "))))
7877 (when org-provide-todo-statistics
7878 (org-update-parent-todo-statistics))))
7880 (defun org-insert-subheading (arg)
7881 "Insert a new subheading and demote it.
7882 Works for outline headings and for plain lists alike."
7883 (interactive "P")
7884 (org-insert-heading arg)
7885 (cond
7886 ((org-at-heading-p) (org-do-demote))
7887 ((org-at-item-p) (org-indent-item))))
7889 (defun org-insert-todo-subheading (arg)
7890 "Insert a new subheading with TODO keyword or checkbox and demote it.
7891 Works for outline headings and for plain lists alike."
7892 (interactive "P")
7893 (org-insert-todo-heading arg)
7894 (cond
7895 ((org-at-heading-p) (org-do-demote))
7896 ((org-at-item-p) (org-indent-item))))
7898 ;;; Promotion and Demotion
7900 (defvar org-after-demote-entry-hook nil
7901 "Hook run after an entry has been demoted.
7902 The cursor will be at the beginning of the entry.
7903 When a subtree is being demoted, the hook will be called for each node.")
7905 (defvar org-after-promote-entry-hook nil
7906 "Hook run after an entry has been promoted.
7907 The cursor will be at the beginning of the entry.
7908 When a subtree is being promoted, the hook will be called for each node.")
7910 (defun org-promote-subtree ()
7911 "Promote the entire subtree.
7912 See also `org-promote'."
7913 (interactive)
7914 (save-excursion
7915 (org-with-limited-levels (org-map-tree 'org-promote)))
7916 (org-fix-position-after-promote))
7918 (defun org-demote-subtree ()
7919 "Demote the entire subtree. See `org-demote'.
7920 See also `org-promote'."
7921 (interactive)
7922 (save-excursion
7923 (org-with-limited-levels (org-map-tree 'org-demote)))
7924 (org-fix-position-after-promote))
7927 (defun org-do-promote ()
7928 "Promote the current heading higher up the tree.
7929 If the region is active in `transient-mark-mode', promote all headings
7930 in the region."
7931 (interactive)
7932 (save-excursion
7933 (if (org-region-active-p)
7934 (org-map-region 'org-promote (region-beginning) (region-end))
7935 (org-promote)))
7936 (org-fix-position-after-promote))
7938 (defun org-do-demote ()
7939 "Demote the current heading lower down the tree.
7940 If the region is active in `transient-mark-mode', demote all headings
7941 in the region."
7942 (interactive)
7943 (save-excursion
7944 (if (org-region-active-p)
7945 (org-map-region 'org-demote (region-beginning) (region-end))
7946 (org-demote)))
7947 (org-fix-position-after-promote))
7949 (defun org-fix-position-after-promote ()
7950 "Make sure that after pro/demotion cursor position is right."
7951 (let ((pos (point)))
7952 (when (save-excursion
7953 (beginning-of-line 1)
7954 (looking-at org-todo-line-regexp)
7955 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7956 (cond ((eobp) (insert " "))
7957 ((eolp) (insert " "))
7958 ((equal (char-after) ?\ ) (forward-char 1))))))
7960 (defun org-current-level ()
7961 "Return the level of the current entry, or nil if before the first headline.
7962 The level is the number of stars at the beginning of the headline."
7963 (save-excursion
7964 (org-with-limited-levels
7965 (if (ignore-errors (org-back-to-heading t))
7966 (funcall outline-level)))))
7968 (defun org-get-previous-line-level ()
7969 "Return the outline depth of the last headline before the current line.
7970 Returns 0 for the first headline in the buffer, and nil if before the
7971 first headline."
7972 (let ((current-level (org-current-level))
7973 (prev-level (when (> (line-number-at-pos) 1)
7974 (save-excursion
7975 (beginning-of-line 0)
7976 (org-current-level)))))
7977 (cond ((null current-level) nil) ; Before first headline
7978 ((null prev-level) 0) ; At first headline
7979 (prev-level))))
7981 (defun org-reduced-level (l)
7982 "Compute the effective level of a heading.
7983 This takes into account the setting of `org-odd-levels-only'."
7984 (cond
7985 ((zerop l) 0)
7986 (org-odd-levels-only (1+ (floor (/ l 2))))
7987 (t l)))
7989 (defun org-level-increment ()
7990 "Return the number of stars that will be added or removed at a
7991 time to headlines when structure editing, based on the value of
7992 `org-odd-levels-only'."
7993 (if org-odd-levels-only 2 1))
7995 (defun org-get-valid-level (level &optional change)
7996 "Rectify a level change under the influence of `org-odd-levels-only'
7997 LEVEL is a current level, CHANGE is by how much the level should be
7998 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7999 even level numbers will become the next higher odd number."
8000 (if org-odd-levels-only
8001 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8002 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8003 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8004 (max 1 (+ level (or change 0)))))
8006 (if (boundp 'define-obsolete-function-alias)
8007 (if (or (featurep 'xemacs) (< emacs-major-version 23))
8008 (define-obsolete-function-alias 'org-get-legal-level
8009 'org-get-valid-level)
8010 (define-obsolete-function-alias 'org-get-legal-level
8011 'org-get-valid-level "23.1")))
8013 (defun org-promote ()
8014 "Promote the current heading higher up the tree.
8015 If the region is active in `transient-mark-mode', promote all headings
8016 in the region."
8017 (org-back-to-heading t)
8018 (let* ((level (save-match-data (funcall outline-level)))
8019 (after-change-functions (remove 'flyspell-after-change-function
8020 after-change-functions))
8021 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8022 (diff (abs (- level (length up-head) -1))))
8023 (cond ((and (= level 1) org-called-with-limited-levels
8024 org-allow-promoting-top-level-subtree)
8025 (replace-match "# " nil t))
8026 ((= level 1)
8027 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8028 (t (replace-match up-head nil t)))
8029 ;; Fixup tag positioning
8030 (unless (= level 1)
8031 (and org-auto-align-tags (org-set-tags nil t))
8032 (if org-adapt-indentation (org-fixup-indentation (- diff))))
8033 (run-hooks 'org-after-promote-entry-hook)))
8035 (defun org-demote ()
8036 "Demote the current heading lower down the tree.
8037 If the region is active in `transient-mark-mode', demote all headings
8038 in the region."
8039 (org-back-to-heading t)
8040 (let* ((level (save-match-data (funcall outline-level)))
8041 (after-change-functions (remove 'flyspell-after-change-function
8042 after-change-functions))
8043 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8044 (diff (abs (- level (length down-head) -1))))
8045 (replace-match down-head nil t)
8046 ;; Fixup tag positioning
8047 (and org-auto-align-tags (org-set-tags nil t))
8048 (if org-adapt-indentation (org-fixup-indentation diff))
8049 (run-hooks 'org-after-demote-entry-hook)))
8051 (defun org-cycle-level ()
8052 "Cycle the level of an empty headline through possible states.
8053 This goes first to child, then to parent, level, then up the hierarchy.
8054 After top level, it switches back to sibling level."
8055 (interactive)
8056 (let ((org-adapt-indentation nil))
8057 (when (org-point-at-end-of-empty-headline)
8058 (setq this-command 'org-cycle-level) ; Only needed for caching
8059 (let ((cur-level (org-current-level))
8060 (prev-level (org-get-previous-line-level)))
8061 (cond
8062 ;; If first headline in file, promote to top-level.
8063 ((= prev-level 0)
8064 (loop repeat (/ (- cur-level 1) (org-level-increment))
8065 do (org-do-promote)))
8066 ;; If same level as prev, demote one.
8067 ((= prev-level cur-level)
8068 (org-do-demote))
8069 ;; If parent is top-level, promote to top level if not already.
8070 ((= prev-level 1)
8071 (loop repeat (/ (- cur-level 1) (org-level-increment))
8072 do (org-do-promote)))
8073 ;; If top-level, return to prev-level.
8074 ((= cur-level 1)
8075 (loop repeat (/ (- prev-level 1) (org-level-increment))
8076 do (org-do-demote)))
8077 ;; If less than prev-level, promote one.
8078 ((< cur-level prev-level)
8079 (org-do-promote))
8080 ;; If deeper than prev-level, promote until higher than
8081 ;; prev-level.
8082 ((> cur-level prev-level)
8083 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8084 do (org-do-promote))))
8085 t))))
8087 (defun org-map-tree (fun)
8088 "Call FUN for every heading underneath the current one."
8089 (org-back-to-heading)
8090 (let ((level (funcall outline-level)))
8091 (save-excursion
8092 (funcall fun)
8093 (while (and (progn
8094 (outline-next-heading)
8095 (> (funcall outline-level) level))
8096 (not (eobp)))
8097 (funcall fun)))))
8099 (defun org-map-region (fun beg end)
8100 "Call FUN for every heading between BEG and END."
8101 (let ((org-ignore-region t))
8102 (save-excursion
8103 (setq end (copy-marker end))
8104 (goto-char beg)
8105 (if (and (re-search-forward org-outline-regexp-bol nil t)
8106 (< (point) end))
8107 (funcall fun))
8108 (while (and (progn
8109 (outline-next-heading)
8110 (< (point) end))
8111 (not (eobp)))
8112 (funcall fun)))))
8114 (defvar org-property-end-re) ; silence byte-compiler
8115 (defun org-fixup-indentation (diff)
8116 "Change the indentation in the current entry by DIFF.
8117 However, if any line in the current entry has no indentation, or if it
8118 would end up with no indentation after the change, nothing at all is done."
8119 (save-excursion
8120 (let ((end (save-excursion (outline-next-heading)
8121 (point-marker)))
8122 (prohibit (if (> diff 0)
8123 "^\\S-"
8124 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8125 col)
8126 (unless (save-excursion (end-of-line 1)
8127 (re-search-forward prohibit end t))
8128 (while (and (< (point) end)
8129 (re-search-forward "^[ \t]+" end t))
8130 (goto-char (match-end 0))
8131 (setq col (current-column))
8132 (if (< diff 0) (replace-match ""))
8133 (org-indent-to-column (+ diff col))))
8134 (move-marker end nil))))
8136 (defun org-convert-to-odd-levels ()
8137 "Convert an org-mode file with all levels allowed to one with odd levels.
8138 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8139 level 5 etc."
8140 (interactive)
8141 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8142 (let ((outline-level 'org-outline-level)
8143 (org-odd-levels-only nil) n)
8144 (save-excursion
8145 (goto-char (point-min))
8146 (while (re-search-forward "^\\*\\*+ " nil t)
8147 (setq n (- (length (match-string 0)) 2))
8148 (while (>= (setq n (1- n)) 0)
8149 (org-demote))
8150 (end-of-line 1))))))
8152 (defun org-convert-to-oddeven-levels ()
8153 "Convert an org-mode file with only odd levels to one with odd/even levels.
8154 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8155 file contains a section with an even level, conversion would
8156 destroy the structure of the file. An error is signaled in this
8157 case."
8158 (interactive)
8159 (goto-char (point-min))
8160 ;; First check if there are no even levels
8161 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8162 (org-show-context t)
8163 (error "Not all levels are odd in this file. Conversion not possible"))
8164 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8165 (let ((outline-regexp org-outline-regexp)
8166 (outline-level 'org-outline-level)
8167 (org-odd-levels-only nil) n)
8168 (save-excursion
8169 (goto-char (point-min))
8170 (while (re-search-forward "^\\*\\*+ " nil t)
8171 (setq n (/ (1- (length (match-string 0))) 2))
8172 (while (>= (setq n (1- n)) 0)
8173 (org-promote))
8174 (end-of-line 1))))))
8176 (defun org-tr-level (n)
8177 "Make N odd if required."
8178 (if org-odd-levels-only (1+ (/ n 2)) n))
8180 ;;; Vertical tree motion, cutting and pasting of subtrees
8182 (defun org-move-subtree-up (&optional arg)
8183 "Move the current subtree up past ARG headlines of the same level."
8184 (interactive "p")
8185 (org-move-subtree-down (- (prefix-numeric-value arg))))
8187 (defun org-move-subtree-down (&optional arg)
8188 "Move the current subtree down past ARG headlines of the same level."
8189 (interactive "p")
8190 (setq arg (prefix-numeric-value arg))
8191 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8192 'org-get-last-sibling))
8193 (ins-point (make-marker))
8194 (cnt (abs arg))
8195 (col (current-column))
8196 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8197 ;; Select the tree
8198 (org-back-to-heading)
8199 (setq beg0 (point))
8200 (save-excursion
8201 (setq ne-beg (org-back-over-empty-lines))
8202 (setq beg (point)))
8203 (save-match-data
8204 (save-excursion (outline-end-of-heading)
8205 (setq folded (outline-invisible-p)))
8206 (outline-end-of-subtree))
8207 (outline-next-heading)
8208 (setq ne-end (org-back-over-empty-lines))
8209 (setq end (point))
8210 (goto-char beg0)
8211 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8212 ;; include less whitespace
8213 (save-excursion
8214 (goto-char beg)
8215 (forward-line (- ne-beg ne-end))
8216 (setq beg (point))))
8217 ;; Find insertion point, with error handling
8218 (while (> cnt 0)
8219 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8220 (progn (goto-char beg0)
8221 (user-error "Cannot move past superior level or buffer limit")))
8222 (setq cnt (1- cnt)))
8223 (if (> arg 0)
8224 ;; Moving forward - still need to move over subtree
8225 (progn (org-end-of-subtree t t)
8226 (save-excursion
8227 (org-back-over-empty-lines)
8228 (or (bolp) (newline)))))
8229 (setq ne-ins (org-back-over-empty-lines))
8230 (move-marker ins-point (point))
8231 (setq txt (buffer-substring beg end))
8232 (org-save-markers-in-region beg end)
8233 (delete-region beg end)
8234 (org-remove-empty-overlays-at beg)
8235 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8236 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8237 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8238 (let ((bbb (point)))
8239 (insert-before-markers txt)
8240 (org-reinstall-markers-in-region bbb)
8241 (move-marker ins-point bbb))
8242 (or (bolp) (insert "\n"))
8243 (setq ins-end (point))
8244 (goto-char ins-point)
8245 (org-skip-whitespace)
8246 (when (and (< arg 0)
8247 (org-first-sibling-p)
8248 (> ne-ins ne-beg))
8249 ;; Move whitespace back to beginning
8250 (save-excursion
8251 (goto-char ins-end)
8252 (let ((kill-whole-line t))
8253 (kill-line (- ne-ins ne-beg)) (point)))
8254 (insert (make-string (- ne-ins ne-beg) ?\n)))
8255 (move-marker ins-point nil)
8256 (if folded
8257 (hide-subtree)
8258 (org-show-entry)
8259 (show-children)
8260 (org-cycle-hide-drawers 'children))
8261 (org-clean-visibility-after-subtree-move)
8262 ;; move back to the initial column we were at
8263 (move-to-column col)))
8265 (defvar org-subtree-clip ""
8266 "Clipboard for cut and paste of subtrees.
8267 This is actually only a copy of the kill, because we use the normal kill
8268 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8270 (defvar org-subtree-clip-folded nil
8271 "Was the last copied subtree folded?
8272 This is used to fold the tree back after pasting.")
8274 (defun org-cut-subtree (&optional n)
8275 "Cut the current subtree into the clipboard.
8276 With prefix arg N, cut this many sequential subtrees.
8277 This is a short-hand for marking the subtree and then cutting it."
8278 (interactive "p")
8279 (org-copy-subtree n 'cut))
8281 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8282 "Copy the current subtree it in the clipboard.
8283 With prefix arg N, copy this many sequential subtrees.
8284 This is a short-hand for marking the subtree and then copying it.
8285 If CUT is non-nil, actually cut the subtree.
8286 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8287 of some markers in the region, even if CUT is non-nil. This is
8288 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8289 (interactive "p")
8290 (let (beg end folded (beg0 (point)))
8291 (if (org-called-interactively-p 'any)
8292 (org-back-to-heading nil) ; take what looks like a subtree
8293 (org-back-to-heading t)) ; take what is really there
8294 (setq beg (point))
8295 (skip-chars-forward " \t\r\n")
8296 (save-match-data
8297 (if nosubtrees
8298 (outline-next-heading)
8299 (save-excursion (outline-end-of-heading)
8300 (setq folded (outline-invisible-p)))
8301 (condition-case nil
8302 (org-forward-heading-same-level (1- n) t)
8303 (error nil))
8304 (org-end-of-subtree t t)))
8305 (setq end (point))
8306 (goto-char beg0)
8307 (when (> end beg)
8308 (setq org-subtree-clip-folded folded)
8309 (when (or cut force-store-markers)
8310 (org-save-markers-in-region beg end))
8311 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8312 (setq org-subtree-clip (current-kill 0))
8313 (message "%s: Subtree(s) with %d characters"
8314 (if cut "Cut" "Copied")
8315 (length org-subtree-clip)))))
8317 (defun org-paste-subtree (&optional level tree for-yank)
8318 "Paste the clipboard as a subtree, with modification of headline level.
8319 The entire subtree is promoted or demoted in order to match a new headline
8320 level.
8322 If the cursor is at the beginning of a headline, the same level as
8323 that headline is used to paste the tree.
8325 If not, the new level is derived from the *visible* headings
8326 before and after the insertion point, and taken to be the inferior headline
8327 level of the two. So if the previous visible heading is level 3 and the
8328 next is level 4 (or vice versa), level 4 will be used for insertion.
8329 This makes sure that the subtree remains an independent subtree and does
8330 not swallow low level entries.
8332 You can also force a different level, either by using a numeric prefix
8333 argument, or by inserting the heading marker by hand. For example, if the
8334 cursor is after \"*****\", then the tree will be shifted to level 5.
8336 If optional TREE is given, use this text instead of the kill ring.
8338 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8339 move back over whitespace before inserting, and move point to the end of
8340 the inserted text when done."
8341 (interactive "P")
8342 (setq tree (or tree (and kill-ring (current-kill 0))))
8343 (unless (org-kill-is-subtree-p tree)
8344 (user-error "%s"
8345 (substitute-command-keys
8346 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8347 (org-with-limited-levels
8348 (let* ((visp (not (outline-invisible-p)))
8349 (txt tree)
8350 (^re_ "\\(\\*+\\)[ \t]*")
8351 (old-level (if (string-match org-outline-regexp-bol txt)
8352 (- (match-end 0) (match-beginning 0) 1)
8353 -1))
8354 (force-level (cond (level (prefix-numeric-value level))
8355 ((and (looking-at "[ \t]*$")
8356 (string-match
8357 "^\\*+$" (buffer-substring
8358 (point-at-bol) (point))))
8359 (- (match-end 1) (match-beginning 1)))
8360 ((and (bolp)
8361 (looking-at org-outline-regexp))
8362 (- (match-end 0) (point) 1))))
8363 (previous-level (save-excursion
8364 (condition-case nil
8365 (progn
8366 (outline-previous-visible-heading 1)
8367 (if (looking-at ^re_)
8368 (- (match-end 0) (match-beginning 0) 1)
8370 (error 1))))
8371 (next-level (save-excursion
8372 (condition-case nil
8373 (progn
8374 (or (looking-at org-outline-regexp)
8375 (outline-next-visible-heading 1))
8376 (if (looking-at ^re_)
8377 (- (match-end 0) (match-beginning 0) 1)
8379 (error 1))))
8380 (new-level (or force-level (max previous-level next-level)))
8381 (shift (if (or (= old-level -1)
8382 (= new-level -1)
8383 (= old-level new-level))
8385 (- new-level old-level)))
8386 (delta (if (> shift 0) -1 1))
8387 (func (if (> shift 0) 'org-demote 'org-promote))
8388 (org-odd-levels-only nil)
8389 beg end newend)
8390 ;; Remove the forced level indicator
8391 (if force-level
8392 (delete-region (point-at-bol) (point)))
8393 ;; Paste
8394 (beginning-of-line (if (bolp) 1 2))
8395 (setq beg (point))
8396 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8397 (insert-before-markers txt)
8398 (unless (string-match "\n\\'" txt) (insert "\n"))
8399 (setq newend (point))
8400 (org-reinstall-markers-in-region beg)
8401 (setq end (point))
8402 (goto-char beg)
8403 (skip-chars-forward " \t\n\r")
8404 (setq beg (point))
8405 (if (and (outline-invisible-p) visp)
8406 (save-excursion (outline-show-heading)))
8407 ;; Shift if necessary
8408 (unless (= shift 0)
8409 (save-restriction
8410 (narrow-to-region beg end)
8411 (while (not (= shift 0))
8412 (org-map-region func (point-min) (point-max))
8413 (setq shift (+ delta shift)))
8414 (goto-char (point-min))
8415 (setq newend (point-max))))
8416 (when (or (org-called-interactively-p 'interactive) for-yank)
8417 (message "Clipboard pasted as level %d subtree" new-level))
8418 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8419 kill-ring
8420 (eq org-subtree-clip (current-kill 0))
8421 org-subtree-clip-folded)
8422 ;; The tree was folded before it was killed/copied
8423 (hide-subtree))
8424 (and for-yank (goto-char newend)))))
8426 (defun org-kill-is-subtree-p (&optional txt)
8427 "Check if the current kill is an outline subtree, or a set of trees.
8428 Returns nil if kill does not start with a headline, or if the first
8429 headline level is not the largest headline level in the tree.
8430 So this will actually accept several entries of equal levels as well,
8431 which is OK for `org-paste-subtree'.
8432 If optional TXT is given, check this string instead of the current kill."
8433 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8434 (re (org-get-limited-outline-regexp))
8435 (^re (concat "^" re))
8436 (start-level (and kill
8437 (string-match
8438 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8439 kill)
8440 (- (match-end 2) (match-beginning 2) 1)))
8441 (start (1+ (or (match-beginning 2) -1))))
8442 (if (not start-level)
8443 (progn
8444 nil) ;; does not even start with a heading
8445 (catch 'exit
8446 (while (setq start (string-match ^re kill (1+ start)))
8447 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8448 (throw 'exit nil)))
8449 t))))
8451 (defvar org-markers-to-move nil
8452 "Markers that should be moved with a cut-and-paste operation.
8453 Those markers are stored together with their positions relative to
8454 the start of the region.")
8456 (defun org-save-markers-in-region (beg end)
8457 "Check markers in region.
8458 If these markers are between BEG and END, record their position relative
8459 to BEG, so that after moving the block of text, we can put the markers back
8460 into place.
8461 This function gets called just before an entry or tree gets cut from the
8462 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8463 called immediately, to move the markers with the entries."
8464 (setq org-markers-to-move nil)
8465 (when (featurep 'org-clock)
8466 (org-clock-save-markers-for-cut-and-paste beg end))
8467 (when (featurep 'org-agenda)
8468 (org-agenda-save-markers-for-cut-and-paste beg end)))
8470 (defun org-check-and-save-marker (marker beg end)
8471 "Check if MARKER is between BEG and END.
8472 If yes, remember the marker and the distance to BEG."
8473 (when (and (marker-buffer marker)
8474 (equal (marker-buffer marker) (current-buffer)))
8475 (if (and (>= marker beg) (< marker end))
8476 (push (cons marker (- marker beg)) org-markers-to-move))))
8478 (defun org-reinstall-markers-in-region (beg)
8479 "Move all remembered markers to their position relative to BEG."
8480 (mapc (lambda (x)
8481 (move-marker (car x) (+ beg (cdr x))))
8482 org-markers-to-move)
8483 (setq org-markers-to-move nil))
8485 (defun org-narrow-to-subtree ()
8486 "Narrow buffer to the current subtree."
8487 (interactive)
8488 (save-excursion
8489 (save-match-data
8490 (org-with-limited-levels
8491 (narrow-to-region
8492 (progn (org-back-to-heading t) (point))
8493 (progn (org-end-of-subtree t t)
8494 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8495 (point)))))))
8497 (defun org-narrow-to-block ()
8498 "Narrow buffer to the current block."
8499 (interactive)
8500 (let* ((case-fold-search t)
8501 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8502 "^[ \t]*#\\+end_.*")))
8503 (if blockp
8504 (narrow-to-region (car blockp) (cdr blockp))
8505 (user-error "Not in a block"))))
8507 (eval-when-compile
8508 (defvar org-property-drawer-re))
8510 (defvar org-property-start-re) ;; defined below
8511 (defun org-clone-subtree-with-time-shift (n &optional shift)
8512 "Clone the task (subtree) at point N times.
8513 The clones will be inserted as siblings.
8515 In interactive use, the user will be prompted for the number of
8516 clones to be produced. If the entry has a timestamp, the user
8517 will also be prompted for a time shift, which may be a repeater
8518 as used in time stamps, for example `+3d'. To disable this,
8519 you can call the function with a universal prefix argument.
8521 When a valid repeater is given and the entry contains any time
8522 stamps, the clones will become a sequence in time, with time
8523 stamps in the subtree shifted for each clone produced. If SHIFT
8524 is nil or the empty string, time stamps will be left alone. The
8525 ID property of the original subtree is removed.
8527 If the original subtree did contain time stamps with a repeater,
8528 the following will happen:
8529 - the repeater will be removed in each clone
8530 - an additional clone will be produced, with the current, unshifted
8531 date(s) in the entry.
8532 - the original entry will be placed *after* all the clones, with
8533 repeater intact.
8534 - the start days in the repeater in the original entry will be shifted
8535 to past the last clone.
8536 In this way you can spell out a number of instances of a repeating task,
8537 and still retain the repeater to cover future instances of the task."
8538 (interactive "nNumber of clones to produce: ")
8539 (let ((shift
8540 (or shift
8541 (if (and (not (equal current-prefix-arg '(4)))
8542 (save-excursion
8543 (re-search-forward org-ts-regexp-both
8544 (save-excursion
8545 (org-end-of-subtree t)
8546 (point)) t)))
8547 (read-from-minibuffer
8548 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8549 ""))) ;; No time shift
8550 (n-no-remove -1)
8551 (drawer-re org-drawer-regexp)
8552 beg end template task idprop
8553 shift-n shift-what doshift nmin nmax)
8554 (if (not (and (integerp n) (> n 0)))
8555 (error "Invalid number of replications %s" n))
8556 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8557 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8558 shift)))
8559 (error "Invalid shift specification %s" shift))
8560 (when doshift
8561 (setq shift-n (string-to-number (match-string 1 shift))
8562 shift-what (cdr (assoc (match-string 2 shift)
8563 '(("d" . day) ("w" . week)
8564 ("m" . month) ("y" . year))))))
8565 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8566 (setq nmin 1 nmax n)
8567 (org-back-to-heading t)
8568 (setq beg (point))
8569 (setq idprop (org-entry-get nil "ID"))
8570 (org-end-of-subtree t t)
8571 (or (bolp) (insert "\n"))
8572 (setq end (point))
8573 (setq template (buffer-substring beg end))
8574 (when (and doshift
8575 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8576 (delete-region beg end)
8577 (setq end beg)
8578 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8579 (goto-char end)
8580 (loop for n from nmin to nmax do
8581 ;; prepare clone
8582 (with-temp-buffer
8583 (insert template)
8584 (org-mode)
8585 (goto-char (point-min))
8586 (org-show-subtree)
8587 (and idprop (if org-clone-delete-id
8588 (org-entry-delete nil "ID")
8589 (org-id-get-create t)))
8590 (unless (= n 0)
8591 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8592 (kill-whole-line))
8593 (goto-char (point-min))
8594 (while (re-search-forward drawer-re nil t)
8595 (org-remove-empty-drawer-at (point))))
8596 (goto-char (point-min))
8597 (when doshift
8598 (while (re-search-forward org-ts-regexp-both nil t)
8599 (org-timestamp-change (* n shift-n) shift-what))
8600 (unless (= n n-no-remove)
8601 (goto-char (point-min))
8602 (while (re-search-forward org-ts-regexp nil t)
8603 (save-excursion
8604 (goto-char (match-beginning 0))
8605 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8606 (delete-region (match-beginning 1) (match-end 1)))))))
8607 (setq task (buffer-string)))
8608 (insert task))
8609 (goto-char beg)))
8611 ;;; Outline Sorting
8613 (defun org-sort (with-case)
8614 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8615 Optional argument WITH-CASE means sort case-sensitively."
8616 (interactive "P")
8617 (cond
8618 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8619 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8621 (org-call-with-arg 'org-sort-entries with-case))))
8623 (defun org-sort-remove-invisible (s)
8624 "Remove invisible links from string S."
8625 (remove-text-properties 0 (length s) org-rm-props s)
8626 (while (string-match org-bracket-link-regexp s)
8627 (setq s (replace-match (if (match-end 2)
8628 (match-string 3 s)
8629 (match-string 1 s)) t t s)))
8630 (let ((st (format " %s " s)))
8631 (while (string-match org-emph-re st)
8632 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8633 (setq s (substring st 1 -1)))
8636 (defvar org-priority-regexp) ; defined later in the file
8638 (defvar org-after-sorting-entries-or-items-hook nil
8639 "Hook that is run after a bunch of entries or items have been sorted.
8640 When children are sorted, the cursor is in the parent line when this
8641 hook gets called. When a region or a plain list is sorted, the cursor
8642 will be in the first entry of the sorted region/list.")
8644 (defun org-sort-entries
8645 (&optional with-case sorting-type getkey-func compare-func property)
8646 "Sort entries on a certain level of an outline tree.
8647 If there is an active region, the entries in the region are sorted.
8648 Else, if the cursor is before the first entry, sort the top-level items.
8649 Else, the children of the entry at point are sorted.
8651 Sorting can be alphabetically, numerically, by date/time as given by
8652 a time stamp, by a property, by priority order, or by a custom function.
8654 The command prompts for the sorting type unless it has been given to the
8655 function through the SORTING-TYPE argument, which needs to be a character,
8656 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8657 precise meaning of each character:
8659 n Numerically, by converting the beginning of the entry/item to a number.
8660 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8661 o By order of TODO keywords.
8662 t By date/time, either the first active time stamp in the entry, or, if
8663 none exist, by the first inactive one.
8664 s By the scheduled date/time.
8665 d By deadline date/time.
8666 c By creation time, which is assumed to be the first inactive time stamp
8667 at the beginning of a line.
8668 p By priority according to the cookie.
8669 r By the value of a property.
8671 Capital letters will reverse the sort order.
8673 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8674 called with point at the beginning of the record. It must return either
8675 a string or a number that should serve as the sorting key for that record.
8677 Comparing entries ignores case by default. However, with an optional argument
8678 WITH-CASE, the sorting considers case as well.
8680 Sorting is done against the visible part of the headlines, it ignores hidden
8681 links.
8683 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
8684 (interactive "P")
8685 (let ((case-func (if with-case 'identity 'downcase))
8686 (cmstr
8687 ;; The clock marker is lost when using `sort-subr', let's
8688 ;; store the clocking string.
8689 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8690 (save-excursion
8691 (goto-char org-clock-marker)
8692 (looking-back "^.*") (match-string-no-properties 0))))
8693 start beg end stars re re2
8694 txt what tmp)
8695 ;; Find beginning and end of region to sort
8696 (cond
8697 ((org-region-active-p)
8698 ;; we will sort the region
8699 (setq end (region-end)
8700 what "region")
8701 (goto-char (region-beginning))
8702 (if (not (org-at-heading-p)) (outline-next-heading))
8703 (setq start (point)))
8704 ((or (org-at-heading-p)
8705 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8706 ;; we will sort the children of the current headline
8707 (org-back-to-heading)
8708 (setq start (point)
8709 end (progn (org-end-of-subtree t t)
8710 (or (bolp) (insert "\n"))
8711 (org-back-over-empty-lines)
8712 (point))
8713 what "children")
8714 (goto-char start)
8715 (show-subtree)
8716 (outline-next-heading))
8718 ;; we will sort the top-level entries in this file
8719 (goto-char (point-min))
8720 (or (org-at-heading-p) (outline-next-heading))
8721 (setq start (point))
8722 (goto-char (point-max))
8723 (beginning-of-line 1)
8724 (when (looking-at ".*?\\S-")
8725 ;; File ends in a non-white line
8726 (end-of-line 1)
8727 (insert "\n"))
8728 (setq end (point-max))
8729 (setq what "top-level")
8730 (goto-char start)
8731 (show-all)))
8733 (setq beg (point))
8734 (if (>= beg end) (user-error "Nothing to sort"))
8736 (looking-at "\\(\\*+\\)")
8737 (setq stars (match-string 1)
8738 re (concat "^" (regexp-quote stars) " +")
8739 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8740 txt (buffer-substring beg end))
8741 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8742 (if (and (not (equal stars "*")) (string-match re2 txt))
8743 (user-error "Region to sort contains a level above the first entry"))
8745 (unless sorting-type
8746 (message
8747 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8748 [t]ime [s]cheduled [d]eadline [c]reated
8749 A/N/P/R/O/F/T/S/D/C means reversed:"
8750 what)
8751 (setq sorting-type (read-char-exclusive))
8753 (unless getkey-func
8754 (and (= (downcase sorting-type) ?f)
8755 (setq getkey-func
8756 (org-icompleting-read "Sort using function: "
8757 obarray 'fboundp t nil nil))
8758 (setq getkey-func (intern getkey-func))))
8760 (and (= (downcase sorting-type) ?r)
8761 (not property)
8762 (setq property
8763 (org-icompleting-read "Property: "
8764 (mapcar 'list (org-buffer-property-keys t))
8765 nil t))))
8767 (message "Sorting entries...")
8769 (save-restriction
8770 (narrow-to-region start end)
8771 (let ((dcst (downcase sorting-type))
8772 (case-fold-search nil)
8773 (now (current-time)))
8774 (sort-subr
8775 (/= dcst sorting-type)
8776 ;; This function moves to the beginning character of the "record" to
8777 ;; be sorted.
8778 (lambda nil
8779 (if (re-search-forward re nil t)
8780 (goto-char (match-beginning 0))
8781 (goto-char (point-max))))
8782 ;; This function moves to the last character of the "record" being
8783 ;; sorted.
8784 (lambda nil
8785 (save-match-data
8786 (condition-case nil
8787 (outline-forward-same-level 1)
8788 (error
8789 (goto-char (point-max))))))
8790 ;; This function returns the value that gets sorted against.
8791 (lambda nil
8792 (cond
8793 ((= dcst ?n)
8794 (if (looking-at org-complex-heading-regexp)
8795 (string-to-number (org-sort-remove-invisible (match-string 4)))
8796 nil))
8797 ((= dcst ?a)
8798 (if (looking-at org-complex-heading-regexp)
8799 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8800 nil))
8801 ((= dcst ?t)
8802 (let ((end (save-excursion (outline-next-heading) (point))))
8803 (if (or (re-search-forward org-ts-regexp end t)
8804 (re-search-forward org-ts-regexp-both end t))
8805 (org-time-string-to-seconds (match-string 0))
8806 (org-float-time now))))
8807 ((= dcst ?c)
8808 (let ((end (save-excursion (outline-next-heading) (point))))
8809 (if (re-search-forward
8810 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8811 end t)
8812 (org-time-string-to-seconds (match-string 0))
8813 (org-float-time now))))
8814 ((= dcst ?s)
8815 (let ((end (save-excursion (outline-next-heading) (point))))
8816 (if (re-search-forward org-scheduled-time-regexp end t)
8817 (org-time-string-to-seconds (match-string 1))
8818 (org-float-time now))))
8819 ((= dcst ?d)
8820 (let ((end (save-excursion (outline-next-heading) (point))))
8821 (if (re-search-forward org-deadline-time-regexp end t)
8822 (org-time-string-to-seconds (match-string 1))
8823 (org-float-time now))))
8824 ((= dcst ?p)
8825 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8826 (string-to-char (match-string 2))
8827 org-default-priority))
8828 ((= dcst ?r)
8829 (or (org-entry-get nil property) ""))
8830 ((= dcst ?o)
8831 (if (looking-at org-complex-heading-regexp)
8832 (- 9999 (length (member (match-string 2)
8833 org-todo-keywords-1)))))
8834 ((= dcst ?f)
8835 (if getkey-func
8836 (progn
8837 (setq tmp (funcall getkey-func))
8838 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8839 tmp)
8840 (error "Invalid key function `%s'" getkey-func)))
8841 (t (error "Invalid sorting type `%c'" sorting-type))))
8843 (cond
8844 ((= dcst ?a) 'string<)
8845 ((= dcst ?f) compare-func)
8846 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8847 (run-hooks 'org-after-sorting-entries-or-items-hook)
8848 ;; Reset the clock marker if needed
8849 (when cmstr
8850 (save-excursion
8851 (goto-char start)
8852 (search-forward cmstr nil t)
8853 (move-marker org-clock-marker (point))))
8854 (message "Sorting entries...done")))
8856 (defun org-do-sort (table what &optional with-case sorting-type)
8857 "Sort TABLE of WHAT according to SORTING-TYPE.
8858 The user will be prompted for the SORTING-TYPE if the call to this
8859 function does not specify it. WHAT is only for the prompt, to indicate
8860 what is being sorted. The sorting key will be extracted from
8861 the car of the elements of the table.
8862 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8863 (unless sorting-type
8864 (message
8865 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8866 what)
8867 (setq sorting-type (read-char-exclusive)))
8868 (let ((dcst (downcase sorting-type))
8869 extractfun comparefun)
8870 ;; Define the appropriate functions
8871 (cond
8872 ((= dcst ?n)
8873 (setq extractfun 'string-to-number
8874 comparefun (if (= dcst sorting-type) '< '>)))
8875 ((= dcst ?a)
8876 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8877 (lambda(x) (downcase (org-sort-remove-invisible x))))
8878 comparefun (if (= dcst sorting-type)
8879 'string<
8880 (lambda (a b) (and (not (string< a b))
8881 (not (string= a b)))))))
8882 ((= dcst ?t)
8883 (setq extractfun
8884 (lambda (x)
8885 (if (or (string-match org-ts-regexp x)
8886 (string-match org-ts-regexp-both x))
8887 (org-float-time
8888 (org-time-string-to-time (match-string 0 x)))
8890 comparefun (if (= dcst sorting-type) '< '>)))
8891 (t (error "Invalid sorting type `%c'" sorting-type)))
8893 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8894 table)
8895 (lambda (a b) (funcall comparefun (car a) (car b))))))
8898 ;;; The orgstruct minor mode
8900 ;; Define a minor mode which can be used in other modes in order to
8901 ;; integrate the org-mode structure editing commands.
8903 ;; This is really a hack, because the org-mode structure commands use
8904 ;; keys which normally belong to the major mode. Here is how it
8905 ;; works: The minor mode defines all the keys necessary to operate the
8906 ;; structure commands, but wraps the commands into a function which
8907 ;; tests if the cursor is currently at a headline or a plain list
8908 ;; item. If that is the case, the structure command is used,
8909 ;; temporarily setting many Org-mode variables like regular
8910 ;; expressions for filling etc. However, when any of those keys is
8911 ;; used at a different location, function uses `key-binding' to look
8912 ;; up if the key has an associated command in another currently active
8913 ;; keymap (minor modes, major mode, global), and executes that
8914 ;; command. There might be problems if any of the keys is otherwise
8915 ;; used as a prefix key.
8917 (defcustom orgstruct-heading-prefix-regexp ""
8918 "Regexp that matches the custom prefix of Org headlines in
8919 orgstruct(++)-mode."
8920 :group 'org
8921 :version "24.4"
8922 :package-version '(Org . "8.3")
8923 :type 'regexp)
8924 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8926 (defcustom orgstruct-setup-hook nil
8927 "Hook run after orgstruct-mode-map is filled."
8928 :group 'org
8929 :version "24.4"
8930 :package-version '(Org . "8.0")
8931 :type 'hook)
8933 (defvar orgstruct-initialized nil)
8935 (defvar org-local-vars nil
8936 "List of local variables, for use by `orgstruct-mode'.")
8938 ;;;###autoload
8939 (define-minor-mode orgstruct-mode
8940 "Toggle the minor mode `orgstruct-mode'.
8941 This mode is for using Org-mode structure commands in other
8942 modes. The following keys behave as if Org-mode were active, if
8943 the cursor is on a headline, or on a plain list item (both as
8944 defined by Org-mode)."
8945 nil " OrgStruct" (make-sparse-keymap)
8946 (funcall (if orgstruct-mode
8947 'add-to-invisibility-spec
8948 'remove-from-invisibility-spec)
8949 '(outline . t))
8950 (when orgstruct-mode
8951 (org-load-modules-maybe)
8952 (unless orgstruct-initialized
8953 (orgstruct-setup)
8954 (setq orgstruct-initialized t))))
8956 ;;;###autoload
8957 (defun turn-on-orgstruct ()
8958 "Unconditionally turn on `orgstruct-mode'."
8959 (orgstruct-mode 1))
8961 (defvar org-fb-vars nil)
8962 (make-variable-buffer-local 'org-fb-vars)
8963 (defun orgstruct++-mode (&optional arg)
8964 "Toggle `orgstruct-mode', the enhanced version of it.
8965 In addition to setting orgstruct-mode, this also exports all
8966 indentation and autofilling variables from org-mode into the
8967 buffer. It will also recognize item context in multiline items."
8968 (interactive "P")
8969 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8970 (if (< arg 1)
8971 (progn (orgstruct-mode -1)
8972 (mapc (lambda(v)
8973 (org-set-local (car v)
8974 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8975 org-fb-vars))
8976 (orgstruct-mode 1)
8977 (setq org-fb-vars nil)
8978 (unless org-local-vars
8979 (setq org-local-vars (org-get-local-variables)))
8980 (let (var val)
8981 (mapc
8982 (lambda (x)
8983 (when (string-match
8984 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8985 (symbol-name (car x)))
8986 (setq var (car x) val (nth 1 x))
8987 (push (list var `(quote ,(eval var))) org-fb-vars)
8988 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8989 org-local-vars)
8990 (org-set-local 'orgstruct-is-++ t))))
8992 (defvar orgstruct-is-++ nil
8993 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8994 (make-variable-buffer-local 'orgstruct-is-++)
8996 ;;;###autoload
8997 (defun turn-on-orgstruct++ ()
8998 "Unconditionally turn on `orgstruct++-mode'."
8999 (orgstruct++-mode 1))
9001 (defun orgstruct-error ()
9002 "Error when there is no default binding for a structure key."
9003 (interactive)
9004 (funcall (if (fboundp 'user-error)
9005 'user-error
9006 'error)
9007 "This key has no function outside structure elements"))
9009 (defun orgstruct-setup ()
9010 "Setup orgstruct keymap."
9011 (dolist (cell '((org-demote . t)
9012 (org-metaleft . t)
9013 (org-metaright . t)
9014 (org-promote . t)
9015 (org-shiftmetaleft . t)
9016 (org-shiftmetaright . t)
9017 org-backward-element
9018 org-backward-heading-same-level
9019 org-ctrl-c-ret
9020 org-ctrl-c-minus
9021 org-ctrl-c-star
9022 org-cycle
9023 org-forward-heading-same-level
9024 org-insert-heading
9025 org-insert-heading-respect-content
9026 org-kill-note-or-show-branches
9027 org-mark-subtree
9028 org-meta-return
9029 org-metadown
9030 org-metaup
9031 org-narrow-to-subtree
9032 org-promote-subtree
9033 org-reveal
9034 org-shiftdown
9035 org-shiftleft
9036 org-shiftmetadown
9037 org-shiftmetaup
9038 org-shiftright
9039 org-shifttab
9040 org-shifttab
9041 org-shiftup
9042 org-show-subtree
9043 org-sort
9044 org-up-element
9045 outline-demote
9046 outline-next-visible-heading
9047 outline-previous-visible-heading
9048 outline-promote
9049 outline-up-heading
9050 show-children))
9051 (let ((f (or (car-safe cell) cell))
9052 (disable-when-heading-prefix (cdr-safe cell)))
9053 (when (fboundp f)
9054 (let ((new-bindings))
9055 (dolist (binding (nconc (where-is-internal f org-mode-map)
9056 (where-is-internal f outline-mode-map)))
9057 (push binding new-bindings)
9058 ;; TODO use local-function-key-map
9059 (dolist (rep '(("<tab>" . "TAB")
9060 ("<return>" . "RET")
9061 ("<escape>" . "ESC")
9062 ("<delete>" . "DEL")))
9063 (setq binding (read-kbd-macro
9064 (let ((case-fold-search))
9065 (replace-regexp-in-string
9066 (regexp-quote (cdr rep))
9067 (car rep)
9068 (key-description binding)))))
9069 (pushnew binding new-bindings :test 'equal)))
9070 (dolist (binding new-bindings)
9071 (let ((key (lookup-key orgstruct-mode-map binding)))
9072 (when (or (not key) (numberp key))
9073 (condition-case nil
9074 (org-defkey orgstruct-mode-map
9075 binding
9076 (orgstruct-make-binding f binding disable-when-heading-prefix))
9077 (error nil)))))))))
9078 (run-hooks 'orgstruct-setup-hook))
9080 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9081 "Create a function for binding in the structure minor mode.
9082 FUN is the command to call inside a table. KEY is the key that
9083 should be checked in for a command to execute outside of tables.
9084 Non-nil `disable-when-heading-prefix' means to disable the command
9085 if `orgstruct-heading-prefix-regexp' is not empty."
9086 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9087 (let ((nname name)
9088 (i 0))
9089 (while (fboundp (intern nname))
9090 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9091 (setq name (intern nname)))
9092 (eval
9093 (let ((bindings '((org-heading-regexp
9094 (concat "^"
9095 orgstruct-heading-prefix-regexp
9096 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9097 (org-outline-regexp
9098 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9099 (org-outline-regexp-bol
9100 (concat "^" org-outline-regexp))
9101 (outline-regexp org-outline-regexp)
9102 (outline-heading-end-regexp "\n")
9103 (outline-level 'org-outline-level)
9104 (outline-heading-alist))))
9105 `(defun ,name (arg)
9106 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9107 "Outside of structure, run the binding of `"
9108 (key-description key) "'."
9109 (when disable-when-heading-prefix
9110 (concat
9111 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9112 "back to the default binding due to limitations of Org's implementation of\n"
9113 "`" (symbol-name fun) "'.")))
9114 (interactive "p")
9115 (let* ((disable
9116 ,(and disable-when-heading-prefix
9117 '(not (string= orgstruct-heading-prefix-regexp ""))))
9118 (fallback
9119 (or disable
9120 (not
9121 (let* ,bindings
9122 (org-context-p 'headline 'item
9123 ,(when (memq fun
9124 '(org-insert-heading
9125 org-insert-heading-respect-content
9126 org-meta-return))
9127 '(when orgstruct-is-++
9128 'item-body))))))))
9129 (if fallback
9130 (let* ((orgstruct-mode)
9131 (binding
9132 (loop with key = ,key
9133 for rep in
9134 '(nil
9135 ("<\\([^>]*\\)tab>" . "\\1TAB")
9136 ("<\\([^>]*\\)return>" . "\\1RET")
9137 ("<\\([^>]*\\)escape>" . "\\1ESC")
9138 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9140 (when rep
9141 (setq key (read-kbd-macro
9142 (let ((case-fold-search))
9143 (replace-regexp-in-string
9144 (car rep)
9145 (cdr rep)
9146 (key-description key))))))
9147 thereis (key-binding key))))
9148 (if (keymapp binding)
9149 (set-temporary-overlay-map binding)
9150 (let ((func (or binding
9151 (unless disable
9152 'orgstruct-error))))
9153 (when func
9154 (call-interactively func)))))
9155 (org-run-like-in-org-mode
9156 (lambda ()
9157 (interactive)
9158 (let* ,bindings
9159 (call-interactively ',fun)))))))))
9160 name))
9162 (defun org-contextualize-keys (alist contexts)
9163 "Return valid elements in ALIST depending on CONTEXTS.
9165 `org-agenda-custom-commands' or `org-capture-templates' are the
9166 values used for ALIST, and `org-agenda-custom-commands-contexts'
9167 or `org-capture-templates-contexts' are the associated contexts
9168 definitions."
9169 (let ((contexts
9170 ;; normalize contexts
9171 (mapcar
9172 (lambda(c) (cond ((listp (cadr c))
9173 (list (car c) (car c) (cadr c)))
9174 ((string= "" (cadr c))
9175 (list (car c) (car c) (caddr c)))
9176 (t c))) contexts))
9177 (a alist) c r s)
9178 ;; loop over all commands or templates
9179 (while (setq c (pop a))
9180 (let (vrules repl)
9181 (cond
9182 ((not (assoc (car c) contexts))
9183 (push c r))
9184 ((and (assoc (car c) contexts)
9185 (setq vrules (org-contextualize-validate-key
9186 (car c) contexts)))
9187 (mapc (lambda (vr)
9188 (when (not (equal (car vr) (cadr vr)))
9189 (setq repl vr))) vrules)
9190 (if (not repl) (push c r)
9191 (push (cadr repl) s)
9192 (push
9193 (cons (car c)
9194 (cdr (or (assoc (cadr repl) alist)
9195 (error "Undefined key `%s' as contextual replacement for `%s'"
9196 (cadr repl) (car c)))))
9197 r))))))
9198 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9199 (delq
9201 (delete-dups
9202 (mapcar (lambda (x)
9203 (let ((tpl (car x)))
9204 (when (not (delq
9206 (mapcar (lambda(y)
9207 (equal y tpl)) s))) x)))
9208 (reverse r))))))
9210 (defun org-contextualize-validate-key (key contexts)
9211 "Check CONTEXTS for agenda or capture KEY."
9212 (let (r rr res)
9213 (while (setq r (pop contexts))
9214 (mapc
9215 (lambda (rr)
9216 (when
9217 (and (equal key (car r))
9218 (if (functionp rr) (funcall rr)
9219 (or (and (eq (car rr) 'in-file)
9220 (buffer-file-name)
9221 (string-match (cdr rr) (buffer-file-name)))
9222 (and (eq (car rr) 'in-mode)
9223 (string-match (cdr rr) (symbol-name major-mode)))
9224 (and (eq (car rr) 'in-buffer)
9225 (string-match (cdr rr) (buffer-name)))
9226 (when (and (eq (car rr) 'not-in-file)
9227 (buffer-file-name))
9228 (not (string-match (cdr rr) (buffer-file-name))))
9229 (when (eq (car rr) 'not-in-mode)
9230 (not (string-match (cdr rr) (symbol-name major-mode))))
9231 (when (eq (car rr) 'not-in-buffer)
9232 (not (string-match (cdr rr) (buffer-name)))))))
9233 (push r res)))
9234 (car (last r))))
9235 (delete-dups (delq nil res))))
9237 (defun org-context-p (&rest contexts)
9238 "Check if local context is any of CONTEXTS.
9239 Possible values in the list of contexts are `table', `headline', and `item'."
9240 (let ((pos (point)))
9241 (goto-char (point-at-bol))
9242 (prog1 (or (and (memq 'table contexts)
9243 (looking-at "[ \t]*|"))
9244 (and (memq 'headline contexts)
9245 (looking-at org-outline-regexp))
9246 (and (memq 'item contexts)
9247 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9248 (and (memq 'item-body contexts)
9249 (org-in-item-p)))
9250 (goto-char pos))))
9252 (defun org-get-local-variables ()
9253 "Return a list of all local variables in an Org mode buffer."
9254 (let (varlist)
9255 (with-current-buffer (get-buffer-create "*Org tmp*")
9256 (erase-buffer)
9257 (org-mode)
9258 (setq varlist (buffer-local-variables)))
9259 (kill-buffer "*Org tmp*")
9260 (delq nil
9261 (mapcar
9262 (lambda (x)
9263 (setq x
9264 (if (symbolp x)
9265 (list x)
9266 (list (car x) (cdr x))))
9267 (if (and (not (get (car x) 'org-state))
9268 (string-match
9269 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9270 (symbol-name (car x))))
9271 x nil))
9272 varlist))))
9274 (defun org-clone-local-variables (from-buffer &optional regexp)
9275 "Clone local variables from FROM-BUFFER.
9276 Optional argument REGEXP selects variables to clone."
9277 (mapc
9278 (lambda (pair)
9279 (and (symbolp (car pair))
9280 (or (null regexp)
9281 (string-match regexp (symbol-name (car pair))))
9282 (set (make-local-variable (car pair))
9283 (cdr pair))))
9284 (buffer-local-variables from-buffer)))
9286 ;;;###autoload
9287 (defun org-run-like-in-org-mode (cmd)
9288 "Run a command, pretending that the current buffer is in Org-mode.
9289 This will temporarily bind local variables that are typically bound in
9290 Org-mode to the values they have in Org-mode, and then interactively
9291 call CMD."
9292 (org-load-modules-maybe)
9293 (unless org-local-vars
9294 (setq org-local-vars (org-get-local-variables)))
9295 (let (binds)
9296 (dolist (var org-local-vars)
9297 (when (or (not (boundp (car var)))
9298 (eq (symbol-value (car var))
9299 (default-value (car var))))
9300 (push (list (car var) `(quote ,(cadr var))) binds)))
9301 (eval `(let ,binds
9302 (call-interactively (quote ,cmd))))))
9304 ;;;; Archiving
9306 (defun org-get-category (&optional pos force-refresh)
9307 "Get the category applying to position POS."
9308 (save-match-data
9309 (if force-refresh (org-refresh-category-properties))
9310 (let ((pos (or pos (point))))
9311 (or (get-text-property pos 'org-category)
9312 (progn (org-refresh-category-properties)
9313 (get-text-property pos 'org-category))))))
9315 (defun org-refresh-category-properties ()
9316 "Refresh category text properties in the buffer."
9317 (let ((case-fold-search t)
9318 (inhibit-read-only t)
9319 (def-cat (cond
9320 ((null org-category)
9321 (if buffer-file-name
9322 (file-name-sans-extension
9323 (file-name-nondirectory buffer-file-name))
9324 "???"))
9325 ((symbolp org-category) (symbol-name org-category))
9326 (t org-category)))
9327 beg end cat pos optionp)
9328 (org-with-silent-modifications
9329 (save-excursion
9330 (save-restriction
9331 (widen)
9332 (goto-char (point-min))
9333 (put-text-property (point) (point-max) 'org-category def-cat)
9334 (while (re-search-forward
9335 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9336 (setq pos (match-end 0)
9337 optionp (equal (char-after (match-beginning 0)) ?#)
9338 cat (org-trim (match-string 2)))
9339 (if optionp
9340 (setq beg (point-at-bol) end (point-max))
9341 (org-back-to-heading t)
9342 (setq beg (point) end (org-end-of-subtree t t)))
9343 (put-text-property beg end 'org-category cat)
9344 (put-text-property beg end 'org-category-position beg)
9345 (goto-char pos)))))))
9347 (defun org-refresh-properties (dprop tprop)
9348 "Refresh buffer text properties.
9349 DPROP is the drawer property and TPROP is the corresponding text
9350 property to set."
9351 (let ((case-fold-search t)
9352 (inhibit-read-only t) p)
9353 (org-with-silent-modifications
9354 (save-excursion
9355 (save-restriction
9356 (widen)
9357 (goto-char (point-min))
9358 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9359 (setq p (org-match-string-no-properties 1))
9360 (save-excursion
9361 (org-back-to-heading t)
9362 (put-text-property
9363 (point-at-bol) (org-end-of-subtree t t) tprop p))))))))
9366 ;;;; Link Stuff
9368 ;;; Link abbreviations
9370 (defun org-link-expand-abbrev (link)
9371 "Apply replacements as defined in `org-link-abbrev-alist'."
9372 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9373 (let* ((key (match-string 1 link))
9374 (as (or (assoc key org-link-abbrev-alist-local)
9375 (assoc key org-link-abbrev-alist)))
9376 (tag (and (match-end 2) (match-string 3 link)))
9377 rpl)
9378 (if (not as)
9379 link
9380 (setq rpl (cdr as))
9381 (cond
9382 ((symbolp rpl) (funcall rpl tag))
9383 ((string-match "%(\\([^)]+\\))" rpl)
9384 (replace-match
9385 (save-match-data
9386 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9387 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9388 ((string-match "%h" rpl)
9389 (replace-match (url-hexify-string (or tag "")) t t rpl))
9390 (t (concat rpl tag)))))
9391 link))
9393 ;;; Storing and inserting links
9395 (defvar org-insert-link-history nil
9396 "Minibuffer history for links inserted with `org-insert-link'.")
9398 (defvar org-stored-links nil
9399 "Contains the links stored with `org-store-link'.")
9401 (defvar org-store-link-plist nil
9402 "Plist with info about the most recently link created with `org-store-link'.")
9404 (defvar org-link-protocols nil
9405 "Link protocols added to Org-mode using `org-add-link-type'.")
9407 (defvar org-store-link-functions nil
9408 "List of functions that are called to create and store a link.
9409 Each function will be called in turn until one returns a non-nil
9410 value. Each function should check if it is responsible for creating
9411 this link (for example by looking at the major mode).
9412 If not, it must exit and return nil.
9413 If yes, it should return a non-nil value after a calling
9414 `org-store-link-props' with a list of properties and values.
9415 Special properties are:
9417 :type The link prefix, like \"http\". This must be given.
9418 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9419 This is obligatory as well.
9420 :description Optional default description for the second pair
9421 of brackets in an Org-mode link. The user can still change
9422 this when inserting this link into an Org-mode buffer.
9424 In addition to these, any additional properties can be specified
9425 and then used in capture templates.")
9427 (defun org-add-link-type (type &optional follow export)
9428 "Add TYPE to the list of `org-link-types'.
9429 Re-compute all regular expressions depending on `org-link-types'
9431 FOLLOW and EXPORT are two functions.
9433 FOLLOW should take the link path as the single argument and do whatever
9434 is necessary to follow the link, for example find a file or display
9435 a mail message.
9437 EXPORT should format the link path for export to one of the export formats.
9438 It should be a function accepting three arguments:
9440 path the path of the link, the text after the prefix (like \"http:\")
9441 desc the description of the link, if any, or a description added by
9442 org-export-normalize-links if there is none
9443 format the export format, a symbol like `html' or `latex' or `ascii'..
9445 The function may use the FORMAT information to return different values
9446 depending on the format. The return value will be put literally into
9447 the exported file. If the return value is nil, this means Org should
9448 do what it normally does with links which do not have EXPORT defined.
9450 Org-mode has a built-in default for exporting links. If you are happy with
9451 this default, there is no need to define an export function for the link
9452 type. For a simple example of an export function, see `org-bbdb.el'."
9453 (add-to-list 'org-link-types type t)
9454 (org-make-link-regexps)
9455 (if (assoc type org-link-protocols)
9456 (setcdr (assoc type org-link-protocols) (list follow export))
9457 (push (list type follow export) org-link-protocols)))
9459 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9460 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9462 ;;;###autoload
9463 (defun org-store-link (arg)
9464 "\\<org-mode-map>Store an org-link to the current location.
9465 This link is added to `org-stored-links' and can later be inserted
9466 into an org-buffer with \\[org-insert-link].
9468 For some link types, a prefix arg is interpreted.
9469 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9470 For file links, arg negates `org-context-in-file-links'.
9472 A double prefix arg force skipping storing functions that are not
9473 part of Org's core.
9475 A triple prefix arg force storing a link for each line in the
9476 active region."
9477 (interactive "P")
9478 (org-load-modules-maybe)
9479 (if (and (equal arg '(64)) (org-region-active-p))
9480 (save-excursion
9481 (let ((end (region-end)))
9482 (goto-char (region-beginning))
9483 (set-mark (point))
9484 (while (< (point-at-eol) end)
9485 (move-end-of-line 1) (activate-mark)
9486 (let (current-prefix-arg)
9487 (call-interactively 'org-store-link))
9488 (move-beginning-of-line 2)
9489 (set-mark (point)))))
9490 (org-with-limited-levels
9491 (setq org-store-link-plist nil)
9492 (let (link cpltxt desc description search
9493 txt custom-id agenda-link sfuns sfunsn)
9494 (cond
9496 ;; Store a link using an external link type
9497 ((and (not (equal arg '(16)))
9498 (setq sfuns
9499 (delq
9500 nil (mapcar (lambda (f)
9501 (let (fs) (if (funcall f) (push f fs))))
9502 org-store-link-functions))
9503 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9504 (or (and (cdr sfuns)
9505 (funcall (intern
9506 (completing-read
9507 "Which function for creating the link? "
9508 sfunsn t (car sfunsn)))))
9509 (funcall (caar sfuns)))
9510 (setq link (plist-get org-store-link-plist :link)
9511 desc (or (plist-get org-store-link-plist
9512 :description) link))))
9514 ;; Store a link from a source code buffer
9515 ((org-src-edit-buffer-p)
9516 (let (label gc)
9517 (while (or (not label)
9518 (save-excursion
9519 (save-restriction
9520 (widen)
9521 (goto-char (point-min))
9522 (re-search-forward
9523 (regexp-quote (format org-coderef-label-format label))
9524 nil t))))
9525 (when label (message "Label exists already") (sit-for 2))
9526 (setq label (read-string "Code line label: " label)))
9527 (end-of-line 1)
9528 (setq link (format org-coderef-label-format label))
9529 (setq gc (- 79 (length link)))
9530 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9531 (insert link)
9532 (setq link (concat "(" label ")") desc nil)))
9534 ;; We are in the agenda, link to referenced location
9535 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9536 (let ((m (or (get-text-property (point) 'org-hd-marker)
9537 (get-text-property (point) 'org-marker))))
9538 (when m
9539 (org-with-point-at m
9540 (setq agenda-link
9541 (if (org-called-interactively-p 'any)
9542 (call-interactively 'org-store-link)
9543 (org-store-link nil)))))))
9545 ((eq major-mode 'calendar-mode)
9546 (let ((cd (calendar-cursor-to-date)))
9547 (setq link
9548 (format-time-string
9549 (car org-time-stamp-formats)
9550 (apply 'encode-time
9551 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9552 nil nil nil))))
9553 (org-store-link-props :type "calendar" :date cd)))
9555 ((eq major-mode 'help-mode)
9556 (setq link (concat "help:" (save-excursion
9557 (goto-char (point-min))
9558 (looking-at "^[^ ]+")
9559 (match-string 0))))
9560 (org-store-link-props :type "help"))
9562 ((eq major-mode 'w3-mode)
9563 (setq cpltxt (if (and (buffer-name)
9564 (not (string-match "Untitled" (buffer-name))))
9565 (buffer-name)
9566 (url-view-url t))
9567 link (url-view-url t))
9568 (org-store-link-props :type "w3" :url (url-view-url t)))
9570 ((eq major-mode 'image-mode)
9571 (setq cpltxt (concat "file:"
9572 (abbreviate-file-name buffer-file-name))
9573 link cpltxt)
9574 (org-store-link-props :type "image" :file buffer-file-name))
9576 ;; In dired, store a link to the file of the current line
9577 ((eq major-mode 'dired-mode)
9578 (let ((file (dired-get-filename nil t)))
9579 (setq file (if file
9580 (abbreviate-file-name
9581 (expand-file-name (dired-get-filename nil t)))
9582 ;; otherwise, no file so use current directory.
9583 default-directory))
9584 (setq cpltxt (concat "file:" file)
9585 link cpltxt)))
9587 ((setq search (run-hook-with-args-until-success
9588 'org-create-file-search-functions))
9589 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9590 "::" search))
9591 (setq cpltxt (or description link)))
9593 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9594 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9595 (cond
9596 ;; Store a link using the target at point
9597 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9598 (setq cpltxt
9599 (concat "file:"
9600 (abbreviate-file-name
9601 (buffer-file-name (buffer-base-buffer)))
9602 "::" (match-string 1))
9603 link cpltxt))
9604 ((and (featurep 'org-id)
9605 (or (eq org-id-link-to-org-use-id t)
9606 (and (org-called-interactively-p 'any)
9607 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9608 (and (eq org-id-link-to-org-use-id
9609 'create-if-interactive-and-no-custom-id)
9610 (not custom-id))))
9611 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9612 ;; Store a link using the ID at point
9613 (setq link (condition-case nil
9614 (prog1 (org-id-store-link)
9615 (setq desc (plist-get org-store-link-plist
9616 :description)))
9617 (error
9618 ;; Probably before first headline, link only to file
9619 (concat "file:"
9620 (abbreviate-file-name
9621 (buffer-file-name (buffer-base-buffer))))))))
9623 ;; Just link to current headline
9624 (setq cpltxt (concat "file:"
9625 (abbreviate-file-name
9626 (buffer-file-name (buffer-base-buffer)))))
9627 ;; Add a context search string
9628 (when (org-xor org-context-in-file-links arg)
9629 (let* ((ee (org-element-at-point))
9630 (et (org-element-type ee))
9631 (ev (plist-get (cadr ee) :value))
9632 (ek (plist-get (cadr ee) :key))
9633 (eok (and (stringp ek) (string-match "name" ek))))
9634 (setq txt (cond
9635 ((org-at-heading-p) nil)
9636 ((and (eq et 'keyword) eok) ev)
9637 ((org-region-active-p)
9638 (buffer-substring (region-beginning) (region-end)))))
9639 (when (or (null txt) (string-match "\\S-" txt))
9640 (setq cpltxt
9641 (concat cpltxt "::"
9642 (condition-case nil
9643 (org-make-org-heading-search-string txt)
9644 (error "")))
9645 desc (or (and (eq et 'keyword) eok ev)
9646 (nth 4 (ignore-errors (org-heading-components)))
9647 "NONE")))))
9648 (if (string-match "::\\'" cpltxt)
9649 (setq cpltxt (substring cpltxt 0 -2)))
9650 (setq link cpltxt))))
9652 ((buffer-file-name (buffer-base-buffer))
9653 ;; Just link to this file here.
9654 (setq cpltxt (concat "file:"
9655 (abbreviate-file-name
9656 (buffer-file-name (buffer-base-buffer)))))
9657 ;; Add a context string.
9658 (when (org-xor org-context-in-file-links arg)
9659 (setq txt (if (org-region-active-p)
9660 (buffer-substring (region-beginning) (region-end))
9661 (buffer-substring (point-at-bol) (point-at-eol))))
9662 ;; Only use search option if there is some text.
9663 (when (string-match "\\S-" txt)
9664 (setq cpltxt
9665 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9666 desc "NONE")))
9667 (setq link cpltxt))
9669 ((org-called-interactively-p 'interactive)
9670 (user-error "No method for storing a link from this buffer"))
9672 (t (setq link nil)))
9674 ;; We're done setting link and desc, clean up
9675 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9676 (setq link (or link cpltxt)
9677 desc (or desc cpltxt))
9678 (cond ((equal desc "NONE") (setq desc nil))
9679 ((string-match org-bracket-link-analytic-regexp desc)
9680 (let ((d0 (match-string 3 desc))
9681 (p0 (match-string 5 desc)))
9682 (setq desc
9683 (replace-regexp-in-string
9684 org-bracket-link-regexp
9685 (concat (or p0 d0)
9686 (if (equal (length (match-string 0 desc))
9687 (length desc)) "*" "")) desc)))))
9689 ;; Return the link
9690 (if (not (and (or (org-called-interactively-p 'any)
9691 executing-kbd-macro) link))
9692 (or agenda-link (and link (org-make-link-string link desc)))
9693 (push (list link desc) org-stored-links)
9694 (message "Stored: %s" (or desc link))
9695 (when custom-id
9696 (setq link (concat "file:" (abbreviate-file-name
9697 (buffer-file-name)) "::#" custom-id))
9698 (push (list link desc) org-stored-links)))))))
9700 (defun org-store-link-props (&rest plist)
9701 "Store link properties, extract names and addresses."
9702 (let (x adr)
9703 (when (setq x (plist-get plist :from))
9704 (setq adr (mail-extract-address-components x))
9705 (setq plist (plist-put plist :fromname (car adr)))
9706 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9707 (when (setq x (plist-get plist :to))
9708 (setq adr (mail-extract-address-components x))
9709 (setq plist (plist-put plist :toname (car adr)))
9710 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9711 (let ((from (plist-get plist :from))
9712 (to (plist-get plist :to)))
9713 (when (and from to org-from-is-user-regexp)
9714 (setq plist
9715 (plist-put plist :fromto
9716 (if (string-match org-from-is-user-regexp from)
9717 (concat "to %t")
9718 (concat "from %f"))))))
9719 (setq org-store-link-plist plist))
9721 (defun org-add-link-props (&rest plist)
9722 "Add these properties to the link property list."
9723 (let (key value)
9724 (while plist
9725 (setq key (pop plist) value (pop plist))
9726 (setq org-store-link-plist
9727 (plist-put org-store-link-plist key value)))))
9729 (defun org-email-link-description (&optional fmt)
9730 "Return the description part of an email link.
9731 This takes information from `org-store-link-plist' and formats it
9732 according to FMT (default from `org-email-link-description-format')."
9733 (setq fmt (or fmt org-email-link-description-format))
9734 (let* ((p org-store-link-plist)
9735 (to (plist-get p :toaddress))
9736 (from (plist-get p :fromaddress))
9737 (table
9738 (list
9739 (cons "%c" (plist-get p :fromto))
9740 (cons "%F" (plist-get p :from))
9741 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9742 (cons "%T" (plist-get p :to))
9743 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9744 (cons "%s" (plist-get p :subject))
9745 (cons "%d" (plist-get p :date))
9746 (cons "%m" (plist-get p :message-id)))))
9747 (when (string-match "%c" fmt)
9748 ;; Check if the user wrote this message
9749 (if (and org-from-is-user-regexp from to
9750 (save-match-data (string-match org-from-is-user-regexp from)))
9751 (setq fmt (replace-match "to %t" t t fmt))
9752 (setq fmt (replace-match "from %f" t t fmt))))
9753 (org-replace-escapes fmt table)))
9755 (defun org-make-org-heading-search-string (&optional string)
9756 "Make search string for the current headline or STRING."
9757 (let ((s (or string
9758 (and (derived-mode-p 'org-mode)
9759 (save-excursion
9760 (org-back-to-heading t)
9761 (org-element-property :raw-value (org-element-at-point))))))
9762 (lines org-context-in-file-links))
9763 (or string (setq s (concat "*" s))) ; Add * for headlines
9764 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9765 (when (and string (integerp lines) (> lines 0))
9766 (let ((slines (org-split-string s "\n")))
9767 (when (< lines (length slines))
9768 (setq s (mapconcat
9769 'identity
9770 (reverse (nthcdr (- (length slines) lines)
9771 (reverse slines))) "\n")))))
9772 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9774 (defun org-make-link-string (link &optional description)
9775 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9776 (unless (string-match "\\S-" link)
9777 (error "Empty link"))
9778 (when (and description
9779 (stringp description)
9780 (not (string-match "\\S-" description)))
9781 (setq description nil))
9782 (when (stringp description)
9783 ;; Remove brackets from the description, they are fatal.
9784 (while (string-match "\\[" description)
9785 (setq description (replace-match "{" t t description)))
9786 (while (string-match "\\]" description)
9787 (setq description (replace-match "}" t t description))))
9788 (when (equal link description)
9789 ;; No description needed, it is identical
9790 (setq description nil))
9791 (when (and (not description)
9792 (not (string-match (org-image-file-name-regexp) link))
9793 (not (equal link (org-link-escape link))))
9794 (setq description (org-extract-attributes link)))
9795 (setq link
9796 (cond ((string-match (org-image-file-name-regexp) link) link)
9797 ((string-match org-link-types-re link)
9798 (concat (match-string 1 link)
9799 (org-link-escape (substring link (match-end 1)))))
9800 (t (org-link-escape link))))
9801 (concat "[[" link "]"
9802 (if description (concat "[" description "]") "")
9803 "]"))
9805 (defconst org-link-escape-chars
9806 ;;%20 %2B %3B %3D %5B %5D
9807 '(?\ ?\+ ?\; ?\= ?\[ ?\])
9808 "List of characters that should be escaped in link.
9809 This is the list that is used for internal purposes.")
9811 (defconst org-link-escape-chars-browser
9812 ;;%20 %22
9813 '(?\ ?\")
9814 "List of escapes for characters that are problematic in links.
9815 This is the list that is used before handing over to the browser.")
9817 (defun org-link-escape (text &optional table merge)
9818 "Return percent escaped representation of TEXT.
9819 TEXT is a string with the text to escape.
9820 Optional argument TABLE is a list with characters that should be
9821 escaped. When nil, `org-link-escape-chars' is used.
9822 If optional argument MERGE is set, merge TABLE into
9823 `org-link-escape-chars'."
9824 (cond
9825 ((and table merge)
9826 (mapc (lambda (defchr)
9827 (unless (member defchr table)
9828 (setq table (cons defchr table)))) org-link-escape-chars))
9829 ((null table)
9830 (setq table org-link-escape-chars)))
9831 (mapconcat
9832 (lambda (char)
9833 (if (or (member char table)
9834 (and (or (< char 32) (= char ?\%) (> char 126))
9835 org-url-hexify-p))
9836 (mapconcat (lambda (sequence-element)
9837 (format "%%%.2X" sequence-element))
9838 (or (encode-coding-char char 'utf-8)
9839 (error "Unable to percent escape character: %s"
9840 (char-to-string char))) "")
9841 (char-to-string char))) text ""))
9843 (defun org-link-escape-browser (text)
9844 (if (org-string-match-p
9845 (concat "[[:nonascii:]" org-link-escape-chars-browser "]")
9846 text)
9847 (org-link-escape text org-link-escape-chars-browser)
9848 text))
9850 (defun org-link-unescape (str)
9851 "Unhex hexified Unicode strings as returned from the JavaScript function
9852 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9853 (unless (and (null str) (string= "" str))
9854 (let ((pos 0) (case-fold-search t) unhexed)
9855 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9856 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9857 (setq str (replace-match unhexed t t str))
9858 (setq pos (+ pos (length unhexed))))))
9859 str)
9861 (defun org-link-unescape-compound (hex)
9862 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9863 Note: this function also decodes single byte encodings like
9864 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9865 (save-match-data
9866 (let* ((bytes (cdr (split-string hex "%")))
9867 (ret "")
9868 (eat 0)
9869 (sum 0))
9870 (while bytes
9871 (let* ((val (string-to-number (pop bytes) 16))
9872 (shift-xor
9873 (if (= 0 eat)
9874 (cond
9875 ((>= val 252) (cons 6 252))
9876 ((>= val 248) (cons 5 248))
9877 ((>= val 240) (cons 4 240))
9878 ((>= val 224) (cons 3 224))
9879 ((>= val 192) (cons 2 192))
9880 (t (cons 0 0)))
9881 (cons 6 128))))
9882 (if (>= val 192) (setq eat (car shift-xor)))
9883 (setq val (logxor val (cdr shift-xor)))
9884 (setq sum (+ (lsh sum (car shift-xor)) val))
9885 (if (> eat 0) (setq eat (- eat 1)))
9886 (cond
9887 ((= 0 eat) ;multi byte
9888 (setq ret (concat ret (org-char-to-string sum)))
9889 (setq sum 0))
9890 ((not bytes) ; single byte(s)
9891 (setq ret (org-link-unescape-single-byte-sequence hex))))
9892 )) ;; end (while bytes
9893 ret )))
9895 (defun org-link-unescape-single-byte-sequence (hex)
9896 "Unhexify hex-encoded single byte character sequences."
9897 (mapconcat (lambda (byte)
9898 (char-to-string (string-to-number byte 16)))
9899 (cdr (split-string hex "%")) ""))
9901 (defun org-xor (a b)
9902 "Exclusive or."
9903 (if a (not b) b))
9905 (defun org-fixup-message-id-for-http (s)
9906 "Replace special characters in a message id, so it can be used in an http query."
9907 (when (string-match "%" s)
9908 (setq s (mapconcat (lambda (c)
9909 (if (eq c ?%)
9910 "%25"
9911 (char-to-string c)))
9912 s "")))
9913 (while (string-match "<" s)
9914 (setq s (replace-match "%3C" t t s)))
9915 (while (string-match ">" s)
9916 (setq s (replace-match "%3E" t t s)))
9917 (while (string-match "@" s)
9918 (setq s (replace-match "%40" t t s)))
9921 (defun org-link-prettify (link)
9922 "Return a human-readable representation of LINK.
9923 The car of LINK must be a raw link the cdr of LINK must be either
9924 a link description or nil."
9925 (let ((desc (or (cadr link) "<no description>")))
9926 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9927 "<" (car link) ">")))
9929 ;;;###autoload
9930 (defun org-insert-link-global ()
9931 "Insert a link like Org-mode does.
9932 This command can be called in any mode to insert a link in Org-mode syntax."
9933 (interactive)
9934 (org-load-modules-maybe)
9935 (org-run-like-in-org-mode 'org-insert-link))
9937 (defun org-insert-all-links (&optional keep)
9938 "Insert all links in `org-stored-links'."
9939 (interactive "P")
9940 (let ((links (copy-sequence org-stored-links)) l)
9941 (while (setq l (if keep (pop links) (pop org-stored-links)))
9942 (insert "- ")
9943 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9944 (insert "\n"))))
9946 (defun org-link-fontify-links-to-this-file ()
9947 "Fontify links to the current file in `org-stored-links'."
9948 (let ((f (buffer-file-name)) a b)
9949 (setq a (mapcar (lambda(l)
9950 (let ((ll (car l)))
9951 (when (and (string-match "^file:\\(.+\\)::" ll)
9952 (equal f (expand-file-name (match-string 1 ll))))
9953 ll)))
9954 org-stored-links))
9955 (when (featurep 'org-id)
9956 (setq b (mapcar (lambda(l)
9957 (let ((ll (car l)))
9958 (when (and (string-match "^id:\\(.+\\)$" ll)
9959 (equal f (expand-file-name
9960 (or (org-id-find-id-file
9961 (match-string 1 ll)) ""))))
9962 ll)))
9963 org-stored-links)))
9964 (mapcar (lambda(l)
9965 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9966 (delq nil (append a b)))))
9968 (defvar org-link-links-in-this-file nil)
9969 (defun org-insert-link (&optional complete-file link-location default-description)
9970 "Insert a link. At the prompt, enter the link.
9972 Completion can be used to insert any of the link protocol prefixes like
9973 http or ftp in use.
9975 The history can be used to select a link previously stored with
9976 `org-store-link'. When the empty string is entered (i.e. if you just
9977 press RET at the prompt), the link defaults to the most recently
9978 stored link. As SPC triggers completion in the minibuffer, you need to
9979 use M-SPC or C-q SPC to force the insertion of a space character.
9981 You will also be prompted for a description, and if one is given, it will
9982 be displayed in the buffer instead of the link.
9984 If there is already a link at point, this command will allow you to edit link
9985 and description parts.
9987 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9988 be selected using completion. The path to the file will be relative to the
9989 current directory if the file is in the current directory or a subdirectory.
9990 Otherwise, the link will be the absolute path as completed in the minibuffer
9991 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9992 option `org-link-file-path-type'.
9994 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9995 the current directory or below.
9997 With three \\[universal-argument] prefixes, negate the meaning of
9998 `org-keep-stored-link-after-insertion'.
10000 If `org-make-link-description-function' is non-nil, this function will be
10001 called with the link target, and the result will be the default
10002 link description.
10004 If the LINK-LOCATION parameter is non-nil, this value will be
10005 used as the link location instead of reading one interactively.
10007 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10008 be used as the default description."
10009 (interactive "P")
10010 (let* ((wcf (current-window-configuration))
10011 (origbuf (current-buffer))
10012 (region (if (org-region-active-p)
10013 (buffer-substring (region-beginning) (region-end))))
10014 (remove (and region (list (region-beginning) (region-end))))
10015 (desc region)
10016 tmphist ; byte-compile incorrectly complains about this
10017 (link link-location)
10018 (abbrevs org-link-abbrev-alist-local)
10019 entry file all-prefixes auto-desc)
10020 (cond
10021 (link-location) ; specified by arg, just use it.
10022 ((org-in-regexp org-bracket-link-regexp 1)
10023 ;; We do have a link at point, and we are going to edit it.
10024 (setq remove (list (match-beginning 0) (match-end 0)))
10025 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
10026 (setq link (read-string "Link: "
10027 (org-link-unescape
10028 (org-match-string-no-properties 1)))))
10029 ((or (org-in-regexp org-angle-link-re)
10030 (org-in-regexp org-plain-link-re))
10031 ;; Convert to bracket link
10032 (setq remove (list (match-beginning 0) (match-end 0))
10033 link (read-string "Link: "
10034 (org-remove-angle-brackets (match-string 0)))))
10035 ((member complete-file '((4) (16)))
10036 ;; Completing read for file names.
10037 (setq link (org-file-complete-link complete-file)))
10039 ;; Read link, with completion for stored links.
10040 (org-link-fontify-links-to-this-file)
10041 (org-switch-to-buffer-other-window "*Org Links*")
10042 (with-current-buffer "*Org Links*"
10043 (erase-buffer)
10044 (insert "Insert a link.
10045 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10046 (when org-stored-links
10047 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10048 (insert (mapconcat 'org-link-prettify
10049 (reverse org-stored-links) "\n")))
10050 (goto-char (point-min)))
10051 (let ((cw (selected-window)))
10052 (select-window (get-buffer-window "*Org Links*" 'visible))
10053 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10054 (unless (pos-visible-in-window-p (point-max))
10055 (org-fit-window-to-buffer))
10056 (and (window-live-p cw) (select-window cw)))
10057 ;; Fake a link history, containing the stored links.
10058 (setq tmphist (append (mapcar 'car org-stored-links)
10059 org-insert-link-history))
10060 (setq all-prefixes (append (mapcar 'car abbrevs)
10061 (mapcar 'car org-link-abbrev-alist)
10062 org-link-types))
10063 (unwind-protect
10064 (progn
10065 (setq link
10066 (org-completing-read
10067 "Link: "
10068 (append
10069 (mapcar (lambda (x) (concat x ":"))
10070 all-prefixes)
10071 (mapcar 'car org-stored-links))
10072 nil nil nil
10073 'tmphist
10074 (caar org-stored-links)))
10075 (if (not (string-match "\\S-" link))
10076 (user-error "No link selected"))
10077 (mapc (lambda(l)
10078 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
10079 org-stored-links)
10080 (if (or (member link all-prefixes)
10081 (and (equal ":" (substring link -1))
10082 (member (substring link 0 -1) all-prefixes)
10083 (setq link (substring link 0 -1))))
10084 (setq link (with-current-buffer origbuf
10085 (org-link-try-special-completion link)))))
10086 (set-window-configuration wcf)
10087 (kill-buffer "*Org Links*"))
10088 (setq entry (assoc link org-stored-links))
10089 (or entry (push link org-insert-link-history))
10090 (setq desc (or desc (nth 1 entry)))))
10092 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10093 (not org-keep-stored-link-after-insertion))
10094 (setq org-stored-links (delq (assoc link org-stored-links)
10095 org-stored-links)))
10097 (if (and (string-match org-plain-link-re link)
10098 (not (string-match org-ts-regexp link)))
10099 ;; URL-like link, normalize the use of angular brackets.
10100 (setq link (org-remove-angle-brackets link)))
10102 ;; Check if we are linking to the current file with a search
10103 ;; option If yes, simplify the link by using only the search
10104 ;; option.
10105 (when (and buffer-file-name
10106 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10107 (let* ((path (match-string 1 link))
10108 (case-fold-search nil)
10109 (search (match-string 2 link)))
10110 (save-match-data
10111 (if (equal (file-truename buffer-file-name) (file-truename path))
10112 ;; We are linking to this same file, with a search option
10113 (setq link search)))))
10115 ;; Check if we can/should use a relative path. If yes, simplify the link
10116 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10117 (let* ((type (match-string 1 link))
10118 (path (match-string 2 link))
10119 (origpath path)
10120 (case-fold-search nil))
10121 (cond
10122 ((or (eq org-link-file-path-type 'absolute)
10123 (equal complete-file '(16)))
10124 (setq path (abbreviate-file-name (expand-file-name path))))
10125 ((eq org-link-file-path-type 'noabbrev)
10126 (setq path (expand-file-name path)))
10127 ((eq org-link-file-path-type 'relative)
10128 (setq path (file-relative-name path)))
10130 (save-match-data
10131 (if (string-match (concat "^" (regexp-quote
10132 (expand-file-name
10133 (file-name-as-directory
10134 default-directory))))
10135 (expand-file-name path))
10136 ;; We are linking a file with relative path name.
10137 (setq path (substring (expand-file-name path)
10138 (match-end 0)))
10139 (setq path (abbreviate-file-name (expand-file-name path)))))))
10140 (setq link (concat type path))
10141 (if (equal desc origpath)
10142 (setq desc path))))
10144 (if org-make-link-description-function
10145 (setq desc
10146 (or (condition-case nil
10147 (funcall org-make-link-description-function link desc)
10148 (error (progn (message "Can't get link description from `%s'"
10149 (symbol-name org-make-link-description-function))
10150 (sit-for 2) nil)))
10151 (read-string "Description: " default-description)))
10152 (if default-description (setq desc default-description)
10153 (setq desc (or (and auto-desc desc)
10154 (read-string "Description: " desc)))))
10156 (unless (string-match "\\S-" desc) (setq desc nil))
10157 (if remove (apply 'delete-region remove))
10158 (insert (org-make-link-string link desc))))
10160 (defun org-link-try-special-completion (type)
10161 "If there is completion support for link type TYPE, offer it."
10162 (let ((fun (intern (concat "org-" type "-complete-link"))))
10163 (if (functionp fun)
10164 (funcall fun)
10165 (read-string "Link (no completion support): " (concat type ":")))))
10167 (defun org-file-complete-link (&optional arg)
10168 "Create a file link using completion."
10169 (let (file link)
10170 (setq file (org-iread-file-name "File: "))
10171 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10172 (pwd1 (file-name-as-directory (abbreviate-file-name
10173 (expand-file-name ".")))))
10174 (cond
10175 ((equal arg '(16))
10176 (setq link (concat
10177 "file:"
10178 (abbreviate-file-name (expand-file-name file)))))
10179 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10180 (setq link (concat "file:" (match-string 1 file))))
10181 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10182 (expand-file-name file))
10183 (setq link (concat
10184 "file:" (match-string 1 (expand-file-name file)))))
10185 (t (setq link (concat "file:" file)))))
10186 link))
10188 (defun org-iread-file-name (&rest args)
10189 "Read-file-name using `ido-mode' speedup if available.
10190 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10191 See `read-file-name' for a description of parameters."
10192 (org-without-partial-completion
10193 (if (and org-completion-use-ido
10194 (fboundp 'ido-read-file-name)
10195 (boundp 'ido-mode) ido-mode
10196 (listp (second args)))
10197 (let ((ido-enter-matching-directory nil))
10198 (apply 'ido-read-file-name args))
10199 (apply 'read-file-name args))))
10201 (defun org-completing-read (&rest args)
10202 "Completing-read with SPACE being a normal character."
10203 (let ((enable-recursive-minibuffers t)
10204 (minibuffer-local-completion-map
10205 (copy-keymap minibuffer-local-completion-map)))
10206 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10207 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10208 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10209 (apply 'org-icompleting-read args)))
10211 (defun org-completing-read-no-i (&rest args)
10212 (let (org-completion-use-ido org-completion-use-iswitchb)
10213 (apply 'org-completing-read args)))
10215 (defun org-iswitchb-completing-read (prompt choices &rest args)
10216 "Use iswitch as a completing-read replacement to choose from choices.
10217 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10218 from."
10219 (let* ((iswitchb-use-virtual-buffers nil)
10220 (iswitchb-make-buflist-hook
10221 (lambda ()
10222 (setq iswitchb-temp-buflist choices))))
10223 (iswitchb-read-buffer prompt)))
10225 (defun org-icompleting-read (&rest args)
10226 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10227 (org-without-partial-completion
10228 (if (and org-completion-use-ido
10229 (fboundp 'ido-completing-read)
10230 (boundp 'ido-mode) ido-mode
10231 (listp (second args)))
10232 (let ((ido-enter-matching-directory nil))
10233 (apply 'ido-completing-read (concat (car args))
10234 (if (consp (car (nth 1 args)))
10235 (mapcar 'car (nth 1 args))
10236 (nth 1 args))
10237 (cddr args)))
10238 (if (and org-completion-use-iswitchb
10239 (boundp 'iswitchb-mode) iswitchb-mode
10240 (listp (second args)))
10241 (apply 'org-iswitchb-completing-read (concat (car args))
10242 (if (consp (car (nth 1 args)))
10243 (mapcar 'car (nth 1 args))
10244 (nth 1 args))
10245 (cddr args))
10246 (apply 'completing-read args)))))
10248 (defun org-extract-attributes (s)
10249 "Extract the attributes cookie from a string and set as text property."
10250 (let (a attr (start 0) key value)
10251 (save-match-data
10252 (when (string-match "{{\\([^}]+\\)}}$" s)
10253 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10254 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10255 (setq key (match-string 1 a) value (match-string 2 a)
10256 start (match-end 0)
10257 attr (plist-put attr (intern key) value))))
10258 (org-add-props s nil 'org-attr attr))
10261 ;;; Opening/following a link
10263 (defvar org-link-search-failed nil)
10265 (defvar org-open-link-functions nil
10266 "Hook for functions finding a plain text link.
10267 These functions must take a single argument, the link content.
10268 They will be called for links that look like [[link text][description]]
10269 when LINK TEXT does not have a protocol like \"http:\" and does not look
10270 like a filename (e.g. \"./blue.png\").
10272 These functions will be called *before* Org attempts to resolve the
10273 link by doing text searches in the current buffer - so if you want a
10274 link \"[[target]]\" to still find \"<<target>>\", your function should
10275 handle this as a special case.
10277 When the function does handle the link, it must return a non-nil value.
10278 If it decides that it is not responsible for this link, it must return
10279 nil to indicate that that Org-mode can continue with other options
10280 like exact and fuzzy text search.")
10282 (defun org-next-link (&optional search-backward)
10283 "Move forward to the next link.
10284 If the link is in hidden text, expose it."
10285 (interactive "P")
10286 (when (and org-link-search-failed (eq this-command last-command))
10287 (goto-char (point-min))
10288 (message "Link search wrapped back to beginning of buffer"))
10289 (setq org-link-search-failed nil)
10290 (let* ((pos (point))
10291 (ct (org-context))
10292 (a (assoc :link ct))
10293 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10294 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10295 ((looking-at org-any-link-re)
10296 ;; Don't stay stuck at link without an org-link face
10297 (forward-char (if search-backward -1 1))))
10298 (if (funcall srch-fun org-any-link-re nil t)
10299 (progn
10300 (goto-char (match-beginning 0))
10301 (if (outline-invisible-p) (org-show-context)))
10302 (goto-char pos)
10303 (setq org-link-search-failed t)
10304 (message "No further link found"))))
10306 (defun org-previous-link ()
10307 "Move backward to the previous link.
10308 If the link is in hidden text, expose it."
10309 (interactive)
10310 (funcall 'org-next-link t))
10312 (defun org-translate-link (s)
10313 "Translate a link string if a translation function has been defined."
10314 (if (and org-link-translation-function
10315 (fboundp org-link-translation-function)
10316 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10317 (progn
10318 (setq s (funcall org-link-translation-function
10319 (match-string 1 s) (match-string 2 s)))
10320 (concat (car s) ":" (cdr s)))
10323 (defun org-translate-link-from-planner (type path)
10324 "Translate a link from Emacs Planner syntax so that Org can follow it.
10325 This is still an experimental function, your mileage may vary."
10326 (cond
10327 ((member type '("http" "https" "news" "ftp"))
10328 ;; standard Internet links are the same.
10329 nil)
10330 ((and (equal type "irc") (string-match "^//" path))
10331 ;; Planner has two / at the beginning of an irc link, we have 1.
10332 ;; We should have zero, actually....
10333 (setq path (substring path 1)))
10334 ((and (equal type "lisp") (string-match "^/" path))
10335 ;; Planner has a slash, we do not.
10336 (setq type "elisp" path (substring path 1)))
10337 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10338 ;; A typical message link. Planner has the id after the final slash,
10339 ;; we separate it with a hash mark
10340 (setq path (concat (match-string 1 path) "#"
10341 (org-remove-angle-brackets (match-string 2 path))))))
10342 (cons type path))
10344 (defun org-find-file-at-mouse (ev)
10345 "Open file link or URL at mouse."
10346 (interactive "e")
10347 (mouse-set-point ev)
10348 (org-open-at-point 'in-emacs))
10350 (defun org-open-at-mouse (ev)
10351 "Open file link or URL at mouse.
10352 See the docstring of `org-open-file' for details."
10353 (interactive "e")
10354 (mouse-set-point ev)
10355 (if (eq major-mode 'org-agenda-mode)
10356 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10357 (org-open-at-point))
10359 (defvar org-window-config-before-follow-link nil
10360 "The window configuration before following a link.
10361 This is saved in case the need arises to restore it.")
10363 (defvar org-open-link-marker (make-marker)
10364 "Marker pointing to the location where `org-open-at-point; was called.")
10366 ;;;###autoload
10367 (defun org-open-at-point-global ()
10368 "Follow a link like Org-mode does.
10369 This command can be called in any mode to follow a link that has
10370 Org-mode syntax."
10371 (interactive)
10372 (org-run-like-in-org-mode 'org-open-at-point))
10374 ;;;###autoload
10375 (defun org-open-link-from-string (s &optional arg reference-buffer)
10376 "Open a link in the string S, as if it was in Org-mode."
10377 (interactive "sLink: \nP")
10378 (let ((reference-buffer (or reference-buffer (current-buffer))))
10379 (with-temp-buffer
10380 (let ((org-inhibit-startup (not reference-buffer)))
10381 (org-mode)
10382 (insert s)
10383 (goto-char (point-min))
10384 (when reference-buffer
10385 (setq org-link-abbrev-alist-local
10386 (with-current-buffer reference-buffer
10387 org-link-abbrev-alist-local)))
10388 (org-open-at-point arg reference-buffer)))))
10390 (defvar org-open-at-point-functions nil
10391 "Hook that is run when following a link at point.
10393 Functions in this hook must return t if they identify and follow
10394 a link at point. If they don't find anything interesting at point,
10395 they must return nil.")
10397 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10398 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10399 (defun org-open-at-point (&optional arg reference-buffer)
10400 "Open link at or after point.
10401 If there is no link at point, this function will search forward up to
10402 the end of the current line.
10403 Normally, files will be opened by an appropriate application. If the
10404 optional prefix argument ARG is non-nil, Emacs will visit the file.
10405 With a double prefix argument, try to open outside of Emacs, in the
10406 application the system uses for this file type."
10407 (interactive "P")
10408 ;; if in a code block, then open the block's results
10409 (unless (call-interactively #'org-babel-open-src-block-result)
10410 (org-load-modules-maybe)
10411 (move-marker org-open-link-marker (point))
10412 (setq org-window-config-before-follow-link (current-window-configuration))
10413 (org-remove-occur-highlights nil nil t)
10414 (cond
10415 ((and (org-at-heading-p)
10416 (not (org-at-timestamp-p t))
10417 (not (org-in-regexp
10418 (concat org-plain-link-re "\\|"
10419 org-bracket-link-regexp "\\|"
10420 org-angle-link-re "\\|"
10421 "[ \t]:[^ \t\n]+:[ \t]*$")))
10422 (not (get-text-property (point) 'org-linked-text)))
10423 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10424 (lk0 (car lkall))
10425 (lk (if (stringp lk0) (list lk0) lk0))
10426 (lkend (cdr lkall)))
10427 (mapcar (lambda(l)
10428 (search-forward l nil lkend)
10429 (goto-char (match-beginning 0))
10430 (org-open-at-point))
10431 lk))
10432 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10433 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10434 ((and (org-at-timestamp-p t)
10435 (not (org-in-regexp org-bracket-link-regexp)))
10436 (org-follow-timestamp-link))
10437 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10438 (not (org-in-regexp org-any-link-re)))
10439 (org-footnote-action))
10441 (let (type path link line search (pos (point)))
10442 (catch 'match
10443 (save-excursion
10444 (skip-chars-forward "^]\n\r")
10445 (when (org-in-regexp org-bracket-link-regexp 1)
10446 (setq link (org-extract-attributes
10447 (org-link-unescape (org-match-string-no-properties 1))))
10448 (while (string-match " *\n *" link)
10449 (setq link (replace-match " " t t link)))
10450 (setq link (org-link-expand-abbrev link))
10451 (cond
10452 ((or (file-name-absolute-p link)
10453 (string-match "^\\.\\.?/" link))
10454 (setq type "file" path link))
10455 ((string-match org-link-re-with-space3 link)
10456 (setq type (match-string 1 link) path (match-string 2 link)))
10457 ((string-match "^help:+\\(.+\\)" link)
10458 (setq type "help" path (match-string 1 link)))
10459 (t (setq type "thisfile" path link)))
10460 (throw 'match t)))
10462 (when (get-text-property (point) 'org-linked-text)
10463 (setq type "thisfile"
10464 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10465 (1+ (point)) (point))
10466 path (buffer-substring
10467 (or (previous-single-property-change pos 'org-linked-text)
10468 (point-min))
10469 (or (next-single-property-change pos 'org-linked-text)
10470 (point-max)))
10471 ;; Ensure we will search for a <<<radio>>> link, not
10472 ;; a simple reference like <<ref>>
10473 path (concat "<" path))
10474 (throw 'match t))
10476 (save-excursion
10477 (when (or (org-in-regexp org-angle-link-re)
10478 (let ((match (org-in-regexp org-plain-link-re)))
10479 ;; Check a plain link is not within a bracket link
10480 (and match
10481 (save-excursion
10482 (progn
10483 (goto-char (car match))
10484 (not (org-in-regexp org-bracket-link-regexp))))))
10485 (let ((line_ending (save-excursion (end-of-line) (point))))
10486 ;; We are in a line before a plain or bracket link
10487 (or (re-search-forward org-plain-link-re line_ending t)
10488 (re-search-forward org-bracket-link-regexp line_ending t))))
10489 (setq type (match-string 1)
10490 path (org-link-unescape (match-string 2)))
10491 (throw 'match t)))
10492 (save-excursion
10493 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10494 (setq type "tags"
10495 path (match-string 1))
10496 (while (string-match ":" path)
10497 (setq path (replace-match "+" t t path)))
10498 (throw 'match t)))
10499 (when (org-in-regexp "<\\([^><\n]+\\)>")
10500 (setq type "tree-match"
10501 path (match-string 1))
10502 (throw 'match t)))
10503 (unless path
10504 (user-error "No link found"))
10506 ;; switch back to reference buffer
10507 ;; needed when if called in a temporary buffer through
10508 ;; org-open-link-from-string
10509 (with-current-buffer (or reference-buffer (current-buffer))
10511 ;; Remove any trailing spaces in path
10512 (if (string-match " +\\'" path)
10513 (setq path (replace-match "" t t path)))
10514 (if (and org-link-translation-function
10515 (fboundp org-link-translation-function))
10516 ;; Check if we need to translate the link
10517 (let ((tmp (funcall org-link-translation-function type path)))
10518 (setq type (car tmp) path (cdr tmp))))
10520 (cond
10522 ((assoc type org-link-protocols)
10523 (funcall (nth 1 (assoc type org-link-protocols)) path))
10525 ((equal type "help")
10526 (let ((f-or-v (intern path)))
10527 (cond ((fboundp f-or-v)
10528 (describe-function f-or-v))
10529 ((boundp f-or-v)
10530 (describe-variable f-or-v))
10531 (t (error "Not a known function or variable")))))
10533 ((equal type "mailto")
10534 (let ((cmd (car org-link-mailto-program))
10535 (args (cdr org-link-mailto-program)) args1
10536 (address path) (subject "") a)
10537 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10538 (setq address (match-string 1 path)
10539 subject (org-link-escape (match-string 2 path))))
10540 (while args
10541 (cond
10542 ((not (stringp (car args))) (push (pop args) args1))
10543 (t (setq a (pop args))
10544 (if (string-match "%a" a)
10545 (setq a (replace-match address t t a)))
10546 (if (string-match "%s" a)
10547 (setq a (replace-match subject t t a)))
10548 (push a args1))))
10549 (apply cmd (nreverse args1))))
10551 ((member type '("http" "https" "ftp" "news"))
10552 ;; In the example of the http Org link
10553 ;; [[http://lists.gnu.org/archive/cgi-bin/namazu.cgi?idxname=emacs-orgmode&query=%252Bsubject:"Release+8.2"]]
10554 ;; to open a browser with +subject:"Release 8.2" in the
10555 ;; query field the variable `path' contains
10556 ;; [...]=%2Bsubject:"Release+8.2", `url-encode-url'
10557 ;; converts correct to [...]=%2Bsubject:%22Release+8.2%22
10558 ;; and `org-link-escape-browser' converts wrong to
10559 ;; [...]=%252Bsubject:%22Release+8.2%22.
10561 ;; `url-encode-url' is available since Emacs 24.3.1 and
10562 ;; `org-link-escape-browser' can be removed altogether
10563 ;; once Org drops support for Emacs 24.1 and 24.2.
10564 (browse-url (funcall (if (fboundp 'url-encode-url)
10565 #'url-encode-url
10566 #'org-link-escape-browser)
10567 (concat type ":" path))))
10569 ((string= type "doi")
10570 ;; See comments for type http above
10571 (browse-url (funcall (if (fboundp 'url-encode-url)
10572 #'url-encode-url
10573 #'org-link-escape-browser)
10574 (concat org-doi-server-url path))))
10576 ((member type '("message"))
10577 (browse-url (concat type ":" path)))
10579 ((string= type "tags")
10580 (org-tags-view arg path))
10582 ((string= type "tree-match")
10583 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10585 ((string= type "file")
10586 (if (string-match "::\\([0-9]+\\)\\'" path)
10587 (setq line (string-to-number (match-string 1 path))
10588 path (substring path 0 (match-beginning 0)))
10589 (if (string-match "::\\(.+\\)\\'" path)
10590 (setq search (match-string 1 path)
10591 path (substring path 0 (match-beginning 0)))))
10592 (if (string-match "[*?{]" (file-name-nondirectory path))
10593 (dired path)
10594 (org-open-file path arg line search)))
10596 ((string= type "shell")
10597 (let ((buf (generate-new-buffer "*Org Shell Output"))
10598 (cmd path))
10599 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10600 (string-match org-confirm-shell-link-not-regexp cmd))
10601 (not org-confirm-shell-link-function)
10602 (funcall org-confirm-shell-link-function
10603 (format "Execute \"%s\" in shell? "
10604 (org-add-props cmd nil
10605 'face 'org-warning))))
10606 (progn
10607 (message "Executing %s" cmd)
10608 (shell-command cmd buf)
10609 (if (featurep 'midnight)
10610 (setq clean-buffer-list-kill-buffer-names
10611 (cons buf clean-buffer-list-kill-buffer-names))))
10612 (error "Abort"))))
10614 ((string= type "elisp")
10615 (let ((cmd path))
10616 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10617 (string-match org-confirm-elisp-link-not-regexp cmd))
10618 (not org-confirm-elisp-link-function)
10619 (funcall org-confirm-elisp-link-function
10620 (format "Execute \"%s\" as elisp? "
10621 (org-add-props cmd nil
10622 'face 'org-warning))))
10623 (message "%s => %s" cmd
10624 (if (equal (string-to-char cmd) ?\()
10625 (eval (read cmd))
10626 (call-interactively (read cmd))))
10627 (error "Abort"))))
10629 ((and (string= type "thisfile")
10630 (or (run-hook-with-args-until-success
10631 'org-open-link-functions path)
10632 (and link
10633 (string-match "^id:" link)
10634 (or (featurep 'org-id) (require 'org-id))
10635 (progn
10636 (funcall (nth 1 (assoc "id" org-link-protocols))
10637 (substring path 3))
10638 t)))))
10640 ((string= type "thisfile")
10641 (if arg
10642 (switch-to-buffer-other-window
10643 (org-get-buffer-for-internal-link (current-buffer)))
10644 (org-mark-ring-push))
10645 (let ((cmd `(org-link-search
10646 ,path
10647 ,(cond ((equal arg '(4)) ''occur)
10648 ((equal arg '(16)) ''org-occur))
10649 ,pos)))
10650 (condition-case nil (let ((org-link-search-inhibit-query t))
10651 (eval cmd))
10652 (error (progn (widen) (eval cmd))))))
10654 (t (browse-url-at-point)))))))
10655 (move-marker org-open-link-marker nil)
10656 (run-hook-with-args 'org-follow-link-hook)))
10658 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10659 "Offer links in the current entry and return the selected link.
10660 If there is only one link, return it.
10661 If NTH is an integer, return the NTH link found.
10662 If ZERO is a string, check also this string for a link, and if
10663 there is one, return it."
10664 (with-current-buffer buffer
10665 (save-excursion
10666 (save-restriction
10667 (widen)
10668 (goto-char marker)
10669 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10670 "\\(" org-angle-link-re "\\)\\|"
10671 "\\(" org-plain-link-re "\\)"))
10672 (cnt ?0)
10673 (in-emacs (if (integerp nth) nil nth))
10674 have-zero end links link c)
10675 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10676 (push (match-string 0 zero) links)
10677 (setq cnt (1- cnt) have-zero t))
10678 (save-excursion
10679 (org-back-to-heading t)
10680 (setq end (save-excursion (outline-next-heading) (point)))
10681 (while (re-search-forward re end t)
10682 (push (match-string 0) links))
10683 (setq links (org-uniquify (reverse links))))
10684 (cond
10685 ((null links)
10686 (message "No links"))
10687 ((equal (length links) 1)
10688 (setq link (car links)))
10689 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10690 (setq link (nth (if have-zero nth (1- nth)) links)))
10691 (t ; we have to select a link
10692 (save-excursion
10693 (save-window-excursion
10694 (delete-other-windows)
10695 (with-output-to-temp-buffer "*Select Link*"
10696 (mapc (lambda (l)
10697 (if (not (string-match org-bracket-link-regexp l))
10698 (princ (format "[%c] %s\n" (incf cnt)
10699 (org-remove-angle-brackets l)))
10700 (if (match-end 3)
10701 (princ (format "[%c] %s (%s)\n" (incf cnt)
10702 (match-string 3 l) (match-string 1 l)))
10703 (princ (format "[%c] %s\n" (incf cnt)
10704 (match-string 1 l))))))
10705 links))
10706 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10707 (message "Select link to open, RET to open all:")
10708 (setq c (read-char-exclusive))
10709 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10710 (when (equal c ?q) (error "Abort"))
10711 (if (equal c ?\C-m)
10712 (setq link links)
10713 (setq nth (- c ?0))
10714 (if have-zero (setq nth (1+ nth)))
10715 (unless (and (integerp nth) (>= (length links) nth))
10716 (user-error "Invalid link selection"))
10717 (setq link (nth (1- nth) links)))))
10718 (cons link end))))))
10720 ;; Add special file links that specify the way of opening
10722 (org-add-link-type "file+sys" 'org-open-file-with-system)
10723 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10724 (defun org-open-file-with-system (path)
10725 "Open file at PATH using the system way of opening it."
10726 (org-open-file path 'system))
10727 (defun org-open-file-with-emacs (path)
10728 "Open file at PATH in Emacs."
10729 (org-open-file path 'emacs))
10732 ;;; File search
10734 (defvar org-create-file-search-functions nil
10735 "List of functions to construct the right search string for a file link.
10736 These functions are called in turn with point at the location to
10737 which the link should point.
10739 A function in the hook should first test if it would like to
10740 handle this file type, for example by checking the `major-mode'
10741 or the file extension. If it decides not to handle this file, it
10742 should just return nil to give other functions a chance. If it
10743 does handle the file, it must return the search string to be used
10744 when following the link. The search string will be part of the
10745 file link, given after a double colon, and `org-open-at-point'
10746 will automatically search for it. If special measures must be
10747 taken to make the search successful, another function should be
10748 added to the companion hook `org-execute-file-search-functions',
10749 which see.
10751 A function in this hook may also use `setq' to set the variable
10752 `description' to provide a suggestion for the descriptive text to
10753 be used for this link when it gets inserted into an Org-mode
10754 buffer with \\[org-insert-link].")
10756 (defvar org-execute-file-search-functions nil
10757 "List of functions to execute a file search triggered by a link.
10759 Functions added to this hook must accept a single argument, the
10760 search string that was part of the file link, the part after the
10761 double colon. The function must first check if it would like to
10762 handle this search, for example by checking the `major-mode' or
10763 the file extension. If it decides not to handle this search, it
10764 should just return nil to give other functions a chance. If it
10765 does handle the search, it must return a non-nil value to keep
10766 other functions from trying.
10768 Each function can access the current prefix argument through the
10769 variable `current-prefix-arg'. Note that a single prefix is used
10770 to force opening a link in Emacs, so it may be good to only use a
10771 numeric or double prefix to guide the search function.
10773 In case this is needed, a function in this hook can also restore
10774 the window configuration before `org-open-at-point' was called using:
10776 (set-window-configuration org-window-config-before-follow-link)")
10778 (defun org-link-search (s &optional type avoid-pos stealth)
10779 "Search for a link search option.
10780 If S is surrounded by forward slashes, it is interpreted as a
10781 regular expression. In org-mode files, this will create an `org-occur'
10782 sparse tree. In ordinary files, `occur' will be used to list matches.
10783 If the current buffer is in `dired-mode', grep will be used to search
10784 in all files. If AVOID-POS is given, ignore matches near that position.
10786 When optional argument STEALTH is non-nil, do not modify
10787 visibility around point, thus ignoring
10788 `org-show-hierarchy-above', `org-show-following-heading' and
10789 `org-show-siblings' variables."
10790 (let ((case-fold-search t)
10791 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10792 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10793 (append '(("") (" ") ("\t") ("\n"))
10794 org-emphasis-alist)
10795 "\\|") "\\)"))
10796 (pos (point))
10797 (pre nil) (post nil)
10798 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10799 (cond
10800 ;; First check if there are any special search functions
10801 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10802 ;; Now try the builtin stuff
10803 ((and (equal (string-to-char s0) ?#)
10804 (> (length s0) 1)
10805 (save-excursion
10806 (goto-char (point-min))
10807 (and
10808 (re-search-forward
10809 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10810 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10811 (setq type 'dedicated
10812 pos (match-beginning 0))))
10813 ;; There is an exact target for this
10814 (goto-char pos)
10815 (org-back-to-heading t)))
10816 ((save-excursion
10817 (goto-char (point-min))
10818 (and
10819 (re-search-forward
10820 (concat "<<" (regexp-quote s0) ">>") nil t)
10821 (setq type 'dedicated
10822 pos (match-beginning 0))))
10823 ;; There is an exact target for this
10824 (goto-char pos))
10825 ((save-excursion
10826 (goto-char (point-min))
10827 (and
10828 (re-search-forward
10829 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10830 (setq type 'dedicated pos (match-beginning 0))))
10831 ;; Found an element with a matching #+name affiliated keyword.
10832 (goto-char pos))
10833 ((and (string-match "^(\\(.*\\))$" s0)
10834 (save-excursion
10835 (goto-char (point-min))
10836 (and
10837 (re-search-forward
10838 (concat "[^[]" (regexp-quote
10839 (format org-coderef-label-format
10840 (match-string 1 s0))))
10841 nil t)
10842 (setq type 'dedicated
10843 pos (1+ (match-beginning 0))))))
10844 ;; There is a coderef target for this
10845 (goto-char pos))
10846 ((string-match "^/\\(.*\\)/$" s)
10847 ;; A regular expression
10848 (cond
10849 ((derived-mode-p 'org-mode)
10850 (org-occur (match-string 1 s)))
10851 (t (org-do-occur (match-string 1 s)))))
10852 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10853 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10854 (goto-char (point-min))
10855 (cond
10856 ((let (case-fold-search)
10857 (re-search-forward (format org-complex-heading-regexp-format
10858 (regexp-quote s))
10859 nil t))
10860 ;; OK, found a match
10861 (setq type 'dedicated)
10862 (goto-char (match-beginning 0)))
10863 ((and (not org-link-search-inhibit-query)
10864 (eq org-link-search-must-match-exact-headline 'query-to-create)
10865 (y-or-n-p "No match - create this as a new heading? "))
10866 (goto-char (point-max))
10867 (or (bolp) (newline))
10868 (insert "* " s "\n")
10869 (beginning-of-line 0))
10871 (goto-char pos)
10872 (error "No match"))))
10874 ;; A normal search string
10875 (when (equal (string-to-char s) ?*)
10876 ;; Anchor on headlines, post may include tags.
10877 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10878 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10879 s (substring s 1)))
10880 (remove-text-properties
10881 0 (length s)
10882 '(face nil mouse-face nil keymap nil fontified nil) s)
10883 ;; Make a series of regular expressions to find a match
10884 (setq words (org-split-string s "[ \n\r\t]+")
10886 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10887 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10888 "\\)" markers)
10889 re2a_ (concat "\\(" (mapconcat 'downcase words
10890 "[ \t\r\n]+") "\\)[ \t\r\n]")
10891 re2a (concat "[ \t\r\n]" re2a_)
10892 re4_ (concat "\\(" (mapconcat 'downcase words
10893 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10894 re4 (concat "[^a-zA-Z_]" re4_)
10896 re1 (concat pre re2 post)
10897 re3 (concat pre (if pre re4_ re4) post)
10898 re5 (concat pre ".*" re4)
10899 re2 (concat pre re2)
10900 re2a (concat pre (if pre re2a_ re2a))
10901 re4 (concat pre (if pre re4_ re4))
10902 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10903 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10904 re5 "\\)"))
10905 (cond
10906 ((eq type 'org-occur) (org-occur reall))
10907 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10908 (t (goto-char (point-min))
10909 (setq type 'fuzzy)
10910 (if (or (and (org-search-not-self 1 re0 nil t)
10911 (setq type 'dedicated))
10912 (org-search-not-self 1 re1 nil t)
10913 (org-search-not-self 1 re2 nil t)
10914 (org-search-not-self 1 re2a nil t)
10915 (org-search-not-self 1 re3 nil t)
10916 (org-search-not-self 1 re4 nil t)
10917 (org-search-not-self 1 re5 nil t))
10918 (goto-char (match-beginning 1))
10919 (goto-char pos)
10920 (error "No match"))))))
10921 (and (derived-mode-p 'org-mode)
10922 (not stealth)
10923 (org-show-context 'link-search))
10924 type))
10926 (defun org-search-not-self (group &rest args)
10927 "Execute `re-search-forward', but only accept matches that do not
10928 enclose the position of `org-open-link-marker'."
10929 (let ((m org-open-link-marker))
10930 (catch 'exit
10931 (while (apply 're-search-forward args)
10932 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10933 (goto-char (match-end group))
10934 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10935 (> (match-beginning 0) (marker-position m))
10936 (< (match-end 0) (marker-position m)))
10937 (save-match-data
10938 (or (not (org-in-regexp
10939 org-bracket-link-analytic-regexp 1))
10940 (not (match-end 4)) ; no description
10941 (and (<= (match-beginning 4) (point))
10942 (>= (match-end 4) (point))))))
10943 (throw 'exit (point))))))))
10945 (defun org-get-buffer-for-internal-link (buffer)
10946 "Return a buffer to be used for displaying the link target of internal links."
10947 (cond
10948 ((not org-display-internal-link-with-indirect-buffer)
10949 buffer)
10950 ((string-match "(Clone)$" (buffer-name buffer))
10951 (message "Buffer is already a clone, not making another one")
10952 ;; we also do not modify visibility in this case
10953 buffer)
10954 (t ; make a new indirect buffer for displaying the link
10955 (let* ((bn (buffer-name buffer))
10956 (ibn (concat bn "(Clone)"))
10957 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10958 (with-current-buffer ib (org-overview))
10959 ib))))
10961 (defun org-do-occur (regexp &optional cleanup)
10962 "Call the Emacs command `occur'.
10963 If CLEANUP is non-nil, remove the printout of the regular expression
10964 in the *Occur* buffer. This is useful if the regex is long and not useful
10965 to read."
10966 (occur regexp)
10967 (when cleanup
10968 (let ((cwin (selected-window)) win beg end)
10969 (when (setq win (get-buffer-window "*Occur*"))
10970 (select-window win))
10971 (goto-char (point-min))
10972 (when (re-search-forward "match[a-z]+" nil t)
10973 (setq beg (match-end 0))
10974 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10975 (setq end (1- (match-beginning 0)))))
10976 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10977 (goto-char (point-min))
10978 (select-window cwin))))
10980 ;;; The mark ring for links jumps
10982 (defvar org-mark-ring nil
10983 "Mark ring for positions before jumps in Org-mode.")
10984 (defvar org-mark-ring-last-goto nil
10985 "Last position in the mark ring used to go back.")
10986 ;; Fill and close the ring
10987 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10988 (loop for i from 1 to org-mark-ring-length do
10989 (push (make-marker) org-mark-ring))
10990 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10991 org-mark-ring)
10993 (defun org-mark-ring-push (&optional pos buffer)
10994 "Put the current position or POS into the mark ring and rotate it."
10995 (interactive)
10996 (setq pos (or pos (point)))
10997 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10998 (move-marker (car org-mark-ring)
10999 (or pos (point))
11000 (or buffer (current-buffer)))
11001 (message "%s"
11002 (substitute-command-keys
11003 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
11005 (defun org-mark-ring-goto (&optional n)
11006 "Jump to the previous position in the mark ring.
11007 With prefix arg N, jump back that many stored positions. When
11008 called several times in succession, walk through the entire ring.
11009 Org-mode commands jumping to a different position in the current file,
11010 or to another Org-mode file, automatically push the old position
11011 onto the ring."
11012 (interactive "p")
11013 (let (p m)
11014 (if (eq last-command this-command)
11015 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11016 (setq p org-mark-ring))
11017 (setq org-mark-ring-last-goto p)
11018 (setq m (car p))
11019 (org-pop-to-buffer-same-window (marker-buffer m))
11020 (goto-char m)
11021 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11023 (defun org-remove-angle-brackets (s)
11024 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
11025 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
11027 (defun org-add-angle-brackets (s)
11028 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
11029 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
11031 (defun org-remove-double-quotes (s)
11032 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
11033 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
11036 ;;; Following specific links
11038 (defun org-follow-timestamp-link ()
11039 "Open an agenda view for the time-stamp date/range at point."
11040 (cond
11041 ((org-at-date-range-p t)
11042 (let ((org-agenda-start-on-weekday)
11043 (t1 (match-string 1))
11044 (t2 (match-string 2)) tt1 tt2)
11045 (setq tt1 (time-to-days (org-time-string-to-time t1))
11046 tt2 (time-to-days (org-time-string-to-time t2)))
11047 (let ((org-agenda-buffer-tmp-name
11048 (format "*Org Agenda(a:%s)"
11049 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11050 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11051 ((org-at-timestamp-p t)
11052 (let ((org-agenda-buffer-tmp-name
11053 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11054 (org-agenda-list nil (time-to-days (org-time-string-to-time
11055 (substring (match-string 1) 0 10)))
11056 1)))
11057 (t (error "This should not happen"))))
11060 ;;; Following file links
11061 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11062 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11063 (declare-function mailcap-mime-info
11064 "mailcap" (string &optional request no-decode))
11065 (defvar org-wait nil)
11066 (defun org-open-file (path &optional in-emacs line search)
11067 "Open the file at PATH.
11068 First, this expands any special file name abbreviations. Then the
11069 configuration variable `org-file-apps' is checked if it contains an
11070 entry for this file type, and if yes, the corresponding command is launched.
11072 If no application is found, Emacs simply visits the file.
11074 With optional prefix argument IN-EMACS, Emacs will visit the file.
11075 With a double \\[universal-argument] \\[universal-argument] \
11076 prefix arg, Org tries to avoid opening in Emacs
11077 and to use an external application to visit the file.
11079 Optional LINE specifies a line to go to, optional SEARCH a string
11080 to search for. If LINE or SEARCH is given, the file will be
11081 opened in Emacs, unless an entry from org-file-apps that makes
11082 use of groups in a regexp matches.
11084 If you want to change the way frames are used when following a
11085 link, please customize `org-link-frame-setup'.
11087 If the file does not exist, an error is thrown."
11088 (let* ((file (if (equal path "")
11089 buffer-file-name
11090 (substitute-in-file-name (expand-file-name path))))
11091 (file-apps (append org-file-apps (org-default-apps)))
11092 (apps (org-remove-if
11093 'org-file-apps-entry-match-against-dlink-p file-apps))
11094 (apps-dlink (org-remove-if-not
11095 'org-file-apps-entry-match-against-dlink-p file-apps))
11096 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11097 (dirp (if remp nil (file-directory-p file)))
11098 (file (if (and dirp org-open-directory-means-index-dot-org)
11099 (concat (file-name-as-directory file) "index.org")
11100 file))
11101 (a-m-a-p (assq 'auto-mode apps))
11102 (dfile (downcase file))
11103 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
11104 (link (cond ((and (eq line nil)
11105 (eq search nil))
11106 file)
11107 (line
11108 (concat file "::" (number-to-string line)))
11109 (search
11110 (concat file "::" search))))
11111 (dlink (downcase link))
11112 (old-buffer (current-buffer))
11113 (old-pos (point))
11114 (old-mode major-mode)
11115 ext cmd link-match-data)
11116 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11117 (setq ext (match-string 1 dfile))
11118 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11119 (setq ext (match-string 1 dfile))))
11120 (cond
11121 ((member in-emacs '((16) system))
11122 (setq cmd (cdr (assoc 'system apps))))
11123 (in-emacs (setq cmd 'emacs))
11125 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11126 (and dirp (cdr (assoc 'directory apps)))
11127 ; first, try matching against apps-dlink
11128 ; if we get a match here, store the match data for later
11129 (let ((match (assoc-default dlink apps-dlink
11130 'string-match)))
11131 (if match
11132 (progn (setq link-match-data (match-data))
11133 match)
11134 (progn (setq in-emacs (or in-emacs line search))
11135 nil))) ; if we have no match in apps-dlink,
11136 ; always open the file in emacs if line or search
11137 ; is given (for backwards compatibility)
11138 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11139 'string-match)
11140 (cdr (assoc ext apps))
11141 (cdr (assoc t apps))))))
11142 (when (eq cmd 'system)
11143 (setq cmd (cdr (assoc 'system apps))))
11144 (when (eq cmd 'default)
11145 (setq cmd (cdr (assoc t apps))))
11146 (when (eq cmd 'mailcap)
11147 (require 'mailcap)
11148 (mailcap-parse-mailcaps)
11149 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11150 (command (mailcap-mime-info mime-type)))
11151 (if (stringp command)
11152 (setq cmd command)
11153 (setq cmd 'emacs))))
11154 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11155 (not (file-exists-p file))
11156 (not org-open-non-existing-files))
11157 (user-error "No such file: %s" file))
11158 (cond
11159 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11160 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11161 (while (string-match "['\"]%s['\"]" cmd)
11162 (setq cmd (replace-match "%s" t t cmd)))
11163 (while (string-match "%s" cmd)
11164 (setq cmd (replace-match
11165 (save-match-data
11166 (shell-quote-argument
11167 (convert-standard-filename file)))
11168 t t cmd)))
11170 ;; Replace "%1", "%2" etc. in command with group matches from regex
11171 (save-match-data
11172 (let ((match-index 1)
11173 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11174 (set-match-data link-match-data)
11175 (while (<= match-index number-of-groups)
11176 (let ((regex (concat "%" (number-to-string match-index)))
11177 (replace-with (match-string match-index dlink)))
11178 (while (string-match regex cmd)
11179 (setq cmd (replace-match replace-with t t cmd))))
11180 (setq match-index (+ match-index 1)))))
11182 (save-window-excursion
11183 (message "Running %s...done" cmd)
11184 (start-process-shell-command cmd nil cmd)
11185 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11186 ((or (stringp cmd)
11187 (eq cmd 'emacs))
11188 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11189 (widen)
11190 (if line (progn (org-goto-line line)
11191 (if (derived-mode-p 'org-mode)
11192 (org-reveal)))
11193 (if search (org-link-search search))))
11194 ((consp cmd)
11195 (let ((file (convert-standard-filename file)))
11196 (save-match-data
11197 (set-match-data link-match-data)
11198 (eval cmd))))
11199 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11200 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11201 (or (not (equal old-buffer (current-buffer)))
11202 (not (equal old-pos (point))))
11203 (org-mark-ring-push old-pos old-buffer))))
11205 (defun org-file-apps-entry-match-against-dlink-p (entry)
11206 "This function returns non-nil if `entry' uses a regular
11207 expression which should be matched against the whole link by
11208 org-open-file.
11210 It assumes that is the case when the entry uses a regular
11211 expression which has at least one grouping construct and the
11212 action is either a lisp form or a command string containing
11213 '%1', i.e. using at least one subexpression match as a
11214 parameter."
11215 (let ((selector (car entry))
11216 (action (cdr entry)))
11217 (if (stringp selector)
11218 (and (> (regexp-opt-depth selector) 0)
11219 (or (and (stringp action)
11220 (string-match "%[0-9]" action))
11221 (consp action)))
11222 nil)))
11224 (defun org-default-apps ()
11225 "Return the default applications for this operating system."
11226 (cond
11227 ((eq system-type 'darwin)
11228 org-file-apps-defaults-macosx)
11229 ((eq system-type 'windows-nt)
11230 org-file-apps-defaults-windowsnt)
11231 (t org-file-apps-defaults-gnu)))
11233 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11234 "Convert extensions to regular expressions in the cars of LIST.
11235 Also, weed out any non-string entries, because the return value is used
11236 only for regexp matching.
11237 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11238 point to the symbol `emacs', indicating that the file should
11239 be opened in Emacs."
11240 (append
11241 (delq nil
11242 (mapcar (lambda (x)
11243 (if (not (stringp (car x)))
11245 (if (string-match "\\W" (car x))
11247 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11248 list))
11249 (if add-auto-mode
11250 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11252 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11253 (defun org-file-remote-p (file)
11254 "Test whether FILE specifies a location on a remote system.
11255 Return non-nil if the location is indeed remote.
11257 For example, the filename \"/user@host:/foo\" specifies a location
11258 on the system \"/user@host:\"."
11259 (cond ((fboundp 'file-remote-p)
11260 (file-remote-p file))
11261 ((fboundp 'tramp-handle-file-remote-p)
11262 (tramp-handle-file-remote-p file))
11263 ((and (boundp 'ange-ftp-name-format)
11264 (string-match (car ange-ftp-name-format) file))
11265 t)))
11268 ;;;; Refiling
11270 (defun org-get-org-file ()
11271 "Read a filename, with default directory `org-directory'."
11272 (let ((default (or org-default-notes-file remember-data-file)))
11273 (read-file-name (format "File name [%s]: " default)
11274 (file-name-as-directory org-directory)
11275 default)))
11277 (defun org-notes-order-reversed-p ()
11278 "Check if the current file should receive notes in reversed order."
11279 (cond
11280 ((not org-reverse-note-order) nil)
11281 ((eq t org-reverse-note-order) t)
11282 ((not (listp org-reverse-note-order)) nil)
11283 (t (catch 'exit
11284 (let ((all org-reverse-note-order)
11285 entry)
11286 (while (setq entry (pop all))
11287 (if (string-match (car entry) buffer-file-name)
11288 (throw 'exit (cdr entry))))
11289 nil)))))
11291 (defvar org-refile-target-table nil
11292 "The list of refile targets, created by `org-refile'.")
11294 (defvar org-agenda-new-buffers nil
11295 "Buffers created to visit agenda files.")
11297 (defvar org-refile-cache nil
11298 "Cache for refile targets.")
11300 (defvar org-refile-markers nil
11301 "All the markers used for caching refile locations.")
11303 (defun org-refile-marker (pos)
11304 "Get a new refile marker, but only if caching is in use."
11305 (if (not org-refile-use-cache)
11307 (let ((m (make-marker)))
11308 (move-marker m pos)
11309 (push m org-refile-markers)
11310 m)))
11312 (defun org-refile-cache-clear ()
11313 "Clear the refile cache and disable all the markers."
11314 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11315 (setq org-refile-markers nil)
11316 (setq org-refile-cache nil)
11317 (message "Refile cache has been cleared"))
11319 (defun org-refile-cache-check-set (set)
11320 "Check if all the markers in the cache still have live buffers."
11321 (let (marker)
11322 (catch 'exit
11323 (while (and set (setq marker (nth 3 (pop set))))
11324 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11325 (when (and marker (null (marker-buffer marker)))
11326 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11327 (sit-for 3)
11328 (throw 'exit nil)))
11329 t)))
11331 (defun org-refile-cache-put (set &rest identifiers)
11332 "Push the refile targets SET into the cache, under IDENTIFIERS."
11333 (let* ((key (sha1 (prin1-to-string identifiers)))
11334 (entry (assoc key org-refile-cache)))
11335 (if entry
11336 (setcdr entry set)
11337 (push (cons key set) org-refile-cache))))
11339 (defun org-refile-cache-get (&rest identifiers)
11340 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11341 (cond
11342 ((not org-refile-cache) nil)
11343 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11345 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11346 org-refile-cache))))
11347 (and set (org-refile-cache-check-set set) set)))))
11349 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11350 "Produce a table with refile targets."
11351 (let ((case-fold-search nil)
11352 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11353 (entries (or org-refile-targets '((nil . (:level . 1)))))
11354 targets tgs txt re files f desc descre fast-path-p level pos0)
11355 (message "Getting targets...")
11356 (with-current-buffer (or default-buffer (current-buffer))
11357 (while (setq entry (pop entries))
11358 (setq files (car entry) desc (cdr entry))
11359 (setq fast-path-p nil)
11360 (cond
11361 ((null files) (setq files (list (current-buffer))))
11362 ((eq files 'org-agenda-files)
11363 (setq files (org-agenda-files 'unrestricted)))
11364 ((and (symbolp files) (fboundp files))
11365 (setq files (funcall files)))
11366 ((and (symbolp files) (boundp files))
11367 (setq files (symbol-value files))))
11368 (if (stringp files) (setq files (list files)))
11369 (cond
11370 ((eq (car desc) :tag)
11371 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11372 ((eq (car desc) :todo)
11373 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11374 ((eq (car desc) :regexp)
11375 (setq descre (cdr desc)))
11376 ((eq (car desc) :level)
11377 (setq descre (concat "^\\*\\{" (number-to-string
11378 (if org-odd-levels-only
11379 (1- (* 2 (cdr desc)))
11380 (cdr desc)))
11381 "\\}[ \t]")))
11382 ((eq (car desc) :maxlevel)
11383 (setq fast-path-p t)
11384 (setq descre (concat "^\\*\\{1," (number-to-string
11385 (if org-odd-levels-only
11386 (1- (* 2 (cdr desc)))
11387 (cdr desc)))
11388 "\\}[ \t]")))
11389 (t (error "Bad refiling target description %s" desc)))
11390 (while (setq f (pop files))
11391 (with-current-buffer
11392 (if (bufferp f) f (org-get-agenda-file-buffer f))
11394 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11395 (progn
11396 (if (bufferp f) (setq f (buffer-file-name
11397 (buffer-base-buffer f))))
11398 (setq f (and f (expand-file-name f)))
11399 (if (eq org-refile-use-outline-path 'file)
11400 (push (list (file-name-nondirectory f) f nil nil) tgs))
11401 (save-excursion
11402 (save-restriction
11403 (widen)
11404 (goto-char (point-min))
11405 (while (re-search-forward descre nil t)
11406 (goto-char (setq pos0 (point-at-bol)))
11407 (catch 'next
11408 (when org-refile-target-verify-function
11409 (save-match-data
11410 (or (funcall org-refile-target-verify-function)
11411 (throw 'next t))))
11412 (when (and (looking-at org-complex-heading-regexp)
11413 (not (member (match-string 4) excluded-entries))
11414 (match-string 4))
11415 (setq level (org-reduced-level
11416 (- (match-end 1) (match-beginning 1)))
11417 txt (org-link-display-format (match-string 4))
11418 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11419 re (format org-complex-heading-regexp-format
11420 (regexp-quote (match-string 4))))
11421 (when org-refile-use-outline-path
11422 (setq txt (mapconcat
11423 'org-protect-slash
11424 (append
11425 (if (eq org-refile-use-outline-path
11426 'file)
11427 (list (file-name-nondirectory
11428 (buffer-file-name
11429 (buffer-base-buffer))))
11430 (if (eq org-refile-use-outline-path
11431 'full-file-path)
11432 (list (buffer-file-name
11433 (buffer-base-buffer)))))
11434 (org-get-outline-path fast-path-p
11435 level txt)
11436 (list txt))
11437 "/")))
11438 (push (list txt f re (org-refile-marker (point)))
11439 tgs)))
11440 (when (= (point) pos0)
11441 ;; verification function has not moved point
11442 (goto-char (point-at-eol))))))))
11443 (when org-refile-use-cache
11444 (org-refile-cache-put tgs (buffer-file-name) descre))
11445 (setq targets (append tgs targets))))))
11446 (message "Getting targets...done")
11447 (nreverse targets)))
11449 (defun org-protect-slash (s)
11450 (while (string-match "/" s)
11451 (setq s (replace-match "\\" t t s)))
11454 (defvar org-olpa (make-vector 20 nil))
11456 (defun org-get-outline-path (&optional fastp level heading)
11457 "Return the outline path to the current entry, as a list.
11459 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11460 routine which makes outline path derivations for an entire file,
11461 avoiding backtracing. Refile target collection makes use of that."
11462 (if fastp
11463 (progn
11464 (if (> level 19)
11465 (error "Outline path failure, more than 19 levels"))
11466 (loop for i from level upto 19 do
11467 (aset org-olpa i nil))
11468 (prog1
11469 (delq nil (append org-olpa nil))
11470 (aset org-olpa level heading)))
11471 (let (rtn case-fold-search)
11472 (save-excursion
11473 (save-restriction
11474 (widen)
11475 (while (org-up-heading-safe)
11476 (when (looking-at org-complex-heading-regexp)
11477 (push (org-trim
11478 (replace-regexp-in-string
11479 ;; Remove statistical/checkboxes cookies
11480 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11481 (org-match-string-no-properties 4)))
11482 rtn)))
11483 rtn)))))
11485 (defun org-format-outline-path (path &optional width prefix separator)
11486 "Format the outline path PATH for display.
11487 WIDTH is the maximum number of characters that is available.
11488 PREFIX is a prefix to be included in the returned string,
11489 such as the file name.
11490 SEPARATOR is inserted between the different parts of the path,
11491 the default is \"/\"."
11492 (setq width (or width 79))
11493 (if prefix (setq width (- width (length prefix))))
11494 (if (not path)
11495 (or prefix "")
11496 (let* ((nsteps (length path))
11497 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11498 (maxwidth (if (<= total-width width)
11499 10000 ;; everything fits
11500 ;; we need to shorten the level headings
11501 (/ (- width nsteps) nsteps)))
11502 (org-odd-levels-only nil)
11503 (n 0)
11504 (total (1+ (length prefix))))
11505 (setq maxwidth (max maxwidth 10))
11506 (concat prefix
11507 (if prefix (or separator "/"))
11508 (mapconcat
11509 (lambda (h)
11510 (setq n (1+ n))
11511 (if (and (= n nsteps) (< maxwidth 10000))
11512 (setq maxwidth (- total-width total)))
11513 (if (< (length h) maxwidth)
11514 (progn (setq total (+ total (length h) 1)) h)
11515 (setq h (substring h 0 (- maxwidth 2))
11516 total (+ total maxwidth 1))
11517 (if (string-match "[ \t]+\\'" h)
11518 (setq h (substring h 0 (match-beginning 0))))
11519 (setq h (concat h "..")))
11520 (org-add-props h nil 'face
11521 (nth (% (1- n) org-n-level-faces)
11522 org-level-faces))
11524 path (or separator "/"))))))
11526 (defun org-display-outline-path (&optional file current separator just-return-string)
11527 "Display the current outline path in the echo area.
11529 If FILE is non-nil, prepend the output with the file name.
11530 If CURRENT is non-nil, append the current heading to the output.
11531 SEPARATOR is passed through to `org-format-outline-path'. It separates
11532 the different parts of the path and defaults to \"/\".
11533 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11534 (interactive "P")
11535 (let* (case-fold-search
11536 (bfn (buffer-file-name (buffer-base-buffer)))
11537 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11538 res)
11539 (if current (setq path (append path
11540 (save-excursion
11541 (org-back-to-heading t)
11542 (if (looking-at org-complex-heading-regexp)
11543 (list (match-string 4)))))))
11544 (setq res
11545 (org-format-outline-path
11546 path
11547 (1- (frame-width))
11548 (and file bfn (concat (file-name-nondirectory bfn) separator))
11549 separator))
11550 (if just-return-string
11551 (org-no-properties res)
11552 (org-unlogged-message "%s" res))))
11554 (defvar org-refile-history nil
11555 "History for refiling operations.")
11557 (defvar org-after-refile-insert-hook nil
11558 "Hook run after `org-refile' has inserted its stuff at the new location.
11559 Note that this is still *before* the stuff will be removed from
11560 the *old* location.")
11562 (defvar org-capture-last-stored-marker)
11563 (defvar org-refile-keep nil
11564 "Non-nil means `org-refile' will copy instead of refile.")
11566 (defun org-copy ()
11567 "Like `org-refile', but copy."
11568 (interactive)
11569 (let ((org-refile-keep t))
11570 (funcall 'org-refile nil nil nil "Copy")))
11572 (defun org-refile (&optional goto default-buffer rfloc msg)
11573 "Move the entry or entries at point to another heading.
11574 The list of target headings is compiled using the information in
11575 `org-refile-targets', which see.
11577 At the target location, the entry is filed as a subitem of the target
11578 heading. Depending on `org-reverse-note-order', the new subitem will
11579 either be the first or the last subitem.
11581 If there is an active region, all entries in that region will be moved.
11582 However, the region must fulfill the requirement that the first heading
11583 is the first one sets the top-level of the moved text - at most siblings
11584 below it are allowed.
11586 With prefix arg GOTO, the command will only visit the target location
11587 and not actually move anything.
11589 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11590 go to the location where the last refiling operation has put the subtree.
11592 With a numeric prefix argument of `2', refile to the running clock.
11594 With a numeric prefix argument of `3', emulate `org-refile-keep'
11595 being set to `t' and copy to the target location, don't move it.
11596 Beware that keeping refiled entries may result in duplicated ID
11597 properties.
11599 RFLOC can be a refile location obtained in a different way.
11601 MSG is a string to replace \"Refile\" in the default prompt with
11602 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11604 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11606 If you are using target caching (see `org-refile-use-cache'),
11607 you have to clear the target cache in order to find new targets.
11608 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11609 prefix argument (`C-u C-u C-u C-c C-w')."
11611 (interactive "P")
11612 (if (member goto '(0 (64)))
11613 (org-refile-cache-clear)
11614 (let* ((actionmsg (or msg "Refile"))
11615 (cbuf (current-buffer))
11616 (regionp (org-region-active-p))
11617 (region-start (and regionp (region-beginning)))
11618 (region-end (and regionp (region-end)))
11619 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11620 (org-refile-keep (if (equal goto 3) t org-refile-keep))
11621 pos it nbuf file re level reversed)
11622 (setq last-command nil)
11623 (when regionp
11624 (goto-char region-start)
11625 (or (bolp) (goto-char (point-at-bol)))
11626 (setq region-start (point))
11627 (unless (or (org-kill-is-subtree-p
11628 (buffer-substring region-start region-end))
11629 (prog1 org-refile-active-region-within-subtree
11630 (let ((s (point-at-eol)))
11631 (org-toggle-heading)
11632 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11633 (user-error "The region is not a (sequence of) subtree(s)")))
11634 (if (equal goto '(16))
11635 (org-refile-goto-last-stored)
11636 (when (or
11637 (and (equal goto 2)
11638 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11639 (prog1
11640 (setq it (list (or org-clock-heading "running clock")
11641 (buffer-file-name
11642 (marker-buffer org-clock-hd-marker))
11644 (marker-position org-clock-hd-marker)))
11645 (setq goto nil)))
11646 (setq it (or rfloc
11647 (let (heading-text)
11648 (save-excursion
11649 (unless goto
11650 (org-back-to-heading t)
11651 (setq heading-text
11652 (nth 4 (org-heading-components))))
11654 (org-refile-get-location
11655 (cond (goto "Goto")
11656 (regionp (concat actionmsg " region to"))
11657 (t (concat actionmsg " subtree \""
11658 heading-text "\" to")))
11659 default-buffer
11660 (and (not (equal '(4) goto))
11661 org-refile-allow-creating-parent-nodes)
11662 goto))))))
11663 (setq file (nth 1 it)
11664 re (nth 2 it)
11665 pos (nth 3 it))
11666 (if (and (not goto)
11668 (equal (buffer-file-name) file)
11669 (if regionp
11670 (and (>= pos region-start)
11671 (<= pos region-end))
11672 (and (>= pos (point))
11673 (< pos (save-excursion
11674 (org-end-of-subtree t t))))))
11675 (error "Cannot refile to position inside the tree or region"))
11677 (setq nbuf (or (find-buffer-visiting file)
11678 (find-file-noselect file)))
11679 (if (and goto (not (equal goto 3)))
11680 (progn
11681 (org-pop-to-buffer-same-window nbuf)
11682 (goto-char pos)
11683 (org-show-context 'org-goto))
11684 (if regionp
11685 (progn
11686 (org-kill-new (buffer-substring region-start region-end))
11687 (org-save-markers-in-region region-start region-end))
11688 (org-copy-subtree 1 nil t))
11689 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11690 (find-file-noselect file)))
11691 (setq reversed (org-notes-order-reversed-p))
11692 (save-excursion
11693 (save-restriction
11694 (widen)
11695 (if pos
11696 (progn
11697 (goto-char pos)
11698 (looking-at org-outline-regexp)
11699 (setq level (org-get-valid-level (funcall outline-level) 1))
11700 (goto-char
11701 (if reversed
11702 (or (outline-next-heading) (point-max))
11703 (or (save-excursion (org-get-next-sibling))
11704 (org-end-of-subtree t t)
11705 (point-max)))))
11706 (setq level 1)
11707 (if (not reversed)
11708 (goto-char (point-max))
11709 (goto-char (point-min))
11710 (or (outline-next-heading) (goto-char (point-max)))))
11711 (if (not (bolp)) (newline))
11712 (org-paste-subtree level)
11713 (when org-log-refile
11714 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11715 (unless (eq org-log-refile 'note)
11716 (save-excursion (org-add-log-note))))
11717 (and org-auto-align-tags
11718 (let ((org-loop-over-headlines-in-active-region nil))
11719 (org-set-tags nil t)))
11720 (let ((bookmark-name (plist-get org-bookmark-names-plist
11721 :last-refile)))
11722 (when bookmark-name
11723 (with-demoted-errors
11724 (bookmark-set bookmark-name))))
11725 ;; If we are refiling for capture, make sure that the
11726 ;; last-capture pointers point here
11727 (when (org-bound-and-true-p org-refile-for-capture)
11728 (let ((bookmark-name (plist-get org-bookmark-names-plist
11729 :last-capture-marker)))
11730 (when bookmark-name
11731 (with-demoted-errors
11732 (bookmark-set bookmark-name))))
11733 (move-marker org-capture-last-stored-marker (point)))
11734 (if (fboundp 'deactivate-mark) (deactivate-mark))
11735 (run-hooks 'org-after-refile-insert-hook))))
11736 (unless org-refile-keep
11737 (if regionp
11738 (delete-region (point) (+ (point) (- region-end region-start)))
11739 (delete-region
11740 (and (org-back-to-heading t) (point))
11741 (min (buffer-size) (org-end-of-subtree t t) (point)))))
11742 (when (featurep 'org-inlinetask)
11743 (org-inlinetask-remove-END-maybe))
11744 (setq org-markers-to-move nil)
11745 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11747 (defun org-refile-goto-last-stored ()
11748 "Go to the location where the last refile was stored."
11749 (interactive)
11750 (bookmark-jump "org-refile-last-stored")
11751 (message "This is the location of the last refile"))
11753 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11754 no-exclude)
11755 "Prompt the user for a refile location, using PROMPT.
11756 PROMPT should not be suffixed with a colon and a space, because
11757 this function appends the default value from
11758 `org-refile-history' automatically, if that is not empty.
11759 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11760 this is used for the GOTO interface."
11761 (let ((org-refile-targets org-refile-targets)
11762 (org-refile-use-outline-path org-refile-use-outline-path)
11763 excluded-entries)
11764 (when (and (derived-mode-p 'org-mode)
11765 (not org-refile-use-cache)
11766 (not no-exclude))
11767 (org-map-tree
11768 (lambda()
11769 (setq excluded-entries
11770 (append excluded-entries (list (org-get-heading t t)))))))
11771 (setq org-refile-target-table
11772 (org-refile-get-targets default-buffer excluded-entries)))
11773 (unless org-refile-target-table
11774 (user-error "No refile targets"))
11775 (let* ((cbuf (current-buffer))
11776 (partial-completion-mode nil)
11777 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11778 (cfunc (if (and org-refile-use-outline-path
11779 org-outline-path-complete-in-steps)
11780 'org-olpath-completing-read
11781 'org-icompleting-read))
11782 (extra (if org-refile-use-outline-path "/" ""))
11783 (cbnex (concat (buffer-name) extra))
11784 (filename (and cfn (expand-file-name cfn)))
11785 (tbl (mapcar
11786 (lambda (x)
11787 (if (and (not (member org-refile-use-outline-path
11788 '(file full-file-path)))
11789 (not (equal filename (nth 1 x))))
11790 (cons (concat (car x) extra " ("
11791 (file-name-nondirectory (nth 1 x)) ")")
11792 (cdr x))
11793 (cons (concat (car x) extra) (cdr x))))
11794 org-refile-target-table))
11795 (completion-ignore-case t)
11796 cdef
11797 (prompt (concat prompt
11798 (or (and (car org-refile-history)
11799 (concat " (default " (car org-refile-history) ")"))
11800 (and (assoc cbnex tbl) (setq cdef cbnex)
11801 (concat " (default " cbnex ")"))) ": "))
11802 pa answ parent-target child parent old-hist)
11803 (setq old-hist org-refile-history)
11804 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11805 nil 'org-refile-history (or cdef (car org-refile-history))))
11806 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11807 (org-refile-check-position pa)
11808 (if pa
11809 (progn
11810 (when (or (not org-refile-history)
11811 (not (eq old-hist org-refile-history))
11812 (not (equal (car pa) (car org-refile-history))))
11813 (setq org-refile-history
11814 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11815 org-refile-history
11816 (cdr org-refile-history))))
11817 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11818 (pop org-refile-history)))
11820 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11821 (progn
11822 (setq parent (match-string 1 answ)
11823 child (match-string 2 answ))
11824 (setq parent-target (or (assoc parent tbl)
11825 (assoc (concat parent "/") tbl)))
11826 (when (and parent-target
11827 (or (eq new-nodes t)
11828 (and (eq new-nodes 'confirm)
11829 (y-or-n-p (format "Create new node \"%s\"? "
11830 child)))))
11831 (org-refile-new-child parent-target child)))
11832 (user-error "Invalid target location")))))
11834 (declare-function org-string-nw-p "org-macs" (s))
11835 (defun org-refile-check-position (refile-pointer)
11836 "Check if the refile pointer matches the headline to which it points."
11837 (let* ((file (nth 1 refile-pointer))
11838 (re (nth 2 refile-pointer))
11839 (pos (nth 3 refile-pointer))
11840 buffer)
11841 (if (and (not (markerp pos)) (not file))
11842 (if file
11843 (user-error "Please save the buffer to a file before refiling")
11844 (user-error "Please indicate a target file in the refile path"))
11845 (when (org-string-nw-p re)
11846 (setq buffer (if (markerp pos)
11847 (marker-buffer pos)
11848 (or (find-buffer-visiting file)
11849 (find-file-noselect file))))
11850 (with-current-buffer buffer
11851 (save-excursion
11852 (save-restriction
11853 (widen)
11854 (goto-char pos)
11855 (beginning-of-line 1)
11856 (unless (org-looking-at-p re)
11857 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11859 (defun org-refile-new-child (parent-target child)
11860 "Use refile target PARENT-TARGET to add new CHILD below it."
11861 (unless parent-target
11862 (error "Cannot find parent for new node"))
11863 (let ((file (nth 1 parent-target))
11864 (pos (nth 3 parent-target))
11865 level)
11866 (with-current-buffer (or (find-buffer-visiting file)
11867 (find-file-noselect file))
11868 (save-excursion
11869 (save-restriction
11870 (widen)
11871 (if pos
11872 (goto-char pos)
11873 (goto-char (point-max))
11874 (if (not (bolp)) (newline)))
11875 (when (looking-at org-outline-regexp)
11876 (setq level (funcall outline-level))
11877 (org-end-of-subtree t t))
11878 (org-back-over-empty-lines)
11879 (insert "\n" (make-string
11880 (if pos (org-get-valid-level level 1) 1) ?*)
11881 " " child "\n")
11882 (beginning-of-line 0)
11883 (list (concat (car parent-target) "/" child) file "" (point)))))))
11885 (defun org-olpath-completing-read (prompt collection &rest args)
11886 "Read an outline path like a file name."
11887 (let ((thetable collection)
11888 (org-completion-use-ido nil) ; does not work with ido.
11889 (org-completion-use-iswitchb nil)) ; or iswitchb
11890 (apply
11891 'org-icompleting-read prompt
11892 (lambda (string predicate &optional flag)
11893 (let (rtn r f (l (length string)))
11894 (cond
11895 ((eq flag nil)
11896 ;; try completion
11897 (try-completion string thetable))
11898 ((eq flag t)
11899 ;; all-completions
11900 (setq rtn (all-completions string thetable predicate))
11901 (mapcar
11902 (lambda (x)
11903 (setq r (substring x l))
11904 (if (string-match " ([^)]*)$" x)
11905 (setq f (match-string 0 x))
11906 (setq f ""))
11907 (if (string-match "/" r)
11908 (concat string (substring r 0 (match-end 0)) f)
11910 rtn))
11911 ((eq flag 'lambda)
11912 ;; exact match?
11913 (assoc string thetable)))))
11914 args)))
11916 ;;;; Dynamic blocks
11918 (defun org-find-dblock (name)
11919 "Find the first dynamic block with name NAME in the buffer.
11920 If not found, stay at current position and return nil."
11921 (let ((case-fold-search t) pos)
11922 (save-excursion
11923 (goto-char (point-min))
11924 (setq pos (and (re-search-forward
11925 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11926 (match-beginning 0))))
11927 (if pos (goto-char pos))
11928 pos))
11930 (defun org-create-dblock (plist)
11931 "Create a dynamic block section, with parameters taken from PLIST.
11932 PLIST must contain a :name entry which is used as name of the block."
11933 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11934 (end-of-line 1)
11935 (newline))
11936 (let ((col (current-column))
11937 (name (plist-get plist :name)))
11938 (insert "#+BEGIN: " name)
11939 (while plist
11940 (if (eq (car plist) :name)
11941 (setq plist (cddr plist))
11942 (insert " " (prin1-to-string (pop plist)))))
11943 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11944 (beginning-of-line -2)))
11946 (defun org-prepare-dblock ()
11947 "Prepare dynamic block for refresh.
11948 This empties the block, puts the cursor at the insert position and returns
11949 the property list including an extra property :name with the block name."
11950 (unless (looking-at org-dblock-start-re)
11951 (user-error "Not at a dynamic block"))
11952 (let* ((begdel (1+ (match-end 0)))
11953 (name (org-no-properties (match-string 1)))
11954 (params (append (list :name name)
11955 (read (concat "(" (match-string 3) ")")))))
11956 (save-excursion
11957 (beginning-of-line 1)
11958 (skip-chars-forward " \t")
11959 (setq params (plist-put params :indentation-column (current-column))))
11960 (unless (re-search-forward org-dblock-end-re nil t)
11961 (error "Dynamic block not terminated"))
11962 (setq params
11963 (append params
11964 (list :content (buffer-substring
11965 begdel (match-beginning 0)))))
11966 (delete-region begdel (match-beginning 0))
11967 (goto-char begdel)
11968 (open-line 1)
11969 params))
11971 (defun org-map-dblocks (&optional command)
11972 "Apply COMMAND to all dynamic blocks in the current buffer.
11973 If COMMAND is not given, use `org-update-dblock'."
11974 (let ((cmd (or command 'org-update-dblock)))
11975 (save-excursion
11976 (goto-char (point-min))
11977 (while (re-search-forward org-dblock-start-re nil t)
11978 (goto-char (match-beginning 0))
11979 (save-excursion
11980 (condition-case nil
11981 (funcall cmd)
11982 (error (message "Error during update of dynamic block"))))
11983 (unless (re-search-forward org-dblock-end-re nil t)
11984 (error "Dynamic block not terminated"))))))
11986 (defun org-dblock-update (&optional arg)
11987 "User command for updating dynamic blocks.
11988 Update the dynamic block at point. With prefix ARG, update all dynamic
11989 blocks in the buffer."
11990 (interactive "P")
11991 (if arg
11992 (org-update-all-dblocks)
11993 (or (looking-at org-dblock-start-re)
11994 (org-beginning-of-dblock))
11995 (org-update-dblock)))
11997 (defun org-update-dblock ()
11998 "Update the dynamic block at point.
11999 This means to empty the block, parse for parameters and then call
12000 the correct writing function."
12001 (interactive)
12002 (save-window-excursion
12003 (let* ((pos (point))
12004 (line (org-current-line))
12005 (params (org-prepare-dblock))
12006 (name (plist-get params :name))
12007 (indent (plist-get params :indentation-column))
12008 (cmd (intern (concat "org-dblock-write:" name))))
12009 (message "Updating dynamic block `%s' at line %d..." name line)
12010 (funcall cmd params)
12011 (message "Updating dynamic block `%s' at line %d...done" name line)
12012 (goto-char pos)
12013 (when (and indent (> indent 0))
12014 (setq indent (make-string indent ?\ ))
12015 (save-excursion
12016 (org-beginning-of-dblock)
12017 (forward-line 1)
12018 (while (not (looking-at org-dblock-end-re))
12019 (insert indent)
12020 (beginning-of-line 2))
12021 (when (looking-at org-dblock-end-re)
12022 (and (looking-at "[ \t]+")
12023 (replace-match ""))
12024 (insert indent)))))))
12026 (defun org-beginning-of-dblock ()
12027 "Find the beginning of the dynamic block at point.
12028 Error if there is no such block at point."
12029 (let ((pos (point))
12030 beg)
12031 (end-of-line 1)
12032 (if (and (re-search-backward org-dblock-start-re nil t)
12033 (setq beg (match-beginning 0))
12034 (re-search-forward org-dblock-end-re nil t)
12035 (> (match-end 0) pos))
12036 (goto-char beg)
12037 (goto-char pos)
12038 (error "Not in a dynamic block"))))
12040 (defun org-update-all-dblocks ()
12041 "Update all dynamic blocks in the buffer.
12042 This function can be used in a hook."
12043 (interactive)
12044 (when (derived-mode-p 'org-mode)
12045 (org-map-dblocks 'org-update-dblock)))
12048 ;;;; Completion
12050 (declare-function org-export-backend-name "org-export" (cl-x))
12051 (declare-function org-export-backend-options "org-export" (cl-x))
12052 (defun org-get-export-keywords ()
12053 "Return a list of all currently understood export keywords.
12054 Export keywords include options, block names, attributes and
12055 keywords relative to each registered export back-end."
12056 (let (keywords)
12057 (dolist (backend
12058 (org-bound-and-true-p org-export--registered-backends)
12059 (delq nil keywords))
12060 ;; Back-end name (for keywords, like #+LATEX:)
12061 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12062 (dolist (option-entry (org-export-backend-options backend))
12063 ;; Back-end options.
12064 (push (nth 1 option-entry) keywords)))))
12066 (defconst org-options-keywords
12067 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12068 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12069 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12070 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12071 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12073 (defcustom org-structure-template-alist
12074 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC" "<src lang=\"?\">\n\n</src>")
12075 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE" "<example>\n?\n</example>")
12076 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE" "<quote>\n?\n</quote>")
12077 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE" "<verse>\n?\n</verse>")
12078 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM" "<verbatim>\n?\n</verbatim>")
12079 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER" "<center>\n?\n</center>")
12080 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
12081 "<literal style=\"latex\">\n?\n</literal>")
12082 ("L" "#+LaTeX: " "<literal style=\"latex\">?</literal>")
12083 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
12084 "<literal style=\"html\">\n?\n</literal>")
12085 ("H" "#+HTML: " "<literal style=\"html\">?</literal>")
12086 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII" "")
12087 ("A" "#+ASCII: " "")
12088 ("i" "#+INDEX: ?" "#+INDEX: ?")
12089 ("I" "#+INCLUDE: %file ?"
12090 "<include file=%file markup=\"?\">"))
12091 "Structure completion elements.
12092 This is a list of abbreviation keys and values. The value gets inserted
12093 if you type `<' followed by the key and then press the completion key,
12094 usually `M-TAB'. %file will be replaced by a file name after prompting
12095 for the file using completion. The cursor will be placed at the position
12096 of the `?` in the template.
12097 There are two templates for each key, the first uses the original Org syntax,
12098 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12099 the default when the /org-mtags.el/ module has been loaded. See also the
12100 variable `org-mtags-prefer-muse-templates'."
12101 :group 'org-completion
12102 :type '(repeat
12103 (list
12104 (string :tag "Key")
12105 (string :tag "Template")
12106 (string :tag "Muse Template"))))
12108 (defun org-try-structure-completion ()
12109 "Try to complete a structure template before point.
12110 This looks for strings like \"<e\" on an otherwise empty line and
12111 expands them."
12112 (let ((l (buffer-substring (point-at-bol) (point)))
12114 (when (and (looking-at "[ \t]*$")
12115 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12116 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12117 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12118 (match-beginning 1)) a)
12119 t)))
12121 (defun org-complete-expand-structure-template (start cell)
12122 "Expand a structure template."
12123 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
12124 (rpl (nth (if musep 2 1) cell))
12125 (ind ""))
12126 (delete-region start (point))
12127 (when (string-match "\\`#\\+" rpl)
12128 (cond
12129 ((bolp))
12130 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12131 (setq ind (buffer-substring (point-at-bol) (point))))
12132 (t (newline))))
12133 (setq start (point))
12134 (if (string-match "%file" rpl)
12135 (setq rpl (replace-match
12136 (concat
12137 "\""
12138 (save-match-data
12139 (abbreviate-file-name (read-file-name "Include file: ")))
12140 "\"")
12141 t t rpl)))
12142 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12143 (concat "\n" ind)))
12144 (insert rpl)
12145 (if (re-search-backward "\\?" start t) (delete-char 1))))
12147 ;;;; TODO, DEADLINE, Comments
12149 (defun org-toggle-comment ()
12150 "Change the COMMENT state of an entry."
12151 (interactive)
12152 (save-excursion
12153 (org-back-to-heading)
12154 (let (case-fold-search)
12155 (cond
12156 ((looking-at (format org-heading-keyword-regexp-format
12157 org-comment-string))
12158 (goto-char (match-end 1))
12159 (looking-at (concat " +" org-comment-string))
12160 (replace-match "" t t)
12161 (when (eolp) (insert " ")))
12162 ((looking-at org-outline-regexp)
12163 (goto-char (match-end 0))
12164 (insert org-comment-string " "))))))
12166 (defvar org-last-todo-state-is-todo nil
12167 "This is non-nil when the last TODO state change led to a TODO state.
12168 If the last change removed the TODO tag or switched to DONE, then
12169 this is nil.")
12171 (defvar org-setting-tags nil) ; dynamically skipped
12173 (defvar org-todo-setup-filter-hook nil
12174 "Hook for functions that pre-filter todo specs.
12175 Each function takes a todo spec and returns either nil or the spec
12176 transformed into canonical form." )
12178 (defvar org-todo-get-default-hook nil
12179 "Hook for functions that get a default item for todo.
12180 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12181 nil or a string to be used for the todo mark." )
12183 (defvar org-agenda-headline-snapshot-before-repeat)
12185 (defun org-current-effective-time ()
12186 "Return current time adjusted for `org-extend-today-until' variable."
12187 (let* ((ct (org-current-time))
12188 (dct (decode-time ct))
12189 (ct1
12190 (cond
12191 (org-use-last-clock-out-time-as-effective-time
12192 (or (org-clock-get-last-clock-out-time) ct))
12193 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12194 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12195 (t ct))))
12196 ct1))
12198 (defun org-todo-yesterday (&optional arg)
12199 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12200 (interactive "P")
12201 (if (eq major-mode 'org-agenda-mode)
12202 (apply 'org-agenda-todo-yesterday arg)
12203 (let* ((hour (third (decode-time
12204 (org-current-time))))
12205 (org-extend-today-until (1+ hour)))
12206 (org-todo arg))))
12208 (defvar org-block-entry-blocking ""
12209 "First entry preventing the TODO state change.")
12211 (defun org-cancel-repeater ()
12212 "Cancel a repeater by setting its numeric value to zero."
12213 (interactive)
12214 (save-excursion
12215 (org-back-to-heading t)
12216 (let ((bound1 (point))
12217 (bound0 (save-excursion (outline-next-heading) (point))))
12218 (when (re-search-forward
12219 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12220 org-deadline-time-regexp "\\)\\|\\("
12221 org-ts-regexp "\\)")
12222 bound0 t)
12223 (if (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]" bound1 t)
12224 (replace-match "0" t nil nil 1))))))
12226 (defun org-todo (&optional arg)
12227 "Change the TODO state of an item.
12228 The state of an item is given by a keyword at the start of the heading,
12229 like
12230 *** TODO Write paper
12231 *** DONE Call mom
12233 The different keywords are specified in the variable `org-todo-keywords'.
12234 By default the available states are \"TODO\" and \"DONE\".
12235 So for this example: when the item starts with TODO, it is changed to DONE.
12236 When it starts with DONE, the DONE is removed. And when neither TODO nor
12237 DONE are present, add TODO at the beginning of the heading.
12239 With \\[universal-argument] prefix arg, use completion to determine the new \
12240 state.
12241 With numeric prefix arg, switch to that state.
12242 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12243 keywords (nextset).
12244 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12245 With a numeric prefix arg of 0, inhibit note taking for the change.
12246 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12248 When called through ELisp, arg is also interpreted in the following way:
12249 'none -> empty state
12250 \"\"(empty string) -> switch to empty state
12251 'done -> switch to DONE
12252 'nextset -> switch to the next set of keywords
12253 'previousset -> switch to the previous set of keywords
12254 \"WAITING\" -> switch to the specified keyword, but only if it
12255 really is a member of `org-todo-keywords'."
12256 (interactive "P")
12257 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12258 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12259 'region-start-level 'region))
12260 org-loop-over-headlines-in-active-region)
12261 (org-map-entries
12262 `(org-todo ,arg)
12263 org-loop-over-headlines-in-active-region
12264 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12265 (if (equal arg '(16)) (setq arg 'nextset))
12266 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12267 (let ((org-blocker-hook org-blocker-hook)
12268 commentp
12269 case-fold-search)
12270 (when (equal arg '(64))
12271 (setq arg nil org-blocker-hook nil))
12272 (when (and org-blocker-hook
12273 (or org-inhibit-blocking
12274 (org-entry-get nil "NOBLOCKING")))
12275 (setq org-blocker-hook nil))
12276 (save-excursion
12277 (catch 'exit
12278 (org-back-to-heading t)
12279 (when (looking-at (concat "^\\*+ " org-comment-string))
12280 (org-toggle-comment)
12281 (setq commentp t))
12282 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12283 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12284 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12285 (let* ((match-data (match-data))
12286 (startpos (point-at-bol))
12287 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12288 (org-log-done org-log-done)
12289 (org-log-repeat org-log-repeat)
12290 (org-todo-log-states org-todo-log-states)
12291 (org-inhibit-logging
12292 (if (equal arg 0)
12293 (progn (setq arg nil) 'note) org-inhibit-logging))
12294 (this (match-string 1))
12295 (hl-pos (match-beginning 0))
12296 (head (org-get-todo-sequence-head this))
12297 (ass (assoc head org-todo-kwd-alist))
12298 (interpret (nth 1 ass))
12299 (done-word (nth 3 ass))
12300 (final-done-word (nth 4 ass))
12301 (org-last-state (or this ""))
12302 (completion-ignore-case t)
12303 (member (member this org-todo-keywords-1))
12304 (tail (cdr member))
12305 (org-state (cond
12306 ((and org-todo-key-trigger
12307 (or (and (equal arg '(4))
12308 (eq org-use-fast-todo-selection 'prefix))
12309 (and (not arg) org-use-fast-todo-selection
12310 (not (eq org-use-fast-todo-selection
12311 'prefix)))))
12312 ;; Use fast selection
12313 (org-fast-todo-selection))
12314 ((and (equal arg '(4))
12315 (or (not org-use-fast-todo-selection)
12316 (not org-todo-key-trigger)))
12317 ;; Read a state with completion
12318 (org-icompleting-read
12319 "State: " (mapcar 'list org-todo-keywords-1)
12320 nil t))
12321 ((eq arg 'right)
12322 (if this
12323 (if tail (car tail) nil)
12324 (car org-todo-keywords-1)))
12325 ((eq arg 'left)
12326 (if (equal member org-todo-keywords-1)
12328 (if this
12329 (nth (- (length org-todo-keywords-1)
12330 (length tail) 2)
12331 org-todo-keywords-1)
12332 (org-last org-todo-keywords-1))))
12333 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12334 (setq arg nil))) ; hack to fall back to cycling
12335 (arg
12336 ;; user or caller requests a specific state
12337 (cond
12338 ((equal arg "") nil)
12339 ((eq arg 'none) nil)
12340 ((eq arg 'done) (or done-word (car org-done-keywords)))
12341 ((eq arg 'nextset)
12342 (or (car (cdr (member head org-todo-heads)))
12343 (car org-todo-heads)))
12344 ((eq arg 'previousset)
12345 (let ((org-todo-heads (reverse org-todo-heads)))
12346 (or (car (cdr (member head org-todo-heads)))
12347 (car org-todo-heads))))
12348 ((car (member arg org-todo-keywords-1)))
12349 ((stringp arg)
12350 (user-error "State `%s' not valid in this file" arg))
12351 ((nth (1- (prefix-numeric-value arg))
12352 org-todo-keywords-1))))
12353 ((null member) (or head (car org-todo-keywords-1)))
12354 ((equal this final-done-word) nil) ;; -> make empty
12355 ((null tail) nil) ;; -> first entry
12356 ((memq interpret '(type priority))
12357 (if (eq this-command last-command)
12358 (car tail)
12359 (if (> (length tail) 0)
12360 (or done-word (car org-done-keywords))
12361 nil)))
12363 (car tail))))
12364 (org-state (or
12365 (run-hook-with-args-until-success
12366 'org-todo-get-default-hook org-state org-last-state)
12367 org-state))
12368 (next (if org-state (concat " " org-state " ") " "))
12369 (change-plist (list :type 'todo-state-change :from this :to org-state
12370 :position startpos))
12371 dolog now-done-p)
12372 (when org-blocker-hook
12373 (setq org-last-todo-state-is-todo
12374 (not (member this org-done-keywords)))
12375 (unless (save-excursion
12376 (save-match-data
12377 (org-with-wide-buffer
12378 (run-hook-with-args-until-failure
12379 'org-blocker-hook change-plist))))
12380 (if (org-called-interactively-p 'interactive)
12381 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12382 this org-state org-block-entry-blocking)
12383 ;; fail silently
12384 (message "TODO state change from %s to %s blocked (by \"%s\")"
12385 this org-state org-block-entry-blocking)
12386 (throw 'exit nil))))
12387 (store-match-data match-data)
12388 (replace-match next t t)
12389 (unless (pos-visible-in-window-p hl-pos)
12390 (message "TODO state changed to %s" (org-trim next)))
12391 (unless head
12392 (setq head (org-get-todo-sequence-head org-state)
12393 ass (assoc head org-todo-kwd-alist)
12394 interpret (nth 1 ass)
12395 done-word (nth 3 ass)
12396 final-done-word (nth 4 ass)))
12397 (when (memq arg '(nextset previousset))
12398 (message "Keyword-Set %d/%d: %s"
12399 (- (length org-todo-sets) -1
12400 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12401 (length org-todo-sets)
12402 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12403 (setq org-last-todo-state-is-todo
12404 (not (member org-state org-done-keywords)))
12405 (setq now-done-p (and (member org-state org-done-keywords)
12406 (not (member this org-done-keywords))))
12407 (and logging (org-local-logging logging))
12408 (when (and (or org-todo-log-states org-log-done)
12409 (not (eq org-inhibit-logging t))
12410 (not (memq arg '(nextset previousset))))
12411 ;; we need to look at recording a time and note
12412 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12413 (nth 2 (assoc this org-todo-log-states))))
12414 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12415 (setq dolog 'time))
12416 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12417 (and org-state
12418 (member org-state org-not-done-keywords)
12419 (not (member this org-not-done-keywords))))
12420 ;; This is now a todo state and was not one before
12421 ;; If there was a CLOSED time stamp, get rid of it.
12422 (org-add-planning-info nil nil 'closed))
12423 (when (and now-done-p org-log-done)
12424 ;; It is now done, and it was not done before
12425 (org-add-planning-info 'closed (org-current-effective-time))
12426 (if (and (not dolog) (eq 'note org-log-done))
12427 (org-add-log-setup 'done org-state this 'findpos 'note)))
12428 (when (and org-state dolog)
12429 ;; This is a non-nil state, and we need to log it
12430 (org-add-log-setup 'state org-state this 'findpos dolog)))
12431 ;; Fixup tag positioning
12432 (org-todo-trigger-tag-changes org-state)
12433 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12434 (when org-provide-todo-statistics
12435 (org-update-parent-todo-statistics))
12436 (run-hooks 'org-after-todo-state-change-hook)
12437 (if (and arg (not (member org-state org-done-keywords)))
12438 (setq head (org-get-todo-sequence-head org-state)))
12439 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12440 ;; Do we need to trigger a repeat?
12441 (when now-done-p
12442 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12443 ;; This is for the agenda, take a snapshot of the headline.
12444 (save-match-data
12445 (setq org-agenda-headline-snapshot-before-repeat
12446 (org-get-heading))))
12447 (org-auto-repeat-maybe org-state))
12448 ;; Fixup cursor location if close to the keyword
12449 (if (and (outline-on-heading-p)
12450 (not (bolp))
12451 (save-excursion (beginning-of-line 1)
12452 (looking-at org-todo-line-regexp))
12453 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12454 (progn
12455 (goto-char (or (match-end 2) (match-end 1)))
12456 (and (looking-at " ") (just-one-space))))
12457 (when org-trigger-hook
12458 (save-excursion
12459 (run-hook-with-args 'org-trigger-hook change-plist)))
12460 (when commentp (org-toggle-comment))))))))
12462 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12463 "Block turning an entry into a TODO, using the hierarchy.
12464 This checks whether the current task should be blocked from state
12465 changes. Such blocking occurs when:
12467 1. The task has children which are not all in a completed state.
12469 2. A task has a parent with the property :ORDERED:, and there
12470 are siblings prior to the current task with incomplete
12471 status.
12473 3. The parent of the task is blocked because it has siblings that should
12474 be done first, or is child of a block grandparent TODO entry."
12476 (if (not org-enforce-todo-dependencies)
12477 t ; if locally turned off don't block
12478 (catch 'dont-block
12479 ;; If this is not a todo state change, or if this entry is already DONE,
12480 ;; do not block
12481 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12482 (member (plist-get change-plist :from)
12483 (cons 'done org-done-keywords))
12484 (member (plist-get change-plist :to)
12485 (cons 'todo org-not-done-keywords))
12486 (not (plist-get change-plist :to)))
12487 (throw 'dont-block t))
12488 ;; If this task has children, and any are undone, it's blocked
12489 (save-excursion
12490 (org-back-to-heading t)
12491 (let ((this-level (funcall outline-level)))
12492 (outline-next-heading)
12493 (let ((child-level (funcall outline-level)))
12494 (while (and (not (eobp))
12495 (> child-level this-level))
12496 ;; this todo has children, check whether they are all
12497 ;; completed
12498 (if (and (not (org-entry-is-done-p))
12499 (org-entry-is-todo-p))
12500 (progn (setq org-block-entry-blocking (org-get-heading))
12501 (throw 'dont-block nil)))
12502 (outline-next-heading)
12503 (setq child-level (funcall outline-level))))))
12504 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12505 ;; any previous siblings are undone, it's blocked
12506 (save-excursion
12507 (org-back-to-heading t)
12508 (let* ((pos (point))
12509 (parent-pos (and (org-up-heading-safe) (point))))
12510 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12511 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12512 (forward-line 1)
12513 (re-search-forward org-not-done-heading-regexp pos t))
12514 (setq org-block-entry-blocking (match-string 0))
12515 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12516 ;; Search further up the hierarchy, to see if an ancestor is blocked
12517 (while t
12518 (goto-char parent-pos)
12519 (if (not (looking-at org-not-done-heading-regexp))
12520 (throw 'dont-block t)) ; do not block, parent is not a TODO
12521 (setq pos (point))
12522 (setq parent-pos (and (org-up-heading-safe) (point)))
12523 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12524 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12525 (forward-line 1)
12526 (re-search-forward org-not-done-heading-regexp pos t)
12527 (setq org-block-entry-blocking (org-get-heading)))
12528 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12530 (defcustom org-track-ordered-property-with-tag nil
12531 "Should the ORDERED property also be shown as a tag?
12532 The ORDERED property decides if an entry should require subtasks to be
12533 completed in sequence. Since a property is not very visible, setting
12534 this option means that toggling the ORDERED property with the command
12535 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12536 not relevant for the behavior, but it makes things more visible.
12538 Note that toggling the tag with tags commands will not change the property
12539 and therefore not influence behavior!
12541 This can be t, meaning the tag ORDERED should be used, It can also be a
12542 string to select a different tag for this task."
12543 :group 'org-todo
12544 :type '(choice
12545 (const :tag "No tracking" nil)
12546 (const :tag "Track with ORDERED tag" t)
12547 (string :tag "Use other tag")))
12549 (defun org-toggle-ordered-property ()
12550 "Toggle the ORDERED property of the current entry.
12551 For better visibility, you can track the value of this property with a tag.
12552 See variable `org-track-ordered-property-with-tag'."
12553 (interactive)
12554 (let* ((t1 org-track-ordered-property-with-tag)
12555 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12556 (save-excursion
12557 (org-back-to-heading)
12558 (if (org-entry-get nil "ORDERED")
12559 (progn
12560 (org-delete-property "ORDERED")
12561 (and tag (org-toggle-tag tag 'off))
12562 (message "Subtasks can be completed in arbitrary order"))
12563 (org-entry-put nil "ORDERED" "t")
12564 (and tag (org-toggle-tag tag 'on))
12565 (message "Subtasks must be completed in sequence")))))
12567 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12568 (defun org-block-todo-from-checkboxes (change-plist)
12569 "Block turning an entry into a TODO, using checkboxes.
12570 This checks whether the current task should be blocked from state
12571 changes because there are unchecked boxes in this entry."
12572 (if (not org-enforce-todo-checkbox-dependencies)
12573 t ; if locally turned off don't block
12574 (catch 'dont-block
12575 ;; If this is not a todo state change, or if this entry is already DONE,
12576 ;; do not block
12577 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12578 (member (plist-get change-plist :from)
12579 (cons 'done org-done-keywords))
12580 (member (plist-get change-plist :to)
12581 (cons 'todo org-not-done-keywords))
12582 (not (plist-get change-plist :to)))
12583 (throw 'dont-block t))
12584 ;; If this task has checkboxes that are not checked, it's blocked
12585 (save-excursion
12586 (org-back-to-heading t)
12587 (let ((beg (point)) end)
12588 (outline-next-heading)
12589 (setq end (point))
12590 (goto-char beg)
12591 (if (org-list-search-forward
12592 (concat (org-item-beginning-re)
12593 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12594 "\\[[- ]\\]")
12595 end t)
12596 (progn
12597 (if (boundp 'org-blocked-by-checkboxes)
12598 (setq org-blocked-by-checkboxes t))
12599 (throw 'dont-block nil)))))
12600 t))) ; do not block
12602 (defun org-entry-blocked-p ()
12603 "Is the current entry blocked?"
12604 (org-with-silent-modifications
12605 (if (org-entry-get nil "NOBLOCKING")
12606 nil ;; Never block this entry
12607 (not (run-hook-with-args-until-failure
12608 'org-blocker-hook
12609 (list :type 'todo-state-change
12610 :position (point)
12611 :from 'todo
12612 :to 'done))))))
12614 (defun org-update-statistics-cookies (all)
12615 "Update the statistics cookie, either from TODO or from checkboxes.
12616 This should be called with the cursor in a line with a statistics cookie."
12617 (interactive "P")
12618 (if all
12619 (progn
12620 (org-update-checkbox-count 'all)
12621 (org-map-entries 'org-update-parent-todo-statistics))
12622 (if (not (org-at-heading-p))
12623 (org-update-checkbox-count)
12624 (let ((pos (point-marker))
12625 end l1 l2)
12626 (ignore-errors (org-back-to-heading t))
12627 (if (not (org-at-heading-p))
12628 (org-update-checkbox-count)
12629 (setq l1 (org-outline-level))
12630 (setq end (save-excursion
12631 (outline-next-heading)
12632 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12633 (point)))
12634 (if (and (save-excursion
12635 (re-search-forward
12636 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12637 (not (save-excursion (re-search-forward
12638 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12639 (org-update-checkbox-count)
12640 (if (and l2 (> l2 l1))
12641 (progn
12642 (goto-char end)
12643 (org-update-parent-todo-statistics))
12644 (goto-char pos)
12645 (beginning-of-line 1)
12646 (while (re-search-forward
12647 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12648 (point-at-eol) t)
12649 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12650 (goto-char pos)
12651 (move-marker pos nil)))))
12653 (defvar org-entry-property-inherited-from) ;; defined below
12654 (defun org-update-parent-todo-statistics ()
12655 "Update any statistics cookie in the parent of the current headline.
12656 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12657 the entire subtree and this will travel up the hierarchy and update
12658 statistics everywhere."
12659 (let* ((prop (save-excursion (org-up-heading-safe)
12660 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12661 (recursive (or (not org-hierarchical-todo-statistics)
12662 (and prop (string-match "\\<recursive\\>" prop))))
12663 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12665 (first t)
12666 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12667 level ltoggle l1 new ndel
12668 (cnt-all 0) (cnt-done 0) is-percent kwd
12669 checkbox-beg ov ovs ove cookie-present)
12670 (catch 'exit
12671 (save-excursion
12672 (beginning-of-line 1)
12673 (setq ltoggle (funcall outline-level))
12674 ;; Three situations are to consider:
12676 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12677 ;; to the top-level ancestor on the headline;
12679 ;; 2. If parent has "recursive" property, repeat up to the
12680 ;; headline setting that property, taking inheritance into
12681 ;; account;
12683 ;; 3. Else, move up to direct parent and proceed only once.
12684 (while (and (setq level (org-up-heading-safe))
12685 (or recursive first)
12686 (>= (point) lim))
12687 (setq first nil cookie-present nil)
12688 (unless (and level
12689 (not (string-match
12690 "\\<checkbox\\>"
12691 (downcase (or (org-entry-get nil "COOKIE_DATA")
12692 "")))))
12693 (throw 'exit nil))
12694 (while (re-search-forward box-re (point-at-eol) t)
12695 (setq cnt-all 0 cnt-done 0 cookie-present t)
12696 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12697 (save-match-data
12698 (unless (outline-next-heading) (throw 'exit nil))
12699 (while (and (looking-at org-complex-heading-regexp)
12700 (> (setq l1 (length (match-string 1))) level))
12701 (setq kwd (and (or recursive (= l1 ltoggle))
12702 (match-string 2)))
12703 (if (or (eq org-provide-todo-statistics 'all-headlines)
12704 (and (listp org-provide-todo-statistics)
12705 (or (member kwd org-provide-todo-statistics)
12706 (member kwd org-done-keywords))))
12707 (setq cnt-all (1+ cnt-all))
12708 (if (eq org-provide-todo-statistics t)
12709 (and kwd (setq cnt-all (1+ cnt-all)))))
12710 (and (member kwd org-done-keywords)
12711 (setq cnt-done (1+ cnt-done)))
12712 (outline-next-heading)))
12713 (setq new
12714 (if is-percent
12715 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12716 (format "[%d/%d]" cnt-done cnt-all))
12717 ndel (- (match-end 0) checkbox-beg))
12718 ;; handle overlays when updating cookie from column view
12719 (when (setq ov (car (overlays-at checkbox-beg)))
12720 (setq ovs (overlay-start ov) ove (overlay-end ov))
12721 (delete-overlay ov))
12722 (goto-char checkbox-beg)
12723 (insert new)
12724 (delete-region (point) (+ (point) ndel))
12725 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12726 (when ov (move-overlay ov ovs ove)))
12727 (when cookie-present
12728 (run-hook-with-args 'org-after-todo-statistics-hook
12729 cnt-done (- cnt-all cnt-done))))))
12730 (run-hooks 'org-todo-statistics-hook)))
12732 (defvar org-after-todo-statistics-hook nil
12733 "Hook that is called after a TODO statistics cookie has been updated.
12734 Each function is called with two arguments: the number of not-done entries
12735 and the number of done entries.
12737 For example, the following function, when added to this hook, will switch
12738 an entry to DONE when all children are done, and back to TODO when new
12739 entries are set to a TODO status. Note that this hook is only called
12740 when there is a statistics cookie in the headline!
12742 (defun org-summary-todo (n-done n-not-done)
12743 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12744 (let (org-log-done org-log-states) ; turn off logging
12745 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12748 (defvar org-todo-statistics-hook nil
12749 "Hook that is run whenever Org thinks TODO statistics should be updated.
12750 This hook runs even if there is no statistics cookie present, in which case
12751 `org-after-todo-statistics-hook' would not run.")
12753 (defun org-todo-trigger-tag-changes (state)
12754 "Apply the changes defined in `org-todo-state-tags-triggers'."
12755 (let ((l org-todo-state-tags-triggers)
12756 changes)
12757 (when (or (not state) (equal state ""))
12758 (setq changes (append changes (cdr (assoc "" l)))))
12759 (when (and (stringp state) (> (length state) 0))
12760 (setq changes (append changes (cdr (assoc state l)))))
12761 (when (member state org-not-done-keywords)
12762 (setq changes (append changes (cdr (assoc 'todo l)))))
12763 (when (member state org-done-keywords)
12764 (setq changes (append changes (cdr (assoc 'done l)))))
12765 (dolist (c changes)
12766 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12768 (defun org-local-logging (value)
12769 "Get logging settings from a property VALUE."
12770 (let* (words w a)
12771 ;; directly set the variables, they are already local.
12772 (setq org-log-done nil
12773 org-log-repeat nil
12774 org-todo-log-states nil)
12775 (setq words (org-split-string value))
12776 (while (setq w (pop words))
12777 (cond
12778 ((setq a (assoc w org-startup-options))
12779 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12780 (set (nth 1 a) (nth 2 a))))
12781 ((setq a (org-extract-log-state-settings w))
12782 (and (member (car a) org-todo-keywords-1)
12783 (push a org-todo-log-states)))))))
12785 (defun org-get-todo-sequence-head (kwd)
12786 "Return the head of the TODO sequence to which KWD belongs.
12787 If KWD is not set, check if there is a text property remembering the
12788 right sequence."
12789 (let (p)
12790 (cond
12791 ((not kwd)
12792 (or (get-text-property (point-at-bol) 'org-todo-head)
12793 (progn
12794 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12795 nil (point-at-eol)))
12796 (get-text-property p 'org-todo-head))))
12797 ((not (member kwd org-todo-keywords-1))
12798 (car org-todo-keywords-1))
12799 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12801 (defun org-fast-todo-selection ()
12802 "Fast TODO keyword selection with single keys.
12803 Returns the new TODO keyword, or nil if no state change should occur."
12804 (let* ((fulltable org-todo-key-alist)
12805 (done-keywords org-done-keywords) ;; needed for the faces.
12806 (maxlen (apply 'max (mapcar
12807 (lambda (x)
12808 (if (stringp (car x)) (string-width (car x)) 0))
12809 fulltable)))
12810 (expert nil)
12811 (fwidth (+ maxlen 3 1 3))
12812 (ncol (/ (- (window-width) 4) fwidth))
12813 tg cnt e c tbl
12814 groups ingroup)
12815 (save-excursion
12816 (save-window-excursion
12817 (if expert
12818 (set-buffer (get-buffer-create " *Org todo*"))
12819 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12820 (erase-buffer)
12821 (org-set-local 'org-done-keywords done-keywords)
12822 (setq tbl fulltable cnt 0)
12823 (while (setq e (pop tbl))
12824 (cond
12825 ((equal e '(:startgroup))
12826 (push '() groups) (setq ingroup t)
12827 (when (not (= cnt 0))
12828 (setq cnt 0)
12829 (insert "\n"))
12830 (insert "{ "))
12831 ((equal e '(:endgroup))
12832 (setq ingroup nil cnt 0)
12833 (insert "}\n"))
12834 ((equal e '(:newline))
12835 (when (not (= cnt 0))
12836 (setq cnt 0)
12837 (insert "\n")
12838 (setq e (car tbl))
12839 (while (equal (car tbl) '(:newline))
12840 (insert "\n")
12841 (setq tbl (cdr tbl)))))
12843 (setq tg (car e) c (cdr e))
12844 (if ingroup (push tg (car groups)))
12845 (setq tg (org-add-props tg nil 'face
12846 (org-get-todo-face tg)))
12847 (if (and (= cnt 0) (not ingroup)) (insert " "))
12848 (insert "[" c "] " tg (make-string
12849 (- fwidth 4 (length tg)) ?\ ))
12850 (when (= (setq cnt (1+ cnt)) ncol)
12851 (insert "\n")
12852 (if ingroup (insert " "))
12853 (setq cnt 0)))))
12854 (insert "\n")
12855 (goto-char (point-min))
12856 (if (not expert) (org-fit-window-to-buffer))
12857 (message "[a-z..]:Set [SPC]:clear")
12858 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12859 (cond
12860 ((or (= c ?\C-g)
12861 (and (= c ?q) (not (rassoc c fulltable))))
12862 (setq quit-flag t))
12863 ((= c ?\ ) nil)
12864 ((setq e (rassoc c fulltable) tg (car e))
12866 (t (setq quit-flag t)))))))
12868 (defun org-entry-is-todo-p ()
12869 (member (org-get-todo-state) org-not-done-keywords))
12871 (defun org-entry-is-done-p ()
12872 (member (org-get-todo-state) org-done-keywords))
12874 (defun org-get-todo-state ()
12875 "Return the TODO keyword of the current subtree."
12876 (save-excursion
12877 (org-back-to-heading t)
12878 (and (looking-at org-todo-line-regexp)
12879 (match-end 2)
12880 (match-string 2))))
12882 (defun org-at-date-range-p (&optional inactive-ok)
12883 "Is the cursor inside a date range?"
12884 (interactive)
12885 (save-excursion
12886 (catch 'exit
12887 (let ((pos (point)))
12888 (skip-chars-backward "^[<\r\n")
12889 (skip-chars-backward "<[")
12890 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12891 (>= (match-end 0) pos)
12892 (throw 'exit t))
12893 (skip-chars-backward "^<[\r\n")
12894 (skip-chars-backward "<[")
12895 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12896 (>= (match-end 0) pos)
12897 (throw 'exit t)))
12898 nil)))
12900 (defun org-get-repeat (&optional tagline)
12901 "Check if there is a deadline/schedule with repeater in this entry."
12902 (save-match-data
12903 (save-excursion
12904 (org-back-to-heading t)
12905 (and (re-search-forward (if tagline
12906 (concat tagline "\\s-*" org-repeat-re)
12907 org-repeat-re)
12908 (org-entry-end-position) t)
12909 (match-string-no-properties 1)))))
12911 (defvar org-last-changed-timestamp)
12912 (defvar org-last-inserted-timestamp)
12913 (defvar org-log-post-message)
12914 (defvar org-log-note-purpose)
12915 (defvar org-log-note-how)
12916 (defvar org-log-note-extra)
12917 (defun org-auto-repeat-maybe (done-word)
12918 "Check if the current headline contains a repeated deadline/schedule.
12919 If yes, set TODO state back to what it was and change the base date
12920 of repeating deadline/scheduled time stamps to new date.
12921 This function is run automatically after each state change to a DONE state."
12922 ;; last-state is dynamically scoped into this function
12923 (let* ((repeat (org-get-repeat))
12924 (aa (assoc org-last-state org-todo-kwd-alist))
12925 (interpret (nth 1 aa))
12926 (head (nth 2 aa))
12927 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12928 (msg "Entry repeats: ")
12929 (org-log-done nil)
12930 (org-todo-log-states nil)
12931 re type n what ts time to-state)
12932 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
12933 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12934 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12935 org-todo-repeat-to-state))
12936 (unless (and to-state (member to-state org-todo-keywords-1))
12937 (setq to-state (if (eq interpret 'type) org-last-state head)))
12938 (org-todo to-state)
12939 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12940 (org-entry-put nil "LAST_REPEAT" (format-time-string
12941 (org-time-stamp-format t t))))
12942 (when org-log-repeat
12943 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12944 (memq 'org-add-log-note post-command-hook))
12945 ;; OK, we are already setup for some record
12946 (if (eq org-log-repeat 'note)
12947 ;; make sure we take a note, not only a time stamp
12948 (setq org-log-note-how 'note))
12949 ;; Set up for taking a record
12950 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12951 org-last-state
12952 'findpos org-log-repeat)))
12953 (org-back-to-heading t)
12954 (org-add-planning-info nil nil 'closed)
12955 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12956 org-deadline-time-regexp "\\)\\|\\("
12957 org-ts-regexp "\\)"))
12958 (while (re-search-forward
12959 re (save-excursion (outline-next-heading) (point)) t)
12960 (setq type (if (match-end 1) org-scheduled-string
12961 (if (match-end 3) org-deadline-string "Plain:"))
12962 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12963 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12964 (setq n (string-to-number (match-string 2 ts))
12965 what (match-string 3 ts))
12966 (if (equal what "w") (setq n (* n 7) what "d"))
12967 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12968 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12969 ;; Preparation, see if we need to modify the start date for the change
12970 (when (match-end 1)
12971 (setq time (save-match-data (org-time-string-to-time ts)))
12972 (cond
12973 ((equal (match-string 1 ts) ".")
12974 ;; Shift starting date to today
12975 (org-timestamp-change
12976 (- (org-today) (time-to-days time))
12977 'day))
12978 ((equal (match-string 1 ts) "+")
12979 (let ((nshiftmax 10) (nshift 0))
12980 (while (or (= nshift 0)
12981 (<= (time-to-days time)
12982 (time-to-days (current-time))))
12983 (when (= (incf nshift) nshiftmax)
12984 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12985 (error "Abort")))
12986 (org-timestamp-change n (cdr (assoc what whata)))
12987 (org-at-timestamp-p t)
12988 (setq ts (match-string 1))
12989 (setq time (save-match-data (org-time-string-to-time ts)))))
12990 (org-timestamp-change (- n) (cdr (assoc what whata)))
12991 ;; rematch, so that we have everything in place for the real shift
12992 (org-at-timestamp-p t)
12993 (setq ts (match-string 1))
12994 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12995 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12996 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12997 (setq org-log-post-message msg)
12998 (message "%s" msg))))
13000 (defun org-show-todo-tree (arg)
13001 "Make a compact tree which shows all headlines marked with TODO.
13002 The tree will show the lines where the regexp matches, and all higher
13003 headlines above the match.
13004 With a \\[universal-argument] prefix, prompt for a regexp to match.
13005 With a numeric prefix N, construct a sparse tree for the Nth element
13006 of `org-todo-keywords-1'."
13007 (interactive "P")
13008 (let ((case-fold-search nil)
13009 (kwd-re
13010 (cond ((null arg) org-not-done-regexp)
13011 ((equal arg '(4))
13012 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
13013 (mapcar 'list org-todo-keywords-1))))
13014 (concat "\\("
13015 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13016 "\\)\\>")))
13017 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13018 (regexp-quote (nth (1- (prefix-numeric-value arg))
13019 org-todo-keywords-1)))
13020 (t (user-error "Invalid prefix argument: %s" arg)))))
13021 (message "%d TODO entries found"
13022 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13024 (defun org-deadline (arg &optional time)
13025 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13026 With one universal prefix argument, remove any deadline from the item.
13027 With two universal prefix arguments, prompt for a warning delay.
13028 With argument TIME, set the deadline at the corresponding date. TIME
13029 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13030 (interactive "P")
13031 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13032 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13033 'region-start-level 'region))
13034 org-loop-over-headlines-in-active-region)
13035 (org-map-entries
13036 `(org-deadline ',arg ,time)
13037 org-loop-over-headlines-in-active-region
13038 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13039 (let* ((old-date (org-entry-get nil "DEADLINE"))
13040 (old-date-time (if old-date (org-time-string-to-time old-date)))
13041 (repeater (and old-date
13042 (string-match
13043 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13044 old-date)
13045 (match-string 1 old-date))))
13046 (cond
13047 ((equal arg '(4))
13048 (when (and old-date org-log-redeadline)
13049 (org-add-log-setup 'deldeadline nil old-date 'findpos
13050 org-log-redeadline))
13051 (org-remove-timestamp-with-keyword org-deadline-string)
13052 (message "Item no longer has a deadline."))
13053 ((equal arg '(16))
13054 (save-excursion
13055 (org-back-to-heading t)
13056 (if (re-search-forward
13057 org-deadline-time-regexp
13058 (save-excursion (outline-next-heading) (point)) t)
13059 (let* ((rpl0 (match-string 1))
13060 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13061 (replace-match
13062 (concat org-deadline-string
13063 " <" rpl
13064 (format " -%dd"
13065 (abs
13066 (- (time-to-days
13067 (save-match-data
13068 (org-read-date nil t nil "Warn starting from" old-date-time)))
13069 (time-to-days old-date-time))))
13070 ">") t t))
13071 (user-error "No deadline information to update"))))
13073 (org-add-planning-info 'deadline time 'closed)
13074 (when (and old-date org-log-redeadline
13075 (not (equal old-date
13076 (substring org-last-inserted-timestamp 1 -1))))
13077 (org-add-log-setup 'redeadline nil old-date 'findpos
13078 org-log-redeadline))
13079 (when repeater
13080 (save-excursion
13081 (org-back-to-heading t)
13082 (when (re-search-forward (concat org-deadline-string " "
13083 org-last-inserted-timestamp)
13084 (save-excursion
13085 (outline-next-heading) (point)) t)
13086 (goto-char (1- (match-end 0)))
13087 (insert " " repeater)
13088 (setq org-last-inserted-timestamp
13089 (concat (substring org-last-inserted-timestamp 0 -1)
13090 " " repeater
13091 (substring org-last-inserted-timestamp -1))))))
13092 (message "Deadline on %s" org-last-inserted-timestamp))))))
13094 (defun org-schedule (arg &optional time)
13095 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13096 With one universal prefix argument, remove any scheduling date from the item.
13097 With two universal prefix arguments, prompt for a delay cookie.
13098 With argument TIME, scheduled at the corresponding date. TIME can
13099 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13100 (interactive "P")
13101 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13102 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13103 'region-start-level 'region))
13104 org-loop-over-headlines-in-active-region)
13105 (org-map-entries
13106 `(org-schedule ',arg ,time)
13107 org-loop-over-headlines-in-active-region
13108 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13109 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13110 (old-date-time (if old-date (org-time-string-to-time old-date)))
13111 (repeater (and old-date
13112 (string-match
13113 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13114 old-date)
13115 (match-string 1 old-date))))
13116 (cond
13117 ((equal arg '(4))
13118 (progn
13119 (when (and old-date org-log-reschedule)
13120 (org-add-log-setup 'delschedule nil old-date 'findpos
13121 org-log-reschedule))
13122 (org-remove-timestamp-with-keyword org-scheduled-string)
13123 (message "Item is no longer scheduled.")))
13124 ((equal arg '(16))
13125 (save-excursion
13126 (org-back-to-heading t)
13127 (if (re-search-forward
13128 org-scheduled-time-regexp
13129 (save-excursion (outline-next-heading) (point)) t)
13130 (let* ((rpl0 (match-string 1))
13131 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13132 (replace-match
13133 (concat org-scheduled-string
13134 " <" rpl
13135 (format " -%dd"
13136 (abs
13137 (- (time-to-days
13138 (save-match-data
13139 (org-read-date nil t nil "Delay until" old-date-time)))
13140 (time-to-days old-date-time))))
13141 ">") t t))
13142 (user-error "No scheduled information to update"))))
13144 (org-add-planning-info 'scheduled time 'closed)
13145 (when (and old-date org-log-reschedule
13146 (not (equal old-date
13147 (substring org-last-inserted-timestamp 1 -1))))
13148 (org-add-log-setup 'reschedule nil old-date 'findpos
13149 org-log-reschedule))
13150 (when repeater
13151 (save-excursion
13152 (org-back-to-heading t)
13153 (when (re-search-forward (concat org-scheduled-string " "
13154 org-last-inserted-timestamp)
13155 (save-excursion
13156 (outline-next-heading) (point)) t)
13157 (goto-char (1- (match-end 0)))
13158 (insert " " repeater)
13159 (setq org-last-inserted-timestamp
13160 (concat (substring org-last-inserted-timestamp 0 -1)
13161 " " repeater
13162 (substring org-last-inserted-timestamp -1))))))
13163 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13165 (defun org-get-scheduled-time (pom &optional inherit)
13166 "Get the scheduled time as a time tuple, of a format suitable
13167 for calling org-schedule with, or if there is no scheduling,
13168 returns nil."
13169 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13170 (when time
13171 (apply 'encode-time (org-parse-time-string time)))))
13173 (defun org-get-deadline-time (pom &optional inherit)
13174 "Get the deadline as a time tuple, of a format suitable for
13175 calling org-deadline with, or if there is no scheduling, returns
13176 nil."
13177 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13178 (when time
13179 (apply 'encode-time (org-parse-time-string time)))))
13181 (defun org-remove-timestamp-with-keyword (keyword)
13182 "Remove all time stamps with KEYWORD in the current entry."
13183 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13184 beg)
13185 (save-excursion
13186 (org-back-to-heading t)
13187 (setq beg (point))
13188 (outline-next-heading)
13189 (while (re-search-backward re beg t)
13190 (replace-match "")
13191 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13192 (equal (char-before) ?\ ))
13193 (backward-delete-char 1)
13194 (if (string-match "^[ \t]*$" (buffer-substring
13195 (point-at-bol) (point-at-eol)))
13196 (delete-region (point-at-bol)
13197 (min (point-max) (1+ (point-at-eol))))))))))
13199 (defvar org-time-was-given) ; dynamically scoped parameter
13200 (defvar org-end-time-was-given) ; dynamically scoped parameter
13202 (defun org-add-planning-info (what &optional time &rest remove)
13203 "Insert new timestamp with keyword in the line directly after the headline.
13204 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13205 If non is given, the user is prompted for a date.
13206 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13207 be removed."
13208 (interactive)
13209 (let (org-time-was-given org-end-time-was-given ts
13210 end default-time default-input)
13212 (catch 'exit
13213 (when (and (memq what '(scheduled deadline))
13214 (or (not time)
13215 (and (stringp time)
13216 (string-match "^[-+]+[0-9]" time))))
13217 ;; Try to get a default date/time from existing timestamp
13218 (save-excursion
13219 (org-back-to-heading t)
13220 (setq end (save-excursion (outline-next-heading) (point)))
13221 (when (re-search-forward (if (eq what 'scheduled)
13222 org-scheduled-time-regexp
13223 org-deadline-time-regexp)
13224 end t)
13225 (setq ts (match-string 1)
13226 default-time
13227 (apply 'encode-time (org-parse-time-string ts))
13228 default-input (and ts (org-get-compact-tod ts))))))
13229 (when what
13230 (setq time
13231 (if (stringp time)
13232 ;; This is a string (relative or absolute), set proper date
13233 (apply 'encode-time
13234 (org-read-date-analyze
13235 time default-time (decode-time default-time)))
13236 ;; If necessary, get the time from the user
13237 (or time (org-read-date nil 'to-time nil nil
13238 default-time default-input)))))
13240 (when (and org-insert-labeled-timestamps-at-point
13241 (member what '(scheduled deadline)))
13242 (insert
13243 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13244 (org-insert-time-stamp time org-time-was-given
13245 nil nil nil (list org-end-time-was-given))
13246 (setq what nil))
13247 (save-excursion
13248 (save-restriction
13249 (let (col list elt ts buffer-invisibility-spec)
13250 (org-back-to-heading t)
13251 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13252 (goto-char (match-end 1))
13253 (setq col (current-column))
13254 (goto-char (match-end 0))
13255 (if (eobp) (insert "\n") (forward-char 1))
13256 (when (and (not what)
13257 (not (looking-at
13258 (concat "[ \t]*"
13259 org-keyword-time-not-clock-regexp))))
13260 ;; Nothing to add, nothing to remove...... :-)
13261 (throw 'exit nil))
13262 (if (and (not (looking-at org-outline-regexp))
13263 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13264 "[^\r\n]*"))
13265 (not (equal (match-string 1) org-clock-string)))
13266 (narrow-to-region (match-beginning 0) (match-end 0))
13267 (insert-before-markers "\n")
13268 (backward-char 1)
13269 (narrow-to-region (point) (point))
13270 (and org-adapt-indentation (org-indent-to-column col)))
13271 ;; Check if we have to remove something.
13272 (setq list (cons what remove))
13273 (while list
13274 (setq elt (pop list))
13275 (when (or (and (eq elt 'scheduled)
13276 (re-search-forward org-scheduled-time-regexp nil t))
13277 (and (eq elt 'deadline)
13278 (re-search-forward org-deadline-time-regexp nil t))
13279 (and (eq elt 'closed)
13280 (re-search-forward org-closed-time-regexp nil t)))
13281 (replace-match "")
13282 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13283 (and (looking-at "[ \t]+") (replace-match ""))
13284 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13285 (when what
13286 (insert
13287 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13288 (cond ((eq what 'scheduled) org-scheduled-string)
13289 ((eq what 'deadline) org-deadline-string)
13290 ((eq what 'closed) org-closed-string))
13291 " ")
13292 (setq ts (org-insert-time-stamp
13293 time
13294 (or org-time-was-given
13295 (and (eq what 'closed) org-log-done-with-time))
13296 (eq what 'closed)
13297 nil nil (list org-end-time-was-given)))
13298 (insert
13299 (if (not (or (bolp) (eq (char-before) ?\ )
13300 (memq (char-after) '(32 10))
13301 (eobp))) " " ""))
13302 (end-of-line 1))
13303 (goto-char (point-min))
13304 (widen)
13305 (if (and (looking-at "[ \t]*\n")
13306 (equal (char-before) ?\n))
13307 (delete-region (1- (point)) (point-at-eol)))
13308 ts))))))
13310 (defvar org-log-note-marker (make-marker))
13311 (defvar org-log-note-purpose nil)
13312 (defvar org-log-note-state nil)
13313 (defvar org-log-note-previous-state nil)
13314 (defvar org-log-note-how nil)
13315 (defvar org-log-note-extra nil)
13316 (defvar org-log-note-window-configuration nil)
13317 (defvar org-log-note-return-to (make-marker))
13318 (defvar org-log-note-effective-time nil
13319 "Remembered current time so that dynamically scoped
13320 `org-extend-today-until' affects tha timestamps in state change
13321 log")
13323 (defvar org-log-post-message nil
13324 "Message to be displayed after a log note has been stored.
13325 The auto-repeater uses this.")
13327 (defun org-add-note ()
13328 "Add a note to the current entry.
13329 This is done in the same way as adding a state change note."
13330 (interactive)
13331 (org-add-log-setup 'note nil nil 'findpos nil))
13333 (defvar org-property-end-re)
13334 (defun org-add-log-setup (&optional purpose state prev-state
13335 findpos how extra)
13336 "Set up the post command hook to take a note.
13337 If this is about to TODO state change, the new state is expected in STATE.
13338 When FINDPOS is non-nil, find the correct position for the note in
13339 the current entry. If not, assume that it can be inserted at point.
13340 HOW is an indicator what kind of note should be created.
13341 EXTRA is additional text that will be inserted into the notes buffer."
13342 (let* ((org-log-into-drawer (org-log-into-drawer))
13343 (drawer (cond ((stringp org-log-into-drawer)
13344 org-log-into-drawer)
13345 (org-log-into-drawer "LOGBOOK"))))
13346 (save-restriction
13347 (save-excursion
13348 (when findpos
13349 (org-back-to-heading t)
13350 (narrow-to-region (point) (save-excursion
13351 (outline-next-heading) (point)))
13352 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13353 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13354 "[^\r\n]*\\)?"))
13355 (goto-char (match-end 0))
13356 (cond
13357 (drawer
13358 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13359 nil t)
13360 (progn
13361 (goto-char (match-end 0))
13362 (or org-log-states-order-reversed
13363 (and (re-search-forward org-property-end-re nil t)
13364 (goto-char (1- (match-beginning 0))))))
13365 (insert "\n:" drawer ":\n:END:")
13366 (beginning-of-line 0)
13367 (org-indent-line)
13368 (beginning-of-line 2)
13369 (org-indent-line)
13370 (end-of-line 0)))
13371 ((and org-log-state-notes-insert-after-drawers
13372 (save-excursion
13373 (forward-line) (looking-at org-drawer-regexp)))
13374 (forward-line)
13375 (while (looking-at org-drawer-regexp)
13376 (goto-char (match-end 0))
13377 (re-search-forward org-property-end-re (point-max) t)
13378 (forward-line))
13379 (forward-line -1)))
13380 (unless org-log-states-order-reversed
13381 (and (= (char-after) ?\n) (forward-char 1))
13382 (org-skip-over-state-notes)
13383 (skip-chars-backward " \t\n\r")))
13384 (move-marker org-log-note-marker (point))
13385 (setq org-log-note-purpose purpose
13386 org-log-note-state state
13387 org-log-note-previous-state prev-state
13388 org-log-note-how how
13389 org-log-note-extra extra
13390 org-log-note-effective-time (org-current-effective-time))
13391 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13393 (defun org-skip-over-state-notes ()
13394 "Skip past the list of State notes in an entry."
13395 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13396 (when (ignore-errors (goto-char (org-in-item-p)))
13397 (let* ((struct (org-list-struct))
13398 (prevs (org-list-prevs-alist struct)))
13399 (while (looking-at "[ \t]*- State")
13400 (goto-char (or (org-list-get-next-item (point) struct prevs)
13401 (org-list-get-item-end (point) struct)))))))
13403 (defun org-add-log-note (&optional purpose)
13404 "Pop up a window for taking a note, and add this note later at point."
13405 (remove-hook 'post-command-hook 'org-add-log-note)
13406 (setq org-log-note-window-configuration (current-window-configuration))
13407 (delete-other-windows)
13408 (move-marker org-log-note-return-to (point))
13409 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13410 (goto-char org-log-note-marker)
13411 (org-switch-to-buffer-other-window "*Org Note*")
13412 (erase-buffer)
13413 (if (memq org-log-note-how '(time state))
13414 (let (current-prefix-arg) (org-store-log-note))
13415 (let ((org-inhibit-startup t)) (org-mode))
13416 (insert (format "# Insert note for %s.
13417 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13418 (cond
13419 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13420 ((eq org-log-note-purpose 'done) "closed todo item")
13421 ((eq org-log-note-purpose 'state)
13422 (format "state change from \"%s\" to \"%s\""
13423 (or org-log-note-previous-state "")
13424 (or org-log-note-state "")))
13425 ((eq org-log-note-purpose 'reschedule)
13426 "rescheduling")
13427 ((eq org-log-note-purpose 'delschedule)
13428 "no longer scheduled")
13429 ((eq org-log-note-purpose 'redeadline)
13430 "changing deadline")
13431 ((eq org-log-note-purpose 'deldeadline)
13432 "removing deadline")
13433 ((eq org-log-note-purpose 'refile)
13434 "refiling")
13435 ((eq org-log-note-purpose 'note)
13436 "this entry")
13437 (t (error "This should not happen")))))
13438 (if org-log-note-extra (insert org-log-note-extra))
13439 (org-set-local 'org-finish-function 'org-store-log-note)
13440 (run-hooks 'org-log-buffer-setup-hook)))
13442 (defvar org-note-abort nil) ; dynamically scoped
13443 (defun org-store-log-note ()
13444 "Finish taking a log note, and insert it to where it belongs."
13445 (let ((txt (buffer-string)))
13446 (kill-buffer (current-buffer))
13447 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13448 lines ind bul)
13449 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13450 (setq txt (replace-match "" t t txt)))
13451 (if (string-match "\\s-+\\'" txt)
13452 (setq txt (replace-match "" t t txt)))
13453 (setq lines (org-split-string txt "\n"))
13454 (when (and note (string-match "\\S-" note))
13455 (setq note
13456 (org-replace-escapes
13457 note
13458 (list (cons "%u" (user-login-name))
13459 (cons "%U" user-full-name)
13460 (cons "%t" (format-time-string
13461 (org-time-stamp-format 'long 'inactive)
13462 org-log-note-effective-time))
13463 (cons "%T" (format-time-string
13464 (org-time-stamp-format 'long nil)
13465 org-log-note-effective-time))
13466 (cons "%d" (format-time-string
13467 (org-time-stamp-format nil 'inactive)
13468 org-log-note-effective-time))
13469 (cons "%D" (format-time-string
13470 (org-time-stamp-format nil nil)
13471 org-log-note-effective-time))
13472 (cons "%s" (if org-log-note-state
13473 (concat "\"" org-log-note-state "\"")
13474 ""))
13475 (cons "%S" (if org-log-note-previous-state
13476 (concat "\"" org-log-note-previous-state "\"")
13477 "\"\"")))))
13478 (if lines (setq note (concat note " \\\\")))
13479 (push note lines))
13480 (when (or current-prefix-arg org-note-abort)
13481 (when org-log-into-drawer
13482 (org-remove-empty-drawer-at org-log-note-marker))
13483 (setq lines nil))
13484 (when lines
13485 (with-current-buffer (marker-buffer org-log-note-marker)
13486 (save-excursion
13487 (goto-char org-log-note-marker)
13488 (move-marker org-log-note-marker nil)
13489 (end-of-line 1)
13490 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13491 (setq ind (save-excursion
13492 (if (ignore-errors (goto-char (org-in-item-p)))
13493 (let ((struct (org-list-struct)))
13494 (org-list-get-ind
13495 (org-list-get-top-point struct) struct))
13496 (skip-chars-backward " \r\t\n")
13497 (cond
13498 ((and (org-at-heading-p)
13499 org-adapt-indentation)
13500 (1+ (org-current-level)))
13501 ((org-at-heading-p) 0)
13502 (t (org-get-indentation))))))
13503 (setq bul (org-list-bullet-string "-"))
13504 (org-indent-line-to ind)
13505 (insert bul (pop lines))
13506 (let ((ind-body (+ (length bul) ind)))
13507 (while lines
13508 (insert "\n")
13509 (org-indent-line-to ind-body)
13510 (insert (pop lines))))
13511 (message "Note stored")
13512 (org-back-to-heading t)
13513 (org-cycle-hide-drawers 'children))
13514 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13515 ;; from within `org-add-log-note' because `buffer-undo-list'
13516 ;; is then modified outside of `org-with-remote-undo'.
13517 (when (eq this-command 'org-agenda-todo)
13518 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13519 ;; Don't add undo information when called from `org-agenda-todo'
13520 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13521 (set-window-configuration org-log-note-window-configuration)
13522 (with-current-buffer (marker-buffer org-log-note-return-to)
13523 (goto-char org-log-note-return-to))
13524 (move-marker org-log-note-return-to nil)
13525 (and org-log-post-message (message "%s" org-log-post-message))))
13527 (defun org-remove-empty-drawer-at (pos)
13528 "Remove an empty drawer at position POS.
13529 POS may also be a marker."
13530 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13531 (org-with-wide-buffer
13532 (goto-char pos)
13533 (let ((drawer (org-element-at-point)))
13534 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13535 (not (org-element-property :contents-begin drawer)))
13536 (delete-region (org-element-property :begin drawer)
13537 (progn (goto-char (org-element-property :end drawer))
13538 (skip-chars-backward " \r\t\n")
13539 (forward-line)
13540 (point))))))))
13542 (defvar org-ts-type nil)
13543 (defun org-sparse-tree (&optional arg type)
13544 "Create a sparse tree, prompt for the details.
13545 This command can create sparse trees. You first need to select the type
13546 of match used to create the tree:
13548 t Show all TODO entries.
13549 T Show entries with a specific TODO keyword.
13550 m Show entries selected by a tags/property match.
13551 p Enter a property name and its value (both with completion on existing
13552 names/values) and show entries with that property.
13553 r Show entries matching a regular expression (`/' can be used as well).
13554 b Show deadlines and scheduled items before a date.
13555 a Show deadlines and scheduled items after a date.
13556 d Show deadlines due within `org-deadline-warning-days'.
13557 D Show deadlines and scheduled items between a date range."
13558 (interactive "P")
13559 (let (ans kwd value ts-type)
13560 (setq type (or type org-sparse-tree-default-date-type))
13561 (setq org-ts-type type)
13562 (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"
13563 (cond ((eq type 'all) "all timestamps")
13564 ((eq type 'scheduled) "only scheduled")
13565 ((eq type 'deadline) "only deadline")
13566 ((eq type 'active) "only active timestamps")
13567 ((eq type 'inactive) "only inactive timestamps")
13568 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13569 ((eq type 'closed) "with a closed time-stamp")
13570 (t "scheduled/deadline")))
13571 (setq ans (read-char-exclusive))
13572 (cond
13573 ((equal ans ?c)
13574 (org-sparse-tree
13575 arg (cadr (member type '(scheduled-or-deadline
13576 all scheduled deadline active inactive closed)))))
13577 ((equal ans ?d)
13578 (call-interactively 'org-check-deadlines))
13579 ((equal ans ?b)
13580 (call-interactively 'org-check-before-date))
13581 ((equal ans ?a)
13582 (call-interactively 'org-check-after-date))
13583 ((equal ans ?D)
13584 (call-interactively 'org-check-dates-range))
13585 ((equal ans ?t)
13586 (call-interactively 'org-show-todo-tree))
13587 ((equal ans ?T)
13588 (org-show-todo-tree '(4)))
13589 ((member ans '(?T ?m))
13590 (call-interactively 'org-match-sparse-tree))
13591 ((member ans '(?p ?P))
13592 (setq kwd (org-icompleting-read "Property: "
13593 (mapcar 'list (org-buffer-property-keys))))
13594 (setq value (org-icompleting-read "Value: "
13595 (mapcar 'list (org-property-values kwd))))
13596 (unless (string-match "\\`{.*}\\'" value)
13597 (setq value (concat "\"" value "\"")))
13598 (org-match-sparse-tree arg (concat kwd "=" value)))
13599 ((member ans '(?r ?R ?/))
13600 (call-interactively 'org-occur))
13601 (t (user-error "No such sparse tree command \"%c\"" ans)))))
13603 (defvar org-occur-highlights nil
13604 "List of overlays used for occur matches.")
13605 (make-variable-buffer-local 'org-occur-highlights)
13606 (defvar org-occur-parameters nil
13607 "Parameters of the active org-occur calls.
13608 This is a list, each call to org-occur pushes as cons cell,
13609 containing the regular expression and the callback, onto the list.
13610 The list can contain several entries if `org-occur' has been called
13611 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13612 will only contain one set of parameters. When the highlights are
13613 removed (for example with `C-c C-c', or with the next edit (depending
13614 on `org-remove-highlights-with-change'), this variable is emptied
13615 as well.")
13616 (make-variable-buffer-local 'org-occur-parameters)
13618 (defun org-occur (regexp &optional keep-previous callback)
13619 "Make a compact tree which shows all matches of REGEXP.
13620 The tree will show the lines where the regexp matches, and all higher
13621 headlines above the match. It will also show the heading after the match,
13622 to make sure editing the matching entry is easy.
13623 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13624 call to `org-occur' will be kept, to allow stacking of calls to this
13625 command.
13626 If CALLBACK is non-nil, it is a function which is called to confirm
13627 that the match should indeed be shown."
13628 (interactive "sRegexp: \nP")
13629 (when (equal regexp "")
13630 (user-error "Regexp cannot be empty"))
13631 (unless keep-previous
13632 (org-remove-occur-highlights nil nil t))
13633 (push (cons regexp callback) org-occur-parameters)
13634 (let ((cnt 0))
13635 (save-excursion
13636 (goto-char (point-min))
13637 (if (or (not keep-previous) ; do not want to keep
13638 (not org-occur-highlights)) ; no previous matches
13639 ;; hide everything
13640 (org-overview))
13641 (while (re-search-forward regexp nil t)
13642 (when (or (not callback)
13643 (save-match-data (funcall callback)))
13644 (setq cnt (1+ cnt))
13645 (when org-highlight-sparse-tree-matches
13646 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13647 (org-show-context 'occur-tree))))
13648 (when org-remove-highlights-with-change
13649 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13650 nil 'local))
13651 (unless org-sparse-tree-open-archived-trees
13652 (org-hide-archived-subtrees (point-min) (point-max)))
13653 (run-hooks 'org-occur-hook)
13654 (if (org-called-interactively-p 'interactive)
13655 (message "%d match(es) for regexp %s" cnt regexp))
13656 cnt))
13658 (defun org-occur-next-match (&optional n reset)
13659 "Function for `next-error-function' to find sparse tree matches.
13660 N is the number of matches to move, when negative move backwards.
13661 RESET is entirely ignored - this function always goes back to the
13662 starting point when no match is found."
13663 (let* ((limit (if (< n 0) (point-min) (point-max)))
13664 (search-func (if (< n 0)
13665 'previous-single-char-property-change
13666 'next-single-char-property-change))
13667 (n (abs n))
13668 (pos (point))
13670 (catch 'exit
13671 (while (setq p1 (funcall search-func (point) 'org-type))
13672 (when (equal p1 limit)
13673 (goto-char pos)
13674 (error "No more matches"))
13675 (when (equal (get-char-property p1 'org-type) 'org-occur)
13676 (setq n (1- n))
13677 (when (= n 0)
13678 (goto-char p1)
13679 (throw 'exit (point))))
13680 (goto-char p1))
13681 (goto-char p1)
13682 (error "No more matches"))))
13684 (defun org-show-context (&optional key)
13685 "Make sure point and context are visible.
13686 How much context is shown depends upon the variables
13687 `org-show-hierarchy-above', `org-show-following-heading',
13688 `org-show-entry-below' and `org-show-siblings'."
13689 (let ((heading-p (org-at-heading-p t))
13690 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13691 (following-p (org-get-alist-option org-show-following-heading key))
13692 (entry-p (org-get-alist-option org-show-entry-below key))
13693 (siblings-p (org-get-alist-option org-show-siblings key)))
13694 ;; Show heading or entry text
13695 (if (and heading-p (not entry-p))
13696 (org-flag-heading nil) ; only show the heading
13697 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13698 (org-show-hidden-entry))) ; show entire entry
13699 (when following-p
13700 ;; Show next sibling, or heading below text
13701 (save-excursion
13702 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13703 (org-flag-heading nil))))
13704 (when siblings-p (org-show-siblings))
13705 (when hierarchy-p
13706 ;; show all higher headings, possibly with siblings
13707 (save-excursion
13708 (while (and (condition-case nil
13709 (progn (org-up-heading-all 1) t)
13710 (error nil))
13711 (not (bobp)))
13712 (org-flag-heading nil)
13713 (when siblings-p (org-show-siblings)))))
13714 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13716 (defvar org-reveal-start-hook nil
13717 "Hook run before revealing a location.")
13719 (defun org-reveal (&optional siblings)
13720 "Show current entry, hierarchy above it, and the following headline.
13721 This can be used to show a consistent set of context around locations
13722 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13723 not t for the search context.
13725 With optional argument SIBLINGS, on each level of the hierarchy all
13726 siblings are shown. This repairs the tree structure to what it would
13727 look like when opened with hierarchical calls to `org-cycle'.
13728 With double optional argument \\[universal-argument] \\[universal-argument], \
13729 go to the parent and show the
13730 entire tree."
13731 (interactive "P")
13732 (run-hooks 'org-reveal-start-hook)
13733 (let ((org-show-hierarchy-above t)
13734 (org-show-following-heading t)
13735 (org-show-siblings (if siblings t org-show-siblings)))
13736 (org-show-context nil))
13737 (when (equal siblings '(16))
13738 (save-excursion
13739 (when (org-up-heading-safe)
13740 (org-show-subtree)
13741 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13743 (defun org-highlight-new-match (beg end)
13744 "Highlight from BEG to END and mark the highlight is an occur headline."
13745 (let ((ov (make-overlay beg end)))
13746 (overlay-put ov 'face 'secondary-selection)
13747 (overlay-put ov 'org-type 'org-occur)
13748 (push ov org-occur-highlights)))
13750 (defun org-remove-occur-highlights (&optional beg end noremove)
13751 "Remove the occur highlights from the buffer.
13752 BEG and END are ignored. If NOREMOVE is nil, remove this function
13753 from the `before-change-functions' in the current buffer."
13754 (interactive)
13755 (unless org-inhibit-highlight-removal
13756 (mapc 'delete-overlay org-occur-highlights)
13757 (setq org-occur-highlights nil)
13758 (setq org-occur-parameters nil)
13759 (unless noremove
13760 (remove-hook 'before-change-functions
13761 'org-remove-occur-highlights 'local))))
13763 ;;;; Priorities
13765 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13766 "Regular expression matching the priority indicator.")
13768 (defvar org-remove-priority-next-time nil)
13770 (defun org-priority-up ()
13771 "Increase the priority of the current item."
13772 (interactive)
13773 (org-priority 'up))
13775 (defun org-priority-down ()
13776 "Decrease the priority of the current item."
13777 (interactive)
13778 (org-priority 'down))
13780 (defun org-priority (&optional action show)
13781 "Change the priority of an item.
13782 ACTION can be `set', `up', `down', or a character."
13783 (interactive "P")
13784 (if (equal action '(4))
13785 (org-show-priority)
13786 (unless org-enable-priority-commands
13787 (user-error "Priority commands are disabled"))
13788 (setq action (or action 'set))
13789 (let (current new news have remove)
13790 (save-excursion
13791 (org-back-to-heading t)
13792 (if (looking-at org-priority-regexp)
13793 (setq current (string-to-char (match-string 2))
13794 have t))
13795 (cond
13796 ((eq action 'remove)
13797 (setq remove t new ?\ ))
13798 ((or (eq action 'set)
13799 (if (featurep 'xemacs) (characterp action) (integerp action)))
13800 (if (not (eq action 'set))
13801 (setq new action)
13802 (message "Priority %c-%c, SPC to remove: "
13803 org-highest-priority org-lowest-priority)
13804 (save-match-data
13805 (setq new (read-char-exclusive))))
13806 (if (and (= (upcase org-highest-priority) org-highest-priority)
13807 (= (upcase org-lowest-priority) org-lowest-priority))
13808 (setq new (upcase new)))
13809 (cond ((equal new ?\ ) (setq remove t))
13810 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13811 (user-error "Priority must be between `%c' and `%c'"
13812 org-highest-priority org-lowest-priority))))
13813 ((eq action 'up)
13814 (setq new (if have
13815 (1- current) ; normal cycling
13816 ;; last priority was empty
13817 (if (eq last-command this-command)
13818 org-lowest-priority ; wrap around empty to lowest
13819 ;; default
13820 (if org-priority-start-cycle-with-default
13821 org-default-priority
13822 (1- org-default-priority))))))
13823 ((eq action 'down)
13824 (setq new (if have
13825 (1+ current) ; normal cycling
13826 ;; last priority was empty
13827 (if (eq last-command this-command)
13828 org-highest-priority ; wrap around empty to highest
13829 ;; default
13830 (if org-priority-start-cycle-with-default
13831 org-default-priority
13832 (1+ org-default-priority))))))
13833 (t (user-error "Invalid action")))
13834 (if (or (< (upcase new) org-highest-priority)
13835 (> (upcase new) org-lowest-priority))
13836 (if (and (memq action '(up down))
13837 (not have) (not (eq last-command this-command)))
13838 ;; `new' is from default priority
13839 (error
13840 "The default can not be set, see `org-default-priority' why")
13841 ;; normal cycling: `new' is beyond highest/lowest priority
13842 ;; and is wrapped around to the empty priority
13843 (setq remove t)))
13844 (setq news (format "%c" new))
13845 (if have
13846 (if remove
13847 (replace-match "" t t nil 1)
13848 (replace-match news t t nil 2))
13849 (if remove
13850 (user-error "No priority cookie found in line")
13851 (let ((case-fold-search nil))
13852 (looking-at org-todo-line-regexp))
13853 (if (match-end 2)
13854 (progn
13855 (goto-char (match-end 2))
13856 (insert " [#" news "]"))
13857 (goto-char (match-beginning 3))
13858 (insert "[#" news "] "))))
13859 (org-preserve-lc (org-set-tags nil 'align)))
13860 (if remove
13861 (message "Priority removed")
13862 (message "Priority of current item set to %s" news)))))
13864 (defun org-show-priority ()
13865 "Show the priority of the current item.
13866 This priority is composed of the main priority given with the [#A] cookies,
13867 and by additional input from the age of a schedules or deadline entry."
13868 (interactive)
13869 (let ((pri (if (eq major-mode 'org-agenda-mode)
13870 (org-get-at-bol 'priority)
13871 (save-excursion
13872 (save-match-data
13873 (beginning-of-line)
13874 (and (looking-at org-heading-regexp)
13875 (org-get-priority (match-string 0))))))))
13876 (message "Priority is %d" (if pri pri -1000))))
13878 (defun org-get-priority (s)
13879 "Find priority cookie and return priority."
13880 (save-match-data
13881 (if (functionp org-get-priority-function)
13882 (funcall org-get-priority-function)
13883 (if (not (string-match org-priority-regexp s))
13884 (* 1000 (- org-lowest-priority org-default-priority))
13885 (* 1000 (- org-lowest-priority
13886 (string-to-char (match-string 2 s))))))))
13888 ;;;; Tags
13890 (defvar org-agenda-archives-mode)
13891 (defvar org-map-continue-from nil
13892 "Position from where mapping should continue.
13893 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13895 (defvar org-scanner-tags nil
13896 "The current tag list while the tags scanner is running.")
13897 (defvar org-trust-scanner-tags nil
13898 "Should `org-get-tags-at' use the tags for the scanner.
13899 This is for internal dynamical scoping only.
13900 When this is non-nil, the function `org-get-tags-at' will return the value
13901 of `org-scanner-tags' instead of building the list by itself. This
13902 can lead to large speed-ups when the tags scanner is used in a file with
13903 many entries, and when the list of tags is retrieved, for example to
13904 obtain a list of properties. Building the tags list for each entry in such
13905 a file becomes an N^2 operation - but with this variable set, it scales
13906 as N.")
13908 (defun org-scan-tags (action matcher todo-only &optional start-level)
13909 "Sca headline tags with inheritance and produce output ACTION.
13911 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13912 or `agenda' to produce an entry list for an agenda view. It can also be
13913 a Lisp form or a function that should be called at each matched headline, in
13914 this case the return value is a list of all return values from these calls.
13916 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13917 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13918 only lines with a not-done TODO keyword are included in the output.
13919 This should be the same variable that was scoped into
13920 and set by `org-make-tags-matcher' when it constructed MATCHER.
13922 START-LEVEL can be a string with asterisks, reducing the scope to
13923 headlines matching this string."
13924 (require 'org-agenda)
13925 (let* ((re (concat "^"
13926 (if start-level
13927 ;; Get the correct level to match
13928 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13929 org-outline-regexp)
13930 " *\\(\\<\\("
13931 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13932 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13933 (props (list 'face 'default
13934 'done-face 'org-agenda-done
13935 'undone-face 'default
13936 'mouse-face 'highlight
13937 'org-not-done-regexp org-not-done-regexp
13938 'org-todo-regexp org-todo-regexp
13939 'org-complex-heading-regexp org-complex-heading-regexp
13940 'help-echo
13941 (format "mouse-2 or RET jump to org file %s"
13942 (abbreviate-file-name
13943 (or (buffer-file-name (buffer-base-buffer))
13944 (buffer-name (buffer-base-buffer)))))))
13945 (org-map-continue-from nil)
13946 lspos tags tags-list
13947 (tags-alist (list (cons 0 org-file-tags)))
13948 (llast 0) rtn rtn1 level category i txt
13949 todo marker entry priority)
13950 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13951 (setq action (list 'lambda nil action)))
13952 (save-excursion
13953 (goto-char (point-min))
13954 (when (eq action 'sparse-tree)
13955 (org-overview)
13956 (org-remove-occur-highlights))
13957 (while (let (case-fold-search)
13958 (re-search-forward re nil t))
13959 (setq org-map-continue-from nil)
13960 (catch :skip
13961 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13962 tags (if (match-end 4) (org-match-string-no-properties 4)))
13963 (goto-char (setq lspos (match-beginning 0)))
13964 (setq level (org-reduced-level (org-outline-level))
13965 category (org-get-category))
13966 (setq i llast llast level)
13967 ;; remove tag lists from same and sublevels
13968 (while (>= i level)
13969 (when (setq entry (assoc i tags-alist))
13970 (setq tags-alist (delete entry tags-alist)))
13971 (setq i (1- i)))
13972 ;; add the next tags
13973 (when tags
13974 (setq tags (org-split-string tags ":")
13975 tags-alist
13976 (cons (cons level tags) tags-alist)))
13977 ;; compile tags for current headline
13978 (setq tags-list
13979 (if org-use-tag-inheritance
13980 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13981 tags)
13982 org-scanner-tags tags-list)
13983 (when org-use-tag-inheritance
13984 (setcdr (car tags-alist)
13985 (mapcar (lambda (x)
13986 (setq x (copy-sequence x))
13987 (org-add-prop-inherited x))
13988 (cdar tags-alist))))
13989 (when (and tags org-use-tag-inheritance
13990 (or (not (eq t org-use-tag-inheritance))
13991 org-tags-exclude-from-inheritance))
13992 ;; selective inheritance, remove uninherited ones
13993 (setcdr (car tags-alist)
13994 (org-remove-uninherited-tags (cdar tags-alist))))
13995 (when (and
13997 ;; eval matcher only when the todo condition is OK
13998 (and (or (not todo-only) (member todo org-not-done-keywords))
13999 (let ((case-fold-search t) (org-trust-scanner-tags t))
14000 (eval matcher)))
14002 ;; Call the skipper, but return t if it does not skip,
14003 ;; so that the `and' form continues evaluating
14004 (progn
14005 (unless (eq action 'sparse-tree) (org-agenda-skip))
14008 ;; Check if timestamps are deselecting this entry
14009 (or (not todo-only)
14010 (and (member todo org-not-done-keywords)
14011 (or (not org-agenda-tags-todo-honor-ignore-options)
14012 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14014 ;; select this headline
14015 (cond
14016 ((eq action 'sparse-tree)
14017 (and org-highlight-sparse-tree-matches
14018 (org-get-heading) (match-end 0)
14019 (org-highlight-new-match
14020 (match-beginning 1) (match-end 1)))
14021 (org-show-context 'tags-tree))
14022 ((eq action 'agenda)
14023 (setq txt (org-agenda-format-item
14025 (concat
14026 (if (eq org-tags-match-list-sublevels 'indented)
14027 (make-string (1- level) ?.) "")
14028 (org-get-heading))
14029 level category
14030 tags-list)
14031 priority (org-get-priority txt))
14032 (goto-char lspos)
14033 (setq marker (org-agenda-new-marker))
14034 (org-add-props txt props
14035 'org-marker marker 'org-hd-marker marker 'org-category category
14036 'todo-state todo
14037 'priority priority 'type "tagsmatch")
14038 (push txt rtn))
14039 ((functionp action)
14040 (setq org-map-continue-from nil)
14041 (save-excursion
14042 (setq rtn1 (funcall action))
14043 (push rtn1 rtn)))
14044 (t (user-error "Invalid action")))
14046 ;; if we are to skip sublevels, jump to end of subtree
14047 (unless org-tags-match-list-sublevels
14048 (org-end-of-subtree t)
14049 (backward-char 1))))
14050 ;; Get the correct position from where to continue
14051 (if org-map-continue-from
14052 (goto-char org-map-continue-from)
14053 (and (= (point) lspos) (end-of-line 1)))))
14054 (when (and (eq action 'sparse-tree)
14055 (not org-sparse-tree-open-archived-trees))
14056 (org-hide-archived-subtrees (point-min) (point-max)))
14057 (nreverse rtn)))
14059 (defun org-remove-uninherited-tags (tags)
14060 "Remove all tags that are not inherited from the list TAGS."
14061 (cond
14062 ((eq org-use-tag-inheritance t)
14063 (if org-tags-exclude-from-inheritance
14064 (org-delete-all org-tags-exclude-from-inheritance tags)
14065 tags))
14066 ((not org-use-tag-inheritance) nil)
14067 ((stringp org-use-tag-inheritance)
14068 (delq nil (mapcar
14069 (lambda (x)
14070 (if (and (string-match org-use-tag-inheritance x)
14071 (not (member x org-tags-exclude-from-inheritance)))
14072 x nil))
14073 tags)))
14074 ((listp org-use-tag-inheritance)
14075 (delq nil (mapcar
14076 (lambda (x)
14077 (if (member x org-use-tag-inheritance) x nil))
14078 tags)))))
14080 (defun org-match-sparse-tree (&optional todo-only match)
14081 "Create a sparse tree according to tags string MATCH.
14082 MATCH can contain positive and negative selection of tags, like
14083 \"+WORK+URGENT-WITHBOSS\".
14084 If optional argument TODO-ONLY is non-nil, only select lines that are
14085 also TODO lines."
14086 (interactive "P")
14087 (org-agenda-prepare-buffers (list (current-buffer)))
14088 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
14090 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14092 (defvar org-cached-props nil)
14093 (defun org-cached-entry-get (pom property)
14094 (if (or (eq t org-use-property-inheritance)
14095 (and (stringp org-use-property-inheritance)
14096 (string-match org-use-property-inheritance property))
14097 (and (listp org-use-property-inheritance)
14098 (member property org-use-property-inheritance)))
14099 ;; Caching is not possible, check it directly
14100 (org-entry-get pom property 'inherit)
14101 ;; Get all properties, so that we can do complicated checks easily
14102 (cdr (assoc property (or org-cached-props
14103 (setq org-cached-props
14104 (org-entry-properties pom)))))))
14106 (defun org-global-tags-completion-table (&optional files)
14107 "Return the list of all tags in all agenda buffer/files.
14108 Optional FILES argument is a list of files which can be used
14109 instead of the agenda files."
14110 (save-excursion
14111 (org-uniquify
14112 (delq nil
14113 (apply 'append
14114 (mapcar
14115 (lambda (file)
14116 (set-buffer (find-file-noselect file))
14117 (append (org-get-buffer-tags)
14118 (mapcar (lambda (x) (if (stringp (car-safe x))
14119 (list (car-safe x)) nil))
14120 org-tag-alist)))
14121 (if (and files (car files))
14122 files
14123 (org-agenda-files))))))))
14125 (defun org-make-tags-matcher (match)
14126 "Create the TAGS/TODO matcher form for the selection string MATCH.
14128 The variable `todo-only' is scoped dynamically into this function.
14129 It will be set to t if the matcher restricts matching to TODO entries,
14130 otherwise will not be touched.
14132 Returns a cons of the selection string MATCH and the constructed
14133 lisp form implementing the matcher. The matcher is to be evaluated
14134 at an Org entry, with point on the headline, and returns t if the
14135 entry matches the selection string MATCH. The returned lisp form
14136 references two variables with information about the entry, which
14137 must be bound around the form's evaluation: todo, the TODO keyword
14138 at the entry (or nil of none); and tags-list, the list of all tags
14139 at the entry including inherited ones. Additionally, the category
14140 of the entry (if any) must be specified as the text property
14141 'org-category on the headline.
14143 See also `org-scan-tags'.
14145 (declare (special todo-only))
14146 (unless (boundp 'todo-only)
14147 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14148 (unless match
14149 ;; Get a new match request, with completion against the global
14150 ;; tags table and the local tags in current buffer
14151 (let ((org-last-tags-completion-table
14152 (org-uniquify
14153 (delq nil (append (org-get-buffer-tags)
14154 (org-global-tags-completion-table))))))
14155 (setq match (org-completing-read-no-i
14156 "Match: " 'org-tags-completion-function nil nil nil
14157 'org-tags-history))))
14159 ;; Parse the string and create a lisp form
14160 (let ((match0 match)
14161 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14162 minus tag mm
14163 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14164 orterms term orlist re-p str-p level-p level-op time-p
14165 prop-p pn pv po gv rest (start 0) (ss 0))
14166 ;; Expand group tags
14167 (setq match (org-tags-expand match))
14169 ;; Check if there is a TODO part of this match, which would be the
14170 ;; part after a "/". TO make sure that this slash is not part of
14171 ;; a property value to be matched against, we also check that there
14172 ;; is no " after that slash.
14173 ;; First, find the last slash
14174 (while (string-match "/+" match ss)
14175 (setq start (match-beginning 0) ss (match-end 0)))
14176 (if (and (string-match "/+" match start)
14177 (not (save-match-data (string-match "\"" match start))))
14178 ;; match contains also a todo-matching request
14179 (progn
14180 (setq tagsmatch (substring match 0 (match-beginning 0))
14181 todomatch (substring match (match-end 0)))
14182 (if (string-match "^!" todomatch)
14183 (setq todo-only t todomatch (substring todomatch 1)))
14184 (if (string-match "^\\s-*$" todomatch)
14185 (setq todomatch nil)))
14186 ;; only matching tags
14187 (setq tagsmatch match todomatch nil))
14189 ;; Make the tags matcher
14190 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14191 (setq tagsmatcher t)
14192 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14193 (while (setq term (pop orterms))
14194 (while (and (equal (substring term -1) "\\") orterms)
14195 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14196 (while (string-match re term)
14197 (setq rest (substring term (match-end 0))
14198 minus (and (match-end 1)
14199 (equal (match-string 1 term) "-"))
14200 tag (save-match-data (replace-regexp-in-string
14201 "\\\\-" "-"
14202 (match-string 2 term)))
14203 re-p (equal (string-to-char tag) ?{)
14204 level-p (match-end 4)
14205 prop-p (match-end 5)
14206 mm (cond
14207 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14208 (level-p
14209 (setq level-op (org-op-to-function (match-string 3 term)))
14210 `(,level-op level ,(string-to-number
14211 (match-string 4 term))))
14212 (prop-p
14213 (setq pn (match-string 5 term)
14214 po (match-string 6 term)
14215 pv (match-string 7 term)
14216 re-p (equal (string-to-char pv) ?{)
14217 str-p (equal (string-to-char pv) ?\")
14218 time-p (save-match-data
14219 (string-match "^\"[[<].*[]>]\"$" pv))
14220 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14221 (if time-p (setq pv (org-matcher-time pv)))
14222 (setq po (org-op-to-function po (if time-p 'time str-p)))
14223 (cond
14224 ((equal pn "CATEGORY")
14225 (setq gv '(get-text-property (point) 'org-category)))
14226 ((equal pn "TODO")
14227 (setq gv 'todo))
14229 (setq gv `(org-cached-entry-get nil ,pn))))
14230 (if re-p
14231 (if (eq po 'org<>)
14232 `(not (string-match ,pv (or ,gv "")))
14233 `(string-match ,pv (or ,gv "")))
14234 (if str-p
14235 `(,po (or ,gv "") ,pv)
14236 `(,po (string-to-number (or ,gv ""))
14237 ,(string-to-number pv) ))))
14238 (t `(member ,tag tags-list)))
14239 mm (if minus (list 'not mm) mm)
14240 term rest)
14241 (push mm tagsmatcher))
14242 (push (if (> (length tagsmatcher) 1)
14243 (cons 'and tagsmatcher)
14244 (car tagsmatcher))
14245 orlist)
14246 (setq tagsmatcher nil))
14247 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14248 (setq tagsmatcher
14249 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14250 ;; Make the todo matcher
14251 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14252 (setq todomatcher t)
14253 (setq orterms (org-split-string todomatch "|") orlist nil)
14254 (while (setq term (pop orterms))
14255 (while (string-match re term)
14256 (setq minus (and (match-end 1)
14257 (equal (match-string 1 term) "-"))
14258 kwd (match-string 2 term)
14259 re-p (equal (string-to-char kwd) ?{)
14260 term (substring term (match-end 0))
14261 mm (if re-p
14262 `(string-match ,(substring kwd 1 -1) todo)
14263 (list 'equal 'todo kwd))
14264 mm (if minus (list 'not mm) mm))
14265 (push mm todomatcher))
14266 (push (if (> (length todomatcher) 1)
14267 (cons 'and todomatcher)
14268 (car todomatcher))
14269 orlist)
14270 (setq todomatcher nil))
14271 (setq todomatcher (if (> (length orlist) 1)
14272 (cons 'or orlist) (car orlist))))
14274 ;; Return the string and lisp forms of the matcher
14275 (setq matcher (if todomatcher
14276 (list 'and tagsmatcher todomatcher)
14277 tagsmatcher))
14278 (when todo-only
14279 (setq matcher (list 'and '(member todo org-not-done-keywords)
14280 matcher)))
14281 (cons match0 matcher)))
14283 (defun org-tags-expand (match &optional single-as-list downcased)
14284 "Expand group tags in MATCH.
14286 This replaces every group tag in MATCH with a regexp tag search.
14287 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14288 will be replaced like this:
14290 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14291 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14292 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14294 Replacing by a regexp preserves the structure of the match.
14295 E.g., this expansion
14297 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14299 will match anything tagged with \"Lab\" and \"Home\", or tagged
14300 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14302 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14303 assumed to be a single group tag, and the function will return
14304 the list of tags in this group.
14306 When DOWNCASE is non-nil, expand downcased TAGS."
14307 (if org-group-tags
14308 (let* ((case-fold-search t)
14309 (stable org-mode-syntax-table)
14310 (tal (or org-tag-groups-alist-for-agenda
14311 org-tag-groups-alist))
14312 (tal (if downcased
14313 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14314 (tml (mapcar 'car tal))
14315 (rtnmatch match) rpl)
14316 ;; @ and _ are allowed as word-components in tags
14317 (modify-syntax-entry ?@ "w" stable)
14318 (modify-syntax-entry ?_ "w" stable)
14319 (while (and tml
14320 (with-syntax-table stable
14321 (string-match
14322 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14323 (regexp-opt tml) "\\>\\)") rtnmatch)))
14324 (let* ((dir (match-string 1 rtnmatch))
14325 (tag (match-string 2 rtnmatch))
14326 (tag (if downcased (downcase tag) tag)))
14327 (setq tml (delete tag tml))
14328 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14329 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14330 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14331 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14332 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14333 (if single-as-list
14334 (or (reverse rpl) (list rtnmatch))
14335 rtnmatch))
14336 (if single-as-list (list (if downcased (downcase match) match))
14337 match)))
14339 (defun org-op-to-function (op &optional stringp)
14340 "Turn an operator into the appropriate function."
14341 (setq op
14342 (cond
14343 ((equal op "<" ) '(< string< org-time<))
14344 ((equal op ">" ) '(> org-string> org-time>))
14345 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14346 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14347 ((member op '("=" "==")) '(= string= org-time=))
14348 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14349 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14351 (defun org<> (a b) (not (= a b)))
14352 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14353 (defun org-string>= (a b) (not (string< a b)))
14354 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14355 (defun org-string<> (a b) (not (string= a b)))
14356 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14357 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14358 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14359 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14360 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14361 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14362 (defun org-2ft (s)
14363 "Convert S to a floating point time.
14364 If S is already a number, just return it. If it is a string, parse
14365 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14366 (cond
14367 ((numberp s) s)
14368 ((stringp s)
14369 (condition-case nil
14370 (float-time (apply 'encode-time (org-parse-time-string s)))
14371 (error 0.)))
14372 (t 0.)))
14374 (defun org-time-today ()
14375 "Time in seconds today at 0:00.
14376 Returns the float number of seconds since the beginning of the
14377 epoch to the beginning of today (00:00)."
14378 (float-time (apply 'encode-time
14379 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14381 (defun org-matcher-time (s)
14382 "Interpret a time comparison value."
14383 (save-match-data
14384 (cond
14385 ((string= s "<now>") (float-time))
14386 ((string= s "<today>") (org-time-today))
14387 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14388 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14389 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14390 (+ (org-time-today)
14391 (* (string-to-number (match-string 1 s))
14392 (cdr (assoc (match-string 2 s)
14393 '(("d" . 86400.0) ("w" . 604800.0)
14394 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14395 (t (org-2ft s)))))
14397 (defun org-match-any-p (re list)
14398 "Does re match any element of list?"
14399 (setq list (mapcar (lambda (x) (string-match re x)) list))
14400 (delq nil list))
14402 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14403 (defvar org-tags-overlay (make-overlay 1 1))
14404 (org-detach-overlay org-tags-overlay)
14406 (defun org-get-local-tags-at (&optional pos)
14407 "Get a list of tags defined in the current headline."
14408 (org-get-tags-at pos 'local))
14410 (defun org-get-local-tags ()
14411 "Get a list of tags defined in the current headline."
14412 (org-get-tags-at nil 'local))
14414 (defun org-get-tags-at (&optional pos local)
14415 "Get a list of all headline tags applicable at POS.
14416 POS defaults to point. If tags are inherited, the list contains
14417 the targets in the same sequence as the headlines appear, i.e.
14418 the tags of the current headline come last.
14419 When LOCAL is non-nil, only return tags from the current headline,
14420 ignore inherited ones."
14421 (interactive)
14422 (if (and org-trust-scanner-tags
14423 (or (not pos) (equal pos (point)))
14424 (not local))
14425 org-scanner-tags
14426 (let (tags ltags lastpos parent)
14427 (save-excursion
14428 (save-restriction
14429 (widen)
14430 (goto-char (or pos (point)))
14431 (save-match-data
14432 (catch 'done
14433 (condition-case nil
14434 (progn
14435 (org-back-to-heading t)
14436 (while (not (equal lastpos (point)))
14437 (setq lastpos (point))
14438 (when (looking-at
14439 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14440 (setq ltags (org-split-string
14441 (org-match-string-no-properties 1) ":"))
14442 (when parent
14443 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14444 (setq tags (append
14445 (if parent
14446 (org-remove-uninherited-tags ltags)
14447 ltags)
14448 tags)))
14449 (or org-use-tag-inheritance (throw 'done t))
14450 (if local (throw 'done t))
14451 (or (org-up-heading-safe) (error nil))
14452 (setq parent t)))
14453 (error nil)))))
14454 (if local
14455 tags
14456 (reverse (delete-dups
14457 (reverse (append
14458 (org-remove-uninherited-tags
14459 org-file-tags) tags)))))))))
14461 (defun org-add-prop-inherited (s)
14462 (add-text-properties 0 (length s) '(inherited t) s)
14465 (defun org-toggle-tag (tag &optional onoff)
14466 "Toggle the tag TAG for the current line.
14467 If ONOFF is `on' or `off', don't toggle but set to this state."
14468 (let (res current)
14469 (save-excursion
14470 (org-back-to-heading t)
14471 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14472 (point-at-eol) t)
14473 (progn
14474 (setq current (match-string 1))
14475 (replace-match ""))
14476 (setq current ""))
14477 (setq current (nreverse (org-split-string current ":")))
14478 (cond
14479 ((eq onoff 'on)
14480 (setq res t)
14481 (or (member tag current) (push tag current)))
14482 ((eq onoff 'off)
14483 (or (not (member tag current)) (setq current (delete tag current))))
14484 (t (if (member tag current)
14485 (setq current (delete tag current))
14486 (setq res t)
14487 (push tag current))))
14488 (end-of-line 1)
14489 (if current
14490 (progn
14491 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14492 (org-set-tags nil t))
14493 (delete-horizontal-space))
14494 (run-hooks 'org-after-tags-change-hook))
14495 res))
14497 (defun org-align-tags-here (to-col)
14498 ;; Assumes that this is a headline
14499 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14500 (beginning-of-line 1)
14501 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14502 (< pos (match-beginning 2)))
14503 (progn
14504 (setq tags-l (- (match-end 2) (match-beginning 2)))
14505 (goto-char (match-beginning 1))
14506 (insert " ")
14507 (delete-region (point) (1+ (match-beginning 2)))
14508 (setq ncol (max (current-column)
14509 (1+ col)
14510 (if (> to-col 0)
14511 to-col
14512 (- (abs to-col) tags-l))))
14513 (setq p (point))
14514 (insert (make-string (- ncol (current-column)) ?\ ))
14515 (setq ncol (current-column))
14516 (when indent-tabs-mode (tabify p (point-at-eol)))
14517 (org-move-to-column (min ncol col) t nil t))
14518 (goto-char pos))))
14520 (defun org-set-tags-command (&optional arg just-align)
14521 "Call the set-tags command for the current entry."
14522 (interactive "P")
14523 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14524 (org-set-tags arg just-align)
14525 (save-excursion
14526 (unless (and (org-region-active-p)
14527 org-loop-over-headlines-in-active-region)
14528 (org-back-to-heading t))
14529 (org-set-tags arg just-align))))
14531 (defun org-set-tags-to (data)
14532 "Set the tags of the current entry to DATA, replacing the current tags.
14533 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14534 If DATA is nil or the empty string, any tags will be removed."
14535 (interactive "sTags: ")
14536 (setq data
14537 (cond
14538 ((eq data nil) "")
14539 ((equal data "") "")
14540 ((stringp data)
14541 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14542 ":"))
14543 ((listp data)
14544 (concat ":" (mapconcat 'identity data ":") ":"))))
14545 (when data
14546 (save-excursion
14547 (org-back-to-heading t)
14548 (when (looking-at org-complex-heading-regexp)
14549 (if (match-end 5)
14550 (progn
14551 (goto-char (match-beginning 5))
14552 (insert data)
14553 (delete-region (point) (point-at-eol))
14554 (org-set-tags nil 'align))
14555 (goto-char (point-at-eol))
14556 (insert " " data)
14557 (org-set-tags nil 'align)))
14558 (beginning-of-line 1)
14559 (if (looking-at ".*?\\([ \t]+\\)$")
14560 (delete-region (match-beginning 1) (match-end 1))))))
14562 (defun org-align-all-tags ()
14563 "Align the tags i all headings."
14564 (interactive)
14565 (save-excursion
14566 (or (ignore-errors (org-back-to-heading t))
14567 (outline-next-heading))
14568 (if (org-at-heading-p)
14569 (org-set-tags t)
14570 (message "No headings"))))
14572 (defvar org-indent-indentation-per-level)
14573 (defun org-set-tags (&optional arg just-align)
14574 "Set the tags for the current headline.
14575 With prefix ARG, realign all tags in headings in the current buffer."
14576 (interactive "P")
14577 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14578 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14579 'region-start-level 'region))
14580 org-loop-over-headlines-in-active-region)
14581 (org-map-entries
14582 ;; We don't use ARG and JUST-ALIGN here these args are not
14583 ;; useful when looping over headlines
14584 `(org-set-tags)
14585 org-loop-over-headlines-in-active-region
14586 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14587 (let* ((re org-outline-regexp-bol)
14588 (current (unless arg (org-get-tags-string)))
14589 (col (current-column))
14590 (org-setting-tags t)
14591 table current-tags inherited-tags ; computed below when needed
14592 tags p0 c0 c1 rpl di tc level)
14593 (if arg
14594 (save-excursion
14595 (goto-char (point-min))
14596 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14597 (while (re-search-forward re nil t)
14598 (org-set-tags nil t)
14599 (end-of-line 1)))
14600 (message "All tags realigned to column %d" org-tags-column))
14601 (if just-align
14602 (setq tags current)
14603 ;; Get a new set of tags from the user
14604 (save-excursion
14605 (setq table (append org-tag-persistent-alist
14606 (or org-tag-alist (org-get-buffer-tags))
14607 (and
14608 org-complete-tags-always-offer-all-agenda-tags
14609 (org-global-tags-completion-table
14610 (org-agenda-files))))
14611 org-last-tags-completion-table table
14612 current-tags (org-split-string current ":")
14613 inherited-tags (nreverse
14614 (nthcdr (length current-tags)
14615 (nreverse (org-get-tags-at))))
14616 tags
14617 (if (or (eq t org-use-fast-tag-selection)
14618 (and org-use-fast-tag-selection
14619 (delq nil (mapcar 'cdr table))))
14620 (org-fast-tag-selection
14621 current-tags inherited-tags table
14622 (if org-fast-tag-selection-include-todo
14623 org-todo-key-alist))
14624 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14625 (org-trim
14626 (org-icompleting-read "Tags: "
14627 'org-tags-completion-function
14628 nil nil current 'org-tags-history))))))
14629 (while (string-match "[-+&]+" tags)
14630 ;; No boolean logic, just a list
14631 (setq tags (replace-match ":" t t tags))))
14633 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14635 (if org-tags-sort-function
14636 (setq tags (mapconcat 'identity
14637 (sort (org-split-string
14638 tags (org-re "[^[:alnum:]_@#%]+"))
14639 org-tags-sort-function) ":")))
14641 (if (string-match "\\`[\t ]*\\'" tags)
14642 (setq tags "")
14643 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14644 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14646 ;; Insert new tags at the correct column
14647 (beginning-of-line 1)
14648 (setq level (or (and (looking-at org-outline-regexp)
14649 (- (match-end 0) (point) 1))
14651 (cond
14652 ((and (equal current "") (equal tags "")))
14653 ((re-search-forward
14654 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14655 (point-at-eol) t)
14656 (if (equal tags "")
14657 (setq rpl "")
14658 (goto-char (match-beginning 0))
14659 (setq c0 (current-column)
14660 ;; compute offset for the case of org-indent-mode active
14661 di (if org-indent-mode
14662 (* (1- org-indent-indentation-per-level) (1- level))
14664 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14665 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14666 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (string-width tags))))
14667 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14668 (replace-match rpl t t)
14669 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14670 tags)
14671 (t (error "Tags alignment failed")))
14672 (org-move-to-column col)
14673 (unless just-align
14674 (run-hooks 'org-after-tags-change-hook))))))
14676 (defun org-change-tag-in-region (beg end tag off)
14677 "Add or remove TAG for each entry in the region.
14678 This works in the agenda, and also in an org-mode buffer."
14679 (interactive
14680 (list (region-beginning) (region-end)
14681 (let ((org-last-tags-completion-table
14682 (if (derived-mode-p 'org-mode)
14683 (org-uniquify
14684 (delq nil (append (org-get-buffer-tags)
14685 (org-global-tags-completion-table))))
14686 (org-global-tags-completion-table))))
14687 (org-icompleting-read
14688 "Tag: " 'org-tags-completion-function nil nil nil
14689 'org-tags-history))
14690 (progn
14691 (message "[s]et or [r]emove? ")
14692 (equal (read-char-exclusive) ?r))))
14693 (if (fboundp 'deactivate-mark) (deactivate-mark))
14694 (let ((agendap (equal major-mode 'org-agenda-mode))
14695 l1 l2 m buf pos newhead (cnt 0))
14696 (goto-char end)
14697 (setq l2 (1- (org-current-line)))
14698 (goto-char beg)
14699 (setq l1 (org-current-line))
14700 (loop for l from l1 to l2 do
14701 (org-goto-line l)
14702 (setq m (get-text-property (point) 'org-hd-marker))
14703 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14704 (and agendap m))
14705 (setq buf (if agendap (marker-buffer m) (current-buffer))
14706 pos (if agendap m (point)))
14707 (with-current-buffer buf
14708 (save-excursion
14709 (save-restriction
14710 (goto-char pos)
14711 (setq cnt (1+ cnt))
14712 (org-toggle-tag tag (if off 'off 'on))
14713 (setq newhead (org-get-heading)))))
14714 (and agendap (org-agenda-change-all-lines newhead m))))
14715 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14717 (defun org-tags-completion-function (string predicate &optional flag)
14718 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14719 (confirm (lambda (x) (stringp (car x)))))
14720 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14721 (setq s1 (match-string 1 string)
14722 s2 (match-string 2 string))
14723 (setq s1 "" s2 string))
14724 (cond
14725 ((eq flag nil)
14726 ;; try completion
14727 (setq rtn (try-completion s2 ctable confirm))
14728 (if (stringp rtn)
14729 (setq rtn
14730 (concat s1 s2 (substring rtn (length s2))
14731 (if (and org-add-colon-after-tag-completion
14732 (assoc rtn ctable))
14733 ":" ""))))
14734 rtn)
14735 ((eq flag t)
14736 ;; all-completions
14737 (all-completions s2 ctable confirm))
14738 ((eq flag 'lambda)
14739 ;; exact match?
14740 (assoc s2 ctable)))))
14742 (defun org-fast-tag-insert (kwd tags face &optional end)
14743 "Insert KDW, and the TAGS, the latter with face FACE.
14744 Also insert END."
14745 (insert (format "%-12s" (concat kwd ":"))
14746 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14747 (or end "")))
14749 (defun org-fast-tag-show-exit (flag)
14750 (save-excursion
14751 (org-goto-line 3)
14752 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14753 (replace-match ""))
14754 (when flag
14755 (end-of-line 1)
14756 (org-move-to-column (- (window-width) 19) t)
14757 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14759 (defun org-set-current-tags-overlay (current prefix)
14760 "Add an overlay to CURRENT tag with PREFIX."
14761 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14762 (if (featurep 'xemacs)
14763 (org-overlay-display org-tags-overlay (concat prefix s)
14764 'secondary-selection)
14765 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14766 (org-overlay-display org-tags-overlay (concat prefix s)))))
14768 (defvar org-last-tag-selection-key nil)
14769 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14770 "Fast tag selection with single keys.
14771 CURRENT is the current list of tags in the headline, INHERITED is the
14772 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14773 possibly with grouping information. TODO-TABLE is a similar table with
14774 TODO keywords, should these have keys assigned to them.
14775 If the keys are nil, a-z are automatically assigned.
14776 Returns the new tags string, or nil to not change the current settings."
14777 (let* ((fulltable (append table todo-table))
14778 (maxlen (apply 'max (mapcar
14779 (lambda (x)
14780 (if (stringp (car x)) (string-width (car x)) 0))
14781 fulltable)))
14782 (buf (current-buffer))
14783 (expert (eq org-fast-tag-selection-single-key 'expert))
14784 (buffer-tags nil)
14785 (fwidth (+ maxlen 3 1 3))
14786 (ncol (/ (- (window-width) 4) fwidth))
14787 (i-face 'org-done)
14788 (c-face 'org-todo)
14789 tg cnt e c char c1 c2 ntable tbl rtn
14790 ov-start ov-end ov-prefix
14791 (exit-after-next org-fast-tag-selection-single-key)
14792 (done-keywords org-done-keywords)
14793 groups ingroup)
14794 (save-excursion
14795 (beginning-of-line 1)
14796 (if (looking-at
14797 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14798 (setq ov-start (match-beginning 1)
14799 ov-end (match-end 1)
14800 ov-prefix "")
14801 (setq ov-start (1- (point-at-eol))
14802 ov-end (1+ ov-start))
14803 (skip-chars-forward "^\n\r")
14804 (setq ov-prefix
14805 (concat
14806 (buffer-substring (1- (point)) (point))
14807 (if (> (current-column) org-tags-column)
14809 (make-string (- org-tags-column (current-column)) ?\ ))))))
14810 (move-overlay org-tags-overlay ov-start ov-end)
14811 (save-window-excursion
14812 (if expert
14813 (set-buffer (get-buffer-create " *Org tags*"))
14814 (delete-other-windows)
14815 (split-window-vertically)
14816 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14817 (erase-buffer)
14818 (org-set-local 'org-done-keywords done-keywords)
14819 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14820 (org-fast-tag-insert "Current" current c-face "\n\n")
14821 (org-fast-tag-show-exit exit-after-next)
14822 (org-set-current-tags-overlay current ov-prefix)
14823 (setq tbl fulltable char ?a cnt 0)
14824 (while (setq e (pop tbl))
14825 (cond
14826 ((equal (car e) :startgroup)
14827 (push '() groups) (setq ingroup t)
14828 (when (not (= cnt 0))
14829 (setq cnt 0)
14830 (insert "\n"))
14831 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14832 ((equal (car e) :endgroup)
14833 (setq ingroup nil cnt 0)
14834 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14835 ((equal e '(:newline))
14836 (when (not (= cnt 0))
14837 (setq cnt 0)
14838 (insert "\n")
14839 (setq e (car tbl))
14840 (while (equal (car tbl) '(:newline))
14841 (insert "\n")
14842 (setq tbl (cdr tbl)))))
14843 ((equal e '(:grouptags)) nil)
14845 (setq tg (copy-sequence (car e)) c2 nil)
14846 (if (cdr e)
14847 (setq c (cdr e))
14848 ;; automatically assign a character.
14849 (setq c1 (string-to-char
14850 (downcase (substring
14851 tg (if (= (string-to-char tg) ?@) 1 0)))))
14852 (if (or (rassoc c1 ntable) (rassoc c1 table))
14853 (while (or (rassoc char ntable) (rassoc char table))
14854 (setq char (1+ char)))
14855 (setq c2 c1))
14856 (setq c (or c2 char)))
14857 (if ingroup (push tg (car groups)))
14858 (setq tg (org-add-props tg nil 'face
14859 (cond
14860 ((not (assoc tg table))
14861 (org-get-todo-face tg))
14862 ((member tg current) c-face)
14863 ((member tg inherited) i-face))))
14864 (if (equal (caar tbl) :grouptags)
14865 (org-add-props tg nil 'face 'org-tag-group))
14866 (if (and (= cnt 0) (not ingroup)) (insert " "))
14867 (insert "[" c "] " tg (make-string
14868 (- fwidth 4 (length tg)) ?\ ))
14869 (push (cons tg c) ntable)
14870 (when (= (setq cnt (1+ cnt)) ncol)
14871 (insert "\n")
14872 (if ingroup (insert " "))
14873 (setq cnt 0)))))
14874 (setq ntable (nreverse ntable))
14875 (insert "\n")
14876 (goto-char (point-min))
14877 (if (not expert) (org-fit-window-to-buffer))
14878 (setq rtn
14879 (catch 'exit
14880 (while t
14881 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14882 (if (not groups) "no " "")
14883 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14884 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14885 (setq org-last-tag-selection-key c)
14886 (cond
14887 ((= c ?\r) (throw 'exit t))
14888 ((= c ?!)
14889 (setq groups (not groups))
14890 (goto-char (point-min))
14891 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14892 ((= c ?\C-c)
14893 (if (not expert)
14894 (org-fast-tag-show-exit
14895 (setq exit-after-next (not exit-after-next)))
14896 (setq expert nil)
14897 (delete-other-windows)
14898 (set-window-buffer (split-window-vertically) " *Org tags*")
14899 (org-switch-to-buffer-other-window " *Org tags*")
14900 (org-fit-window-to-buffer)))
14901 ((or (= c ?\C-g)
14902 (and (= c ?q) (not (rassoc c ntable))))
14903 (org-detach-overlay org-tags-overlay)
14904 (setq quit-flag t))
14905 ((= c ?\ )
14906 (setq current nil)
14907 (if exit-after-next (setq exit-after-next 'now)))
14908 ((= c ?\t)
14909 (condition-case nil
14910 (setq tg (org-icompleting-read
14911 "Tag: "
14912 (or buffer-tags
14913 (with-current-buffer buf
14914 (org-get-buffer-tags)))))
14915 (quit (setq tg "")))
14916 (when (string-match "\\S-" tg)
14917 (add-to-list 'buffer-tags (list tg))
14918 (if (member tg current)
14919 (setq current (delete tg current))
14920 (push tg current)))
14921 (if exit-after-next (setq exit-after-next 'now)))
14922 ((setq e (rassoc c todo-table) tg (car e))
14923 (with-current-buffer buf
14924 (save-excursion (org-todo tg)))
14925 (if exit-after-next (setq exit-after-next 'now)))
14926 ((setq e (rassoc c ntable) tg (car e))
14927 (if (member tg current)
14928 (setq current (delete tg current))
14929 (loop for g in groups do
14930 (if (member tg g)
14931 (mapc (lambda (x)
14932 (setq current (delete x current)))
14933 g)))
14934 (push tg current))
14935 (if exit-after-next (setq exit-after-next 'now))))
14937 ;; Create a sorted list
14938 (setq current
14939 (sort current
14940 (lambda (a b)
14941 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14942 (if (eq exit-after-next 'now) (throw 'exit t))
14943 (goto-char (point-min))
14944 (beginning-of-line 2)
14945 (delete-region (point) (point-at-eol))
14946 (org-fast-tag-insert "Current" current c-face)
14947 (org-set-current-tags-overlay current ov-prefix)
14948 (while (re-search-forward
14949 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14950 (setq tg (match-string 1))
14951 (add-text-properties
14952 (match-beginning 1) (match-end 1)
14953 (list 'face
14954 (cond
14955 ((member tg current) c-face)
14956 ((member tg inherited) i-face)
14957 (t (get-text-property (match-beginning 1) 'face))))))
14958 (goto-char (point-min)))))
14959 (org-detach-overlay org-tags-overlay)
14960 (if rtn
14961 (mapconcat 'identity current ":")
14962 nil))))
14964 (defun org-get-tags-string ()
14965 "Get the TAGS string in the current headline."
14966 (unless (org-at-heading-p t)
14967 (user-error "Not on a heading"))
14968 (save-excursion
14969 (beginning-of-line 1)
14970 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14971 (org-match-string-no-properties 1)
14972 "")))
14974 (defun org-get-tags ()
14975 "Get the list of tags specified in the current headline."
14976 (org-split-string (org-get-tags-string) ":"))
14978 (defun org-get-buffer-tags ()
14979 "Get a table of all tags used in the buffer, for completion."
14980 (let (tags)
14981 (save-excursion
14982 (goto-char (point-min))
14983 (while (re-search-forward
14984 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14985 (when (equal (char-after (point-at-bol 0)) ?*)
14986 (mapc (lambda (x) (add-to-list 'tags x))
14987 (org-split-string (org-match-string-no-properties 1) ":")))))
14988 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14989 (mapcar 'list tags)))
14991 ;;;; The mapping API
14993 (defun org-map-entries (func &optional match scope &rest skip)
14994 "Call FUNC at each headline selected by MATCH in SCOPE.
14996 FUNC is a function or a lisp form. The function will be called without
14997 arguments, with the cursor positioned at the beginning of the headline.
14998 The return values of all calls to the function will be collected and
14999 returned as a list.
15001 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15002 does not need to preserve point. After evaluation, the cursor will be
15003 moved to the end of the line (presumably of the headline of the
15004 processed entry) and search continues from there. Under some
15005 circumstances, this may not produce the wanted results. For example,
15006 if you have removed (e.g. archived) the current (sub)tree it could
15007 mean that the next entry will be skipped entirely. In such cases, you
15008 can specify the position from where search should continue by making
15009 FUNC set the variable `org-map-continue-from' to the desired buffer
15010 position.
15012 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15013 Only headlines that are matched by this query will be considered during
15014 the iteration. When MATCH is nil or t, all headlines will be
15015 visited by the iteration.
15017 SCOPE determines the scope of this command. It can be any of:
15019 nil The current buffer, respecting the restriction if any
15020 tree The subtree started with the entry at point
15021 region The entries within the active region, if any
15022 region-start-level
15023 The entries within the active region, but only those at
15024 the same level than the first one.
15025 file The current buffer, without restriction
15026 file-with-archives
15027 The current buffer, and any archives associated with it
15028 agenda All agenda files
15029 agenda-with-archives
15030 All agenda files with any archive files associated with them
15031 \(file1 file2 ...)
15032 If this is a list, all files in the list will be scanned
15034 The remaining args are treated as settings for the skipping facilities of
15035 the scanner. The following items can be given here:
15037 archive skip trees with the archive tag
15038 comment skip trees with the COMMENT keyword
15039 function or Emacs Lisp form:
15040 will be used as value for `org-agenda-skip-function', so
15041 whenever the function returns a position, FUNC will not be
15042 called for that entry and search will continue from the
15043 position returned
15045 If your function needs to retrieve the tags including inherited tags
15046 at the *current* entry, you can use the value of the variable
15047 `org-scanner-tags' which will be much faster than getting the value
15048 with `org-get-tags-at'. If your function gets properties with
15049 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15050 to t around the call to `org-entry-properties' to get the same speedup.
15051 Note that if your function moves around to retrieve tags and properties at
15052 a *different* entry, you cannot use these techniques."
15053 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15054 (not (org-region-active-p)))
15055 (let* ((org-agenda-archives-mode nil) ; just to make sure
15056 (org-agenda-skip-archived-trees (memq 'archive skip))
15057 (org-agenda-skip-comment-trees (memq 'comment skip))
15058 (org-agenda-skip-function
15059 (car (org-delete-all '(comment archive) skip)))
15060 (org-tags-match-list-sublevels t)
15061 (start-level (eq scope 'region-start-level))
15062 matcher file res
15063 org-todo-keywords-for-agenda
15064 org-done-keywords-for-agenda
15065 org-todo-keyword-alist-for-agenda
15066 org-tag-alist-for-agenda
15067 todo-only)
15069 (cond
15070 ((eq match t) (setq matcher t))
15071 ((eq match nil) (setq matcher t))
15072 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15074 (save-window-excursion
15075 (save-restriction
15076 (cond ((eq scope 'tree)
15077 (org-back-to-heading t)
15078 (org-narrow-to-subtree)
15079 (setq scope nil))
15080 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15081 (org-region-active-p))
15082 ;; If needed, set start-level to a string like "2"
15083 (when start-level
15084 (save-excursion
15085 (goto-char (region-beginning))
15086 (unless (org-at-heading-p) (outline-next-heading))
15087 (setq start-level (org-current-level))))
15088 (narrow-to-region (region-beginning)
15089 (save-excursion
15090 (goto-char (region-end))
15091 (unless (and (bolp) (org-at-heading-p))
15092 (outline-next-heading))
15093 (point)))
15094 (setq scope nil)))
15096 (if (not scope)
15097 (progn
15098 (org-agenda-prepare-buffers
15099 (list (buffer-file-name (current-buffer))))
15100 (setq res (org-scan-tags func matcher todo-only start-level)))
15101 ;; Get the right scope
15102 (cond
15103 ((and scope (listp scope) (symbolp (car scope)))
15104 (setq scope (eval scope)))
15105 ((eq scope 'agenda)
15106 (setq scope (org-agenda-files t)))
15107 ((eq scope 'agenda-with-archives)
15108 (setq scope (org-agenda-files t))
15109 (setq scope (org-add-archive-files scope)))
15110 ((eq scope 'file)
15111 (setq scope (list (buffer-file-name))))
15112 ((eq scope 'file-with-archives)
15113 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15114 (org-agenda-prepare-buffers scope)
15115 (while (setq file (pop scope))
15116 (with-current-buffer (org-find-base-buffer-visiting file)
15117 (save-excursion
15118 (save-restriction
15119 (widen)
15120 (goto-char (point-min))
15121 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
15122 res)))
15124 ;;;; Properties
15126 ;;; Setting and retrieving properties
15128 (defconst org-special-properties
15129 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
15130 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
15131 "The special properties valid in Org-mode.
15133 These are properties that are not defined in the property drawer,
15134 but in some other way.")
15136 (defconst org-default-properties
15137 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15138 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15139 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15140 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15141 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
15142 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15143 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15144 "Some properties that are used by Org-mode for various purposes.
15145 Being in this list makes sure that they are offered for completion.")
15147 (defun org-property-action ()
15148 "Do an action on properties."
15149 (interactive)
15150 (let (c)
15151 (org-at-property-p)
15152 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15153 (setq c (read-char-exclusive))
15154 (cond
15155 ((equal c ?s)
15156 (call-interactively 'org-set-property))
15157 ((equal c ?d)
15158 (call-interactively 'org-delete-property))
15159 ((equal c ?D)
15160 (call-interactively 'org-delete-property-globally))
15161 ((equal c ?c)
15162 (call-interactively 'org-compute-property-at-point))
15163 (t (user-error "No such property action %c" c)))))
15165 (defun org-inc-effort ()
15166 "Increment the value of the effort property in the current entry."
15167 (interactive)
15168 (org-set-effort nil t))
15170 (defvar org-clock-effort) ;; Defined in org-clock.el
15171 (defvar org-clock-current-task) ;; Defined in org-clock.el
15172 (defun org-set-effort (&optional value increment)
15173 "Set the effort property of the current entry.
15174 With numerical prefix arg, use the nth allowed value, 0 stands for the
15175 10th allowed value.
15177 When INCREMENT is non-nil, set the property to the next allowed value."
15178 (interactive "P")
15179 (if (equal value 0) (setq value 10))
15180 (let* ((completion-ignore-case t)
15181 (prop org-effort-property)
15182 (cur (org-entry-get nil prop))
15183 (allowed (org-property-get-allowed-values nil prop 'table))
15184 (existing (mapcar 'list (org-property-values prop)))
15185 (heading (nth 4 (org-heading-components)))
15187 (val (cond
15188 ((stringp value) value)
15189 ((and allowed (integerp value))
15190 (or (car (nth (1- value) allowed))
15191 (car (org-last allowed))))
15192 ((and allowed increment)
15193 (or (caadr (member (list cur) allowed))
15194 (user-error "Allowed effort values are not set")))
15195 (allowed
15196 (message "Select 1-9,0, [RET%s]: %s"
15197 (if cur (concat "=" cur) "")
15198 (mapconcat 'car allowed " "))
15199 (setq rpl (read-char-exclusive))
15200 (if (equal rpl ?\r)
15202 (setq rpl (- rpl ?0))
15203 (if (equal rpl 0) (setq rpl 10))
15204 (if (and (> rpl 0) (<= rpl (length allowed)))
15205 (car (nth (1- rpl) allowed))
15206 (org-completing-read "Effort: " allowed nil))))
15208 (let (org-completion-use-ido org-completion-use-iswitchb)
15209 (org-completing-read
15210 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15211 (concat "[" cur "]") "")
15212 ": ")
15213 existing nil nil "" nil cur))))))
15214 (unless (equal (org-entry-get nil prop) val)
15215 (org-entry-put nil prop val))
15216 (save-excursion
15217 (org-back-to-heading t)
15218 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
15219 (when (string= heading org-clock-current-task)
15220 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
15221 (org-clock-update-mode-line))
15222 (message "%s is now %s" prop val)))
15224 (defun org-at-property-p ()
15225 "Is cursor inside a property drawer?"
15226 (save-excursion
15227 (when (equal 'node-property (car (org-element-at-point)))
15228 (beginning-of-line 1)
15229 (looking-at org-property-re))))
15231 (defun org-get-property-block (&optional beg end force)
15232 "Return the (beg . end) range of the body of the property drawer.
15233 BEG and END are the beginning and end of the current subtree, or of
15234 the part before the first headline. If they are not given, they will
15235 be found. If the drawer does not exist and FORCE is non-nil, create
15236 the drawer."
15237 (catch 'exit
15238 (save-excursion
15239 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15240 (progn (org-back-to-heading t) (point))))
15241 (end (or end (and (not (outline-next-heading)) (point-max))
15242 (point))))
15243 (goto-char beg)
15244 (if (re-search-forward org-property-start-re end t)
15245 (setq beg (1+ (match-end 0)))
15246 (if force
15247 (save-excursion
15248 (org-insert-property-drawer)
15249 (setq end (progn (outline-next-heading) (point))))
15250 (throw 'exit nil))
15251 (goto-char beg)
15252 (if (re-search-forward org-property-start-re end t)
15253 (setq beg (1+ (match-end 0)))))
15254 (if (re-search-forward org-property-end-re end t)
15255 (setq end (match-beginning 0))
15256 (or force (throw 'exit nil))
15257 (goto-char beg)
15258 (setq end beg)
15259 (org-indent-line)
15260 (insert ":END:\n"))
15261 (cons beg end)))))
15263 (defun org-entry-properties (&optional pom which specific)
15264 "Get all properties of the entry at point-or-marker POM.
15265 This includes the TODO keyword, the tags, time strings for deadline,
15266 scheduled, and clocking, and any additional properties defined in the
15267 entry. The return value is an alist, keys may occur multiple times
15268 if the property key was used several times.
15269 POM may also be nil, in which case the current entry is used.
15270 If WHICH is nil or `all', get all properties. If WHICH is
15271 `special' or `standard', only get that subclass. If WHICH
15272 is a string only get exactly this property. SPECIFIC can be a string, the
15273 specific property we are interested in. Specifying it can speed
15274 things up because then unnecessary parsing is avoided."
15275 (setq which (or which 'all))
15276 (org-with-wide-buffer
15277 (org-with-point-at pom
15278 (let ((clockstr (substring org-clock-string 0 -1))
15279 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15280 (case-fold-search nil)
15281 beg end range props sum-props key key1 value string clocksum clocksumt)
15282 (when (and (derived-mode-p 'org-mode)
15283 (ignore-errors (org-back-to-heading t)))
15284 (setq beg (point))
15285 (setq sum-props (get-text-property (point) 'org-summaries))
15286 (setq clocksum (get-text-property (point) :org-clock-minutes)
15287 clocksumt (get-text-property (point) :org-clock-minutes-today))
15288 (outline-next-heading)
15289 (setq end (point))
15290 (when (memq which '(all special))
15291 ;; Get the special properties, like TODO and tags
15292 (goto-char beg)
15293 (when (and (or (not specific) (string= specific "TODO"))
15294 (looking-at org-todo-line-regexp) (match-end 2))
15295 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15296 (when (and (or (not specific) (string= specific "PRIORITY"))
15297 (looking-at org-priority-regexp))
15298 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15299 (when (or (not specific) (string= specific "FILE"))
15300 (push (cons "FILE" buffer-file-name) props))
15301 (when (and (or (not specific) (string= specific "TAGS"))
15302 (setq value (org-get-tags-string))
15303 (string-match "\\S-" value))
15304 (push (cons "TAGS" value) props))
15305 (when (and (or (not specific) (string= specific "ALLTAGS"))
15306 (setq value (org-get-tags-at)))
15307 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15308 ":"))
15309 props))
15310 (when (or (not specific) (string= specific "BLOCKED"))
15311 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15312 (when (or (not specific)
15313 (member specific
15314 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15315 "TIMESTAMP" "TIMESTAMP_IA")))
15316 (catch 'match
15317 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15318 (setq key (if (match-end 1)
15319 (substring (org-match-string-no-properties 1)
15320 0 -1))
15321 string (if (equal key clockstr)
15322 (org-trim
15323 (buffer-substring-no-properties
15324 (match-beginning 3) (goto-char
15325 (point-at-eol))))
15326 (substring (org-match-string-no-properties 3)
15327 1 -1)))
15328 ;; Get the correct property name from the key. This is
15329 ;; necessary if the user has configured time keywords.
15330 (setq key1 (concat key ":"))
15331 (cond
15332 ((not key)
15333 (setq key
15334 (if (= (char-after (match-beginning 3)) ?\[)
15335 "TIMESTAMP_IA" "TIMESTAMP")))
15336 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15337 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15338 ((equal key1 org-closed-string) (setq key "CLOSED"))
15339 ((equal key1 org-clock-string) (setq key "CLOCK")))
15340 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15341 (progn
15342 (push (cons key string) props)
15343 ;; no need to search further if match is found
15344 (throw 'match t))
15345 (when (or (equal key "CLOCK") (not (assoc key props)))
15346 (push (cons key string) props)))))))
15348 (when (memq which '(all standard))
15349 ;; Get the standard properties, like :PROP: ...
15350 (setq range (org-get-property-block beg end))
15351 (when range
15352 (goto-char (car range))
15353 (while (re-search-forward org-property-re
15354 (cdr range) t)
15355 (setq key (org-match-string-no-properties 2)
15356 value (org-trim (or (org-match-string-no-properties 3) "")))
15357 (unless (member key excluded)
15358 (push (cons key (or value "")) props)))))
15359 (if clocksum
15360 (push (cons "CLOCKSUM"
15361 (org-columns-number-to-string (/ (float clocksum) 60.)
15362 'add_times))
15363 props))
15364 (if clocksumt
15365 (push (cons "CLOCKSUM_T"
15366 (org-columns-number-to-string (/ (float clocksumt) 60.)
15367 'add_times))
15368 props))
15369 (unless (assoc "CATEGORY" props)
15370 (push (cons "CATEGORY" (org-get-category)) props))
15371 (append sum-props (nreverse props)))))))
15373 (defun org-entry-get (pom property &optional inherit literal-nil)
15374 "Get value of PROPERTY for entry or content at point-or-marker POM.
15375 If INHERIT is non-nil and the entry does not have the property,
15376 then also check higher levels of the hierarchy.
15377 If INHERIT is the symbol `selective', use inheritance only if the setting
15378 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15379 If the property is present but empty, the return value is the empty string.
15380 If the property is not present at all, nil is returned.
15382 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15383 do not interpret it as the list atom nil. This is used for inheritance
15384 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15385 (org-with-point-at pom
15386 (if (and inherit (if (eq inherit 'selective)
15387 (org-property-inherit-p property)
15389 (org-entry-get-with-inheritance property literal-nil)
15390 (if (member property org-special-properties)
15391 ;; We need a special property. Use `org-entry-properties'
15392 ;; to retrieve it, but specify the wanted property
15393 (cdr (assoc property (org-entry-properties nil 'special property)))
15394 (org-with-wide-buffer
15395 (let ((range (org-get-property-block)))
15396 (when (and range (not (eq (car range) (cdr range))))
15397 (let* ((props
15398 (list (or (assoc property org-file-properties)
15399 (assoc property org-global-properties)
15400 (assoc property org-global-properties-fixed))))
15401 (ap (lambda (key)
15402 (when (re-search-forward
15403 (org-re-property key) (cdr range) t)
15404 (setq props
15405 (org-update-property-plist
15407 (if (match-end 3)
15408 (org-match-string-no-properties 3) "")
15409 props)))))
15410 val)
15411 (goto-char (car range))
15412 (funcall ap property)
15413 (goto-char (car range))
15414 (while (funcall ap (concat property "+")))
15415 (setq val (cdr (assoc property props)))
15416 (when val (if literal-nil val (org-not-nil val)))))))))))
15418 (defun org-property-or-variable-value (var &optional inherit)
15419 "Check if there is a property fixing the value of VAR.
15420 If yes, return this value. If not, return the current value of the variable."
15421 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15422 (if (and prop (stringp prop) (string-match "\\S-" prop))
15423 (read prop)
15424 (symbol-value var))))
15426 (defun org-entry-delete (pom property)
15427 "Delete the property PROPERTY from entry at point-or-marker POM."
15428 (unless (member property org-special-properties)
15429 (org-with-point-at pom
15430 (let ((range (org-get-property-block)))
15431 (if (and range
15432 (goto-char (car range))
15433 (re-search-forward
15434 (org-re-property property)
15435 (cdr range) t))
15436 (progn
15437 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15438 (org-remove-empty-drawer-at (car range))
15440 nil)))))
15442 ;; Multi-values properties are properties that contain multiple values
15443 ;; These values are assumed to be single words, separated by whitespace.
15444 (defun org-entry-add-to-multivalued-property (pom property value)
15445 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15446 (let* ((old (org-entry-get pom property))
15447 (values (and old (org-split-string old "[ \t]"))))
15448 (setq value (org-entry-protect-space value))
15449 (unless (member value values)
15450 (setq values (append values (list value)))
15451 (org-entry-put pom property
15452 (mapconcat 'identity values " ")))))
15454 (defun org-entry-remove-from-multivalued-property (pom property value)
15455 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15456 (let* ((old (org-entry-get pom property))
15457 (values (and old (org-split-string old "[ \t]"))))
15458 (setq value (org-entry-protect-space value))
15459 (when (member value values)
15460 (setq values (delete value values))
15461 (org-entry-put pom property
15462 (mapconcat 'identity values " ")))))
15464 (defun org-entry-member-in-multivalued-property (pom property value)
15465 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15466 (let* ((old (org-entry-get pom property))
15467 (values (and old (org-split-string old "[ \t]"))))
15468 (setq value (org-entry-protect-space value))
15469 (member value values)))
15471 (defun org-entry-get-multivalued-property (pom property)
15472 "Return a list of values in a multivalued property."
15473 (let* ((value (org-entry-get pom property))
15474 (values (and value (org-split-string value "[ \t]"))))
15475 (mapcar 'org-entry-restore-space values)))
15477 (defun org-entry-put-multivalued-property (pom property &rest values)
15478 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15479 VALUES should be a list of strings. Spaces will be protected."
15480 (org-entry-put pom property
15481 (mapconcat 'org-entry-protect-space values " "))
15482 (let* ((value (org-entry-get pom property))
15483 (values (and value (org-split-string value "[ \t]"))))
15484 (mapcar 'org-entry-restore-space values)))
15486 (defun org-entry-protect-space (s)
15487 "Protect spaces and newline in string S."
15488 (while (string-match " " s)
15489 (setq s (replace-match "%20" t t s)))
15490 (while (string-match "\n" s)
15491 (setq s (replace-match "%0A" t t s)))
15494 (defun org-entry-restore-space (s)
15495 "Restore spaces and newline in string S."
15496 (while (string-match "%20" s)
15497 (setq s (replace-match " " t t s)))
15498 (while (string-match "%0A" s)
15499 (setq s (replace-match "\n" t t s)))
15502 (defvar org-entry-property-inherited-from (make-marker)
15503 "Marker pointing to the entry from where a property was inherited.
15504 Each call to `org-entry-get-with-inheritance' will set this marker to the
15505 location of the entry where the inheritance search matched. If there was
15506 no match, the marker will point nowhere.
15507 Note that also `org-entry-get' calls this function, if the INHERIT flag
15508 is set.")
15510 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15511 "Get PROPERTY of entry or content at point, search higher levels if needed.
15512 The search will stop at the first ancestor which has the property defined.
15513 If the value found is \"nil\", return nil to show that the property
15514 should be considered as undefined (this is the meaning of nil here).
15515 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15516 (move-marker org-entry-property-inherited-from nil)
15517 (let (tmp)
15518 (save-excursion
15519 (save-restriction
15520 (widen)
15521 (catch 'ex
15522 (while t
15523 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
15524 (or (ignore-errors (org-back-to-heading t))
15525 (goto-char (point-min)))
15526 (move-marker org-entry-property-inherited-from (point))
15527 (throw 'ex tmp))
15528 (or (ignore-errors (org-up-heading-safe))
15529 (throw 'ex nil))))))
15530 (setq tmp (or tmp
15531 (cdr (assoc property org-file-properties))
15532 (cdr (assoc property org-global-properties))
15533 (cdr (assoc property org-global-properties-fixed))))
15534 (if literal-nil tmp (org-not-nil tmp))))
15536 (defvar org-property-changed-functions nil
15537 "Hook called when the value of a property has changed.
15538 Each hook function should accept two arguments, the name of the property
15539 and the new value.")
15541 (defun org-entry-put (pom property value)
15542 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15543 If the value is `nil', it is converted to the empty string.
15544 If it is not a string, an error is raised."
15545 (cond ((null value) (setq value ""))
15546 ((not (stringp value))
15547 (error "Properties values should be strings.")))
15548 (org-with-point-at pom
15549 (org-back-to-heading t)
15550 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15551 range)
15552 (cond
15553 ((equal property "TODO")
15554 (when (and (string-match "\\S-" value)
15555 (not (member value org-todo-keywords-1)))
15556 (user-error "\"%s\" is not a valid TODO state" value))
15557 (if (or (not value)
15558 (not (string-match "\\S-" value)))
15559 (setq value 'none))
15560 (org-todo value)
15561 (org-set-tags nil 'align))
15562 ((equal property "PRIORITY")
15563 (org-priority (if (and value (string-match "\\S-" value))
15564 (string-to-char value) ?\ ))
15565 (org-set-tags nil 'align))
15566 ((equal property "CLOCKSUM")
15567 (if (not (re-search-forward
15568 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15569 (error "Cannot find a clock log")
15570 (goto-char (- (match-end 1) 2))
15571 (cond
15572 ((eq value 'earlier) (org-timestamp-down))
15573 ((eq value 'later) (org-timestamp-up)))
15574 (org-clock-sum-current-item)))
15575 ((equal property "SCHEDULED")
15576 (if (re-search-forward org-scheduled-time-regexp end t)
15577 (cond
15578 ((eq value 'earlier) (org-timestamp-change -1 'day))
15579 ((eq value 'later) (org-timestamp-change 1 'day))
15580 (t (call-interactively 'org-schedule)))
15581 (call-interactively 'org-schedule)))
15582 ((equal property "DEADLINE")
15583 (if (re-search-forward org-deadline-time-regexp end t)
15584 (cond
15585 ((eq value 'earlier) (org-timestamp-change -1 'day))
15586 ((eq value 'later) (org-timestamp-change 1 'day))
15587 (t (call-interactively 'org-deadline)))
15588 (call-interactively 'org-deadline)))
15589 ((member property org-special-properties)
15590 (error "The %s property can not yet be set with `org-entry-put'"
15591 property))
15592 (t ; a non-special property
15593 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15594 (setq range (org-get-property-block beg end 'force))
15595 (goto-char (car range))
15596 (if (re-search-forward
15597 (org-re-property property) (cdr range) t)
15598 (progn
15599 (delete-region (match-beginning 0) (match-end 0))
15600 (goto-char (match-beginning 0)))
15601 (goto-char (cdr range))
15602 (insert "\n")
15603 (backward-char 1)
15604 (org-indent-line))
15605 (insert ":" property ":")
15606 (and value (insert " " value))
15607 (org-indent-line)))))
15608 (run-hook-with-args 'org-property-changed-functions property value)))
15610 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15611 "Get all property keys in the current buffer.
15612 With INCLUDE-SPECIALS, also list the special properties that reflect things
15613 like tags and TODO state.
15614 With INCLUDE-DEFAULTS, also include properties that has special meaning
15615 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15616 and others.
15617 With INCLUDE-COLUMNS, also include property names given in COLUMN
15618 formats in the current buffer."
15619 (let (rtn range cfmt s p)
15620 (save-excursion
15621 (save-restriction
15622 (widen)
15623 (goto-char (point-min))
15624 (while (re-search-forward org-property-start-re nil t)
15625 (setq range (org-get-property-block))
15626 (goto-char (car range))
15627 (while (re-search-forward org-property-re
15628 (cdr range) t)
15629 (add-to-list 'rtn (org-match-string-no-properties 2)))
15630 (outline-next-heading))))
15632 (when include-specials
15633 (setq rtn (append org-special-properties rtn)))
15635 (when include-defaults
15636 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15637 (add-to-list 'rtn org-effort-property))
15639 (when include-columns
15640 (save-excursion
15641 (save-restriction
15642 (widen)
15643 (goto-char (point-min))
15644 (while (re-search-forward
15645 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15646 nil t)
15647 (setq cfmt (match-string 2) s 0)
15648 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15649 cfmt s)
15650 (setq s (match-end 0)
15651 p (match-string 1 cfmt))
15652 (unless (or (equal p "ITEM")
15653 (member p org-special-properties))
15654 (add-to-list 'rtn (match-string 1 cfmt))))))))
15656 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15658 (defun org-property-values (key)
15659 "Return a list of all values of property KEY in the current buffer."
15660 (save-excursion
15661 (save-restriction
15662 (widen)
15663 (goto-char (point-min))
15664 (let ((re (org-re-property key))
15665 values)
15666 (while (re-search-forward re nil t)
15667 (add-to-list 'values (org-trim (match-string 3))))
15668 (delete "" values)))))
15670 (defun org-insert-property-drawer ()
15671 "Insert a property drawer into the current entry."
15672 (org-back-to-heading t)
15673 (looking-at org-outline-regexp)
15674 (let ((indent (if org-adapt-indentation
15675 (- (match-end 0) (match-beginning 0))
15677 (beg (point))
15678 (re (concat "^[ \t]*" org-keyword-time-regexp))
15679 end hiddenp)
15680 (outline-next-heading)
15681 (setq end (point))
15682 (goto-char beg)
15683 (while (re-search-forward re end t))
15684 (setq hiddenp (outline-invisible-p))
15685 (end-of-line 1)
15686 (and (equal (char-after) ?\n) (forward-char 1))
15687 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15688 (if (member (match-string 1) '("CLOCK:" ":END:"))
15689 ;; just skip this line
15690 (beginning-of-line 2)
15691 ;; Drawer start, find the end
15692 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15693 (beginning-of-line 1)))
15694 (org-skip-over-state-notes)
15695 (skip-chars-backward " \t\n\r")
15696 (if (and (eq (char-before) ?*) (not (eq (char-after) ?\n)))
15697 (forward-char 1))
15698 (goto-char (point-at-eol))
15699 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15700 (beginning-of-line 0)
15701 (org-indent-to-column indent)
15702 (beginning-of-line 2)
15703 (org-indent-to-column indent)
15704 (beginning-of-line 0)
15705 (if hiddenp
15706 (save-excursion
15707 (org-back-to-heading t)
15708 (hide-entry))
15709 (org-flag-drawer t))))
15711 (defun org-insert-drawer (&optional arg drawer)
15712 "Insert a drawer at point.
15714 Optional argument DRAWER, when non-nil, is a string representing
15715 drawer's name. Otherwise, the user is prompted for a name.
15717 If a region is active, insert the drawer around that region
15718 instead.
15720 Point is left between drawer's boundaries."
15721 (interactive "P")
15722 (let* ((drawer (if arg "PROPERTIES"
15723 (or drawer (read-from-minibuffer "Drawer: ")))))
15724 (cond
15725 ;; With C-u, fall back on `org-insert-property-drawer'
15726 (arg (org-insert-property-drawer))
15728 ((not (org-string-match-p org-drawer-regexp (format ":%s:" drawer)))
15729 (user-error "Invalid drawer name"))
15730 ;; With an active region, insert a drawer at point.
15731 ((not (org-region-active-p))
15732 (progn
15733 (unless (bolp) (insert "\n"))
15734 (insert (format ":%s:\n\n:END:\n" drawer))
15735 (forward-line -2)))
15736 ;; Otherwise, insert the drawer at point
15738 (let ((rbeg (region-beginning))
15739 (rend (copy-marker (region-end))))
15740 (unwind-protect
15741 (progn
15742 (goto-char rbeg)
15743 (beginning-of-line)
15744 (when (save-excursion
15745 (re-search-forward org-outline-regexp-bol rend t))
15746 (user-error "Drawers cannot contain headlines"))
15747 ;; Position point at the beginning of the first
15748 ;; non-blank line in region. Insert drawer's opening
15749 ;; there, then indent it.
15750 (org-skip-whitespace)
15751 (beginning-of-line)
15752 (insert ":" drawer ":\n")
15753 (forward-line -1)
15754 (indent-for-tab-command)
15755 ;; Move point to the beginning of the first blank line
15756 ;; after the last non-blank line in region. Insert
15757 ;; drawer's closing, then indent it.
15758 (goto-char rend)
15759 (skip-chars-backward " \r\t\n")
15760 (insert "\n:END:")
15761 (deactivate-mark t)
15762 (indent-for-tab-command)
15763 (unless (eolp) (insert "\n")))
15764 ;; Clear marker, whatever the outcome of insertion is.
15765 (set-marker rend nil)))))))
15767 (defvar org-property-set-functions-alist nil
15768 "Property set function alist.
15769 Each entry should have the following format:
15771 (PROPERTY . READ-FUNCTION)
15773 The read function will be called with the same argument as
15774 `org-completing-read'.")
15776 (defun org-set-property-function (property)
15777 "Get the function that should be used to set PROPERTY.
15778 This is computed according to `org-property-set-functions-alist'."
15779 (or (cdr (assoc property org-property-set-functions-alist))
15780 'org-completing-read))
15782 (defun org-read-property-value (property)
15783 "Read PROPERTY value from user."
15784 (let* ((completion-ignore-case t)
15785 (allowed (org-property-get-allowed-values nil property 'table))
15786 (cur (org-entry-get nil property))
15787 (prompt (concat property " value"
15788 (if (and cur (string-match "\\S-" cur))
15789 (concat " [" cur "]") "") ": "))
15790 (set-function (org-set-property-function property))
15791 (val (if allowed
15792 (funcall set-function prompt allowed nil
15793 (not (get-text-property 0 'org-unrestricted
15794 (caar allowed))))
15795 (let (org-completion-use-ido org-completion-use-iswitchb)
15796 (funcall set-function prompt
15797 (mapcar 'list (org-property-values property))
15798 nil nil "" nil cur)))))
15799 (if (equal val "")
15801 val)))
15803 (defvar org-last-set-property nil)
15804 (defvar org-last-set-property-value nil)
15805 (defun org-read-property-name ()
15806 "Read a property name."
15807 (let* ((completion-ignore-case t)
15808 (keys (org-buffer-property-keys nil t t))
15809 (default-prop (or (save-excursion
15810 (save-match-data
15811 (beginning-of-line)
15812 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15813 (null (string= (match-string 1) "END"))
15814 (match-string 1))))
15815 org-last-set-property))
15816 (property (org-icompleting-read
15817 (concat "Property"
15818 (if default-prop (concat " [" default-prop "]") "")
15819 ": ")
15820 (mapcar 'list keys)
15821 nil nil nil nil
15822 default-prop)))
15823 (if (member property keys)
15824 property
15825 (or (cdr (assoc (downcase property)
15826 (mapcar (lambda (x) (cons (downcase x) x))
15827 keys)))
15828 property))))
15830 (defun org-set-property-and-value (use-last)
15831 "Allow to set [PROPERTY]: [value] direction from prompt.
15832 When use-default, don't even ask, just use the last
15833 \"[PROPERTY]: [value]\" string from the history."
15834 (interactive "P")
15835 (let* ((completion-ignore-case t)
15836 (pv (or (and use-last org-last-set-property-value)
15837 (org-completing-read
15838 "Enter a \"[Property]: [value]\" pair: "
15839 nil nil nil nil nil
15840 org-last-set-property-value)))
15841 prop val)
15842 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15843 (setq prop (match-string 1 pv)
15844 val (match-string 2 pv))
15845 (org-set-property prop val))))
15847 (defun org-set-property (property value)
15848 "In the current entry, set PROPERTY to VALUE.
15849 When called interactively, this will prompt for a property name, offering
15850 completion on existing and default properties. And then it will prompt
15851 for a value, offering completion either on allowed values (via an inherited
15852 xxx_ALL property) or on existing values in other instances of this property
15853 in the current file."
15854 (interactive (list nil nil))
15855 (let* ((property (or property (org-read-property-name)))
15856 (value (or value (org-read-property-value property)))
15857 (fn (cdr (assoc property org-properties-postprocess-alist))))
15858 (setq org-last-set-property property)
15859 (setq org-last-set-property-value (concat property ": " value))
15860 ;; Possibly postprocess the inserted value:
15861 (when fn (setq value (funcall fn value)))
15862 (unless (equal (org-entry-get nil property) value)
15863 (org-entry-put nil property value))))
15865 (defun org-delete-property (property)
15866 "In the current entry, delete PROPERTY."
15867 (interactive
15868 (let* ((completion-ignore-case t)
15869 (prop (org-icompleting-read "Property: "
15870 (org-entry-properties nil 'standard))))
15871 (list prop)))
15872 (message "Property %s %s" property
15873 (if (org-entry-delete nil property)
15874 "deleted"
15875 "was not present in the entry")))
15877 (defun org-delete-property-globally (property)
15878 "Remove PROPERTY globally, from all entries."
15879 (interactive
15880 (let* ((completion-ignore-case t)
15881 (prop (org-icompleting-read
15882 "Globally remove property: "
15883 (mapcar 'list (org-buffer-property-keys)))))
15884 (list prop)))
15885 (save-excursion
15886 (save-restriction
15887 (widen)
15888 (goto-char (point-min))
15889 (let ((cnt 0))
15890 (while (re-search-forward
15891 (org-re-property property)
15892 nil t)
15893 (setq cnt (1+ cnt))
15894 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15895 (message "Property \"%s\" removed from %d entries" property cnt)))))
15897 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15899 (defun org-compute-property-at-point ()
15900 "Compute the property at point.
15901 This looks for an enclosing column format, extracts the operator and
15902 then applies it to the property in the column format's scope."
15903 (interactive)
15904 (unless (org-at-property-p)
15905 (user-error "Not at a property"))
15906 (let ((prop (org-match-string-no-properties 2)))
15907 (org-columns-get-format-and-top-level)
15908 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15909 (user-error "No operator defined for property %s" prop))
15910 (org-columns-compute prop)))
15912 (defvar org-property-allowed-value-functions nil
15913 "Hook for functions supplying allowed values for a specific property.
15914 The functions must take a single argument, the name of the property, and
15915 return a flat list of allowed values. If \":ETC\" is one of
15916 the values, this means that these values are intended as defaults for
15917 completion, but that other values should be allowed too.
15918 The functions must return nil if they are not responsible for this
15919 property.")
15921 (defun org-property-get-allowed-values (pom property &optional table)
15922 "Get allowed values for the property PROPERTY.
15923 When TABLE is non-nil, return an alist that can directly be used for
15924 completion."
15925 (let (vals)
15926 (cond
15927 ((equal property "TODO")
15928 (setq vals (org-with-point-at pom
15929 (append org-todo-keywords-1 '("")))))
15930 ((equal property "PRIORITY")
15931 (let ((n org-lowest-priority))
15932 (while (>= n org-highest-priority)
15933 (push (char-to-string n) vals)
15934 (setq n (1- n)))))
15935 ((member property org-special-properties))
15936 ((setq vals (run-hook-with-args-until-success
15937 'org-property-allowed-value-functions property)))
15939 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15940 (when (and vals (string-match "\\S-" vals))
15941 (setq vals (car (read-from-string (concat "(" vals ")"))))
15942 (setq vals (mapcar (lambda (x)
15943 (cond ((stringp x) x)
15944 ((numberp x) (number-to-string x))
15945 ((symbolp x) (symbol-name x))
15946 (t "???")))
15947 vals)))))
15948 (when (member ":ETC" vals)
15949 (setq vals (remove ":ETC" vals))
15950 (org-add-props (car vals) '(org-unrestricted t)))
15951 (if table (mapcar 'list vals) vals)))
15953 (defun org-property-previous-allowed-value (&optional previous)
15954 "Switch to the next allowed value for this property."
15955 (interactive)
15956 (org-property-next-allowed-value t))
15958 (defun org-property-next-allowed-value (&optional previous)
15959 "Switch to the next allowed value for this property."
15960 (interactive)
15961 (unless (org-at-property-p)
15962 (user-error "Not at a property"))
15963 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15964 (key (match-string 2))
15965 (value (match-string 3))
15966 (allowed (or (org-property-get-allowed-values (point) key)
15967 (and (member value '("[ ]" "[-]" "[X]"))
15968 '("[ ]" "[X]"))))
15969 (heading (save-match-data (nth 4 (org-heading-components))))
15970 nval)
15971 (unless allowed
15972 (user-error "Allowed values for this property have not been defined"))
15973 (if previous (setq allowed (reverse allowed)))
15974 (if (member value allowed)
15975 (setq nval (car (cdr (member value allowed)))))
15976 (setq nval (or nval (car allowed)))
15977 (if (equal nval value)
15978 (user-error "Only one allowed value for this property"))
15979 (org-at-property-p)
15980 (replace-match (concat " :" key ": " nval) t t)
15981 (org-indent-line)
15982 (beginning-of-line 1)
15983 (skip-chars-forward " \t")
15984 (when (equal prop org-effort-property)
15985 (save-excursion
15986 (org-back-to-heading t)
15987 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
15988 (when (string= org-clock-current-task heading)
15989 (setq org-clock-effort nval)
15990 (org-clock-update-mode-line)))
15991 (run-hook-with-args 'org-property-changed-functions key nval)))
15993 (defun org-find-olp (path &optional this-buffer)
15994 "Return a marker pointing to the entry at outline path OLP.
15995 If anything goes wrong, throw an error.
15996 You can wrap this call to catch the error like this:
15998 (condition-case msg
15999 (org-mobile-locate-entry (match-string 4))
16000 (error (nth 1 msg)))
16002 The return value will then be either a string with the error message,
16003 or a marker if everything is OK.
16005 If THIS-BUFFER is set, the outline path does not contain a file,
16006 only headings."
16007 (let* ((file (if this-buffer buffer-file-name (pop path)))
16008 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16009 (level 1)
16010 (lmin 1)
16011 (lmax 1)
16012 limit re end found pos heading cnt flevel)
16013 (unless buffer (error "File not found :%s" file))
16014 (with-current-buffer buffer
16015 (save-excursion
16016 (save-restriction
16017 (widen)
16018 (setq limit (point-max))
16019 (goto-char (point-min))
16020 (while (setq heading (pop path))
16021 (setq re (format org-complex-heading-regexp-format
16022 (regexp-quote heading)))
16023 (setq cnt 0 pos (point))
16024 (while (re-search-forward re end t)
16025 (setq level (- (match-end 1) (match-beginning 1)))
16026 (if (and (>= level lmin) (<= level lmax))
16027 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16028 (when (= cnt 0) (error "Heading not found on level %d: %s"
16029 lmax heading))
16030 (when (> cnt 1) (error "Heading not unique on level %d: %s"
16031 lmax heading))
16032 (goto-char found)
16033 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16034 (setq end (save-excursion (org-end-of-subtree t t))))
16035 (when (org-at-heading-p)
16036 (point-marker)))))))
16038 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16039 "Find node HEADING in BUFFER.
16040 Return a marker to the heading if it was found, or nil if not.
16041 If POS-ONLY is set, return just the position instead of a marker.
16043 The heading text must match exact, but it may have a TODO keyword,
16044 a priority cookie and tags in the standard locations."
16045 (with-current-buffer (or buffer (current-buffer))
16046 (save-excursion
16047 (save-restriction
16048 (widen)
16049 (goto-char (point-min))
16050 (let (case-fold-search)
16051 (if (re-search-forward
16052 (format org-complex-heading-regexp-format
16053 (regexp-quote heading)) nil t)
16054 (if pos-only
16055 (match-beginning 0)
16056 (move-marker (make-marker) (match-beginning 0)))))))))
16058 (defun org-find-exact-heading-in-directory (heading &optional dir)
16059 "Find Org node headline HEADING in all .org files in directory DIR.
16060 When the target headline is found, return a marker to this location."
16061 (let ((files (directory-files (or dir default-directory)
16062 nil "\\`[^.#].*\\.org\\'"))
16063 file visiting m buffer)
16064 (catch 'found
16065 (while (setq file (pop files))
16066 (message "trying %s" file)
16067 (setq visiting (org-find-base-buffer-visiting file))
16068 (setq buffer (or visiting (find-file-noselect file)))
16069 (setq m (org-find-exact-headline-in-buffer
16070 heading buffer))
16071 (when (and (not m) (not visiting)) (kill-buffer buffer))
16072 (and m (throw 'found m))))))
16074 (defun org-find-entry-with-id (ident)
16075 "Locate the entry that contains the ID property with exact value IDENT.
16076 IDENT can be a string, a symbol or a number, this function will search for
16077 the string representation of it.
16078 Return the position where this entry starts, or nil if there is no such entry."
16079 (interactive "sID: ")
16080 (let ((id (cond
16081 ((stringp ident) ident)
16082 ((symbol-name ident) (symbol-name ident))
16083 ((numberp ident) (number-to-string ident))
16084 (t (error "IDENT %s must be a string, symbol or number" ident))))
16085 (case-fold-search nil))
16086 (save-excursion
16087 (save-restriction
16088 (widen)
16089 (goto-char (point-min))
16090 (when (re-search-forward
16091 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16092 nil t)
16093 (org-back-to-heading t)
16094 (point))))))
16096 ;;;; Timestamps
16098 (defvar org-last-changed-timestamp nil)
16099 (defvar org-last-inserted-timestamp nil
16100 "The last time stamp inserted with `org-insert-time-stamp'.")
16101 (defvar org-ts-what) ; dynamically scoped parameter
16103 (defun org-time-stamp (arg &optional inactive)
16104 "Prompt for a date/time and insert a time stamp.
16105 If the user specifies a time like HH:MM or if this command is
16106 called with at least one prefix argument, the time stamp contains
16107 the date and the time. Otherwise, only the date is be included.
16109 All parts of a date not specified by the user is filled in from
16110 the current date/time. So if you just press return without
16111 typing anything, the time stamp will represent the current
16112 date/time.
16114 If there is already a timestamp at the cursor, it will be
16115 modified.
16117 With two universal prefix arguments, insert an active timestamp
16118 with the current time without prompting the user.
16120 When called from lisp, the timestamp is inactive if INACTIVE is
16121 non-nil."
16122 (interactive "P")
16123 (let* ((ts nil)
16124 (default-time
16125 ;; Default time is either today, or, when entering a range,
16126 ;; the range start.
16127 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16128 (save-excursion
16129 (re-search-backward
16130 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16131 (- (point) 20) t)))
16132 (apply 'encode-time (org-parse-time-string (match-string 1)))
16133 (current-time)))
16134 (default-input (and ts (org-get-compact-tod ts)))
16135 (repeater (save-excursion
16136 (save-match-data
16137 (beginning-of-line)
16138 (when (re-search-forward
16139 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16140 (save-excursion (progn (end-of-line) (point))) t)
16141 (match-string 0)))))
16142 org-time-was-given org-end-time-was-given time)
16143 (cond
16144 ((and (org-at-timestamp-p t)
16145 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16146 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16147 (insert "--")
16148 (setq time (let ((this-command this-command))
16149 (org-read-date arg 'totime nil nil
16150 default-time default-input inactive)))
16151 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16152 ((org-at-timestamp-p t)
16153 (setq time (let ((this-command this-command))
16154 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16155 (when (org-at-timestamp-p t) ; just to get the match data
16156 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16157 (replace-match "")
16158 (setq org-last-changed-timestamp
16159 (org-insert-time-stamp
16160 time (or org-time-was-given arg)
16161 inactive nil nil (list org-end-time-was-given)))
16162 (when repeater (goto-char (1- (point))) (insert " " repeater)
16163 (setq org-last-changed-timestamp
16164 (concat (substring org-last-inserted-timestamp 0 -1)
16165 " " repeater ">"))))
16166 (message "Timestamp updated"))
16167 ((equal arg '(16))
16168 (org-insert-time-stamp (current-time) t inactive))
16170 (setq time (let ((this-command this-command))
16171 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16172 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16173 nil nil (list org-end-time-was-given))))))
16175 ;; FIXME: can we use this for something else, like computing time differences?
16176 (defun org-get-compact-tod (s)
16177 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16178 (let* ((t1 (match-string 1 s))
16179 (h1 (string-to-number (match-string 2 s)))
16180 (m1 (string-to-number (match-string 3 s)))
16181 (t2 (and (match-end 4) (match-string 5 s)))
16182 (h2 (and t2 (string-to-number (match-string 6 s))))
16183 (m2 (and t2 (string-to-number (match-string 7 s))))
16184 dh dm)
16185 (if (not t2)
16187 (setq dh (- h2 h1) dm (- m2 m1))
16188 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16189 (concat t1 "+" (number-to-string dh)
16190 (and (/= 0 dm) (format ":%02d" dm)))))))
16192 (defun org-time-stamp-inactive (&optional arg)
16193 "Insert an inactive time stamp.
16194 An inactive time stamp is enclosed in square brackets instead of angle
16195 brackets. It is inactive in the sense that it does not trigger agenda entries,
16196 does not link to the calendar and cannot be changed with the S-cursor keys.
16197 So these are more for recording a certain time/date."
16198 (interactive "P")
16199 (org-time-stamp arg 'inactive))
16201 (defvar org-date-ovl (make-overlay 1 1))
16202 (overlay-put org-date-ovl 'face 'org-date-selected)
16203 (org-detach-overlay org-date-ovl)
16205 (defvar org-ans1) ; dynamically scoped parameter
16206 (defvar org-ans2) ; dynamically scoped parameter
16208 (defvar org-plain-time-of-day-regexp) ; defined below
16210 (defvar org-overriding-default-time nil) ; dynamically scoped
16211 (defvar org-read-date-overlay nil)
16212 (defvar org-dcst nil) ; dynamically scoped
16213 (defvar org-read-date-history nil)
16214 (defvar org-read-date-final-answer nil)
16215 (defvar org-read-date-analyze-futurep nil)
16216 (defvar org-read-date-analyze-forced-year nil)
16217 (defvar org-read-date-inactive)
16219 (defvar org-read-date-minibuffer-local-map
16220 (let* ((org-replace-disputed-keys nil)
16221 (map (make-sparse-keymap)))
16222 (set-keymap-parent map minibuffer-local-map)
16223 (org-defkey map (kbd ".")
16224 (lambda () (interactive)
16225 ;; Are we at the beginning of the prompt?
16226 (if (looking-back "^[^:]+: ")
16227 (org-eval-in-calendar '(calendar-goto-today))
16228 (insert "."))))
16229 (org-defkey map (kbd "C-.")
16230 (lambda () (interactive)
16231 (org-eval-in-calendar '(calendar-goto-today))))
16232 (org-defkey map [(meta shift left)]
16233 (lambda () (interactive)
16234 (org-eval-in-calendar '(calendar-backward-month 1))))
16235 (org-defkey map [(meta shift right)]
16236 (lambda () (interactive)
16237 (org-eval-in-calendar '(calendar-forward-month 1))))
16238 (org-defkey map [(meta shift up)]
16239 (lambda () (interactive)
16240 (org-eval-in-calendar '(calendar-backward-year 1))))
16241 (org-defkey map [(meta shift down)]
16242 (lambda () (interactive)
16243 (org-eval-in-calendar '(calendar-forward-year 1))))
16244 (org-defkey map [?\e (shift left)]
16245 (lambda () (interactive)
16246 (org-eval-in-calendar '(calendar-backward-month 1))))
16247 (org-defkey map [?\e (shift right)]
16248 (lambda () (interactive)
16249 (org-eval-in-calendar '(calendar-forward-month 1))))
16250 (org-defkey map [?\e (shift up)]
16251 (lambda () (interactive)
16252 (org-eval-in-calendar '(calendar-backward-year 1))))
16253 (org-defkey map [?\e (shift down)]
16254 (lambda () (interactive)
16255 (org-eval-in-calendar '(calendar-forward-year 1))))
16256 (org-defkey map [(shift up)]
16257 (lambda () (interactive)
16258 (org-eval-in-calendar '(calendar-backward-week 1))))
16259 (org-defkey map [(shift down)]
16260 (lambda () (interactive)
16261 (org-eval-in-calendar '(calendar-forward-week 1))))
16262 (org-defkey map [(shift left)]
16263 (lambda () (interactive)
16264 (org-eval-in-calendar '(calendar-backward-day 1))))
16265 (org-defkey map [(shift right)]
16266 (lambda () (interactive)
16267 (org-eval-in-calendar '(calendar-forward-day 1))))
16268 (org-defkey map "!"
16269 (lambda () (interactive)
16270 (org-eval-in-calendar '(diary-view-entries))
16271 (message "")))
16272 (org-defkey map ">"
16273 (lambda () (interactive)
16274 (org-eval-in-calendar '(scroll-calendar-left 1))))
16275 (org-defkey map "<"
16276 (lambda () (interactive)
16277 (org-eval-in-calendar '(scroll-calendar-right 1))))
16278 (org-defkey map "\C-v"
16279 (lambda () (interactive)
16280 (org-eval-in-calendar
16281 '(calendar-scroll-left-three-months 1))))
16282 (org-defkey map "\M-v"
16283 (lambda () (interactive)
16284 (org-eval-in-calendar
16285 '(calendar-scroll-right-three-months 1))))
16286 map)
16287 "Keymap for minibuffer commands when using `org-read-date'.")
16289 (defvar org-def)
16290 (defvar org-defdecode)
16291 (defvar org-with-time)
16293 (defun org-read-date (&optional org-with-time to-time from-string prompt
16294 default-time default-input inactive)
16295 "Read a date, possibly a time, and make things smooth for the user.
16296 The prompt will suggest to enter an ISO date, but you can also enter anything
16297 which will at least partially be understood by `parse-time-string'.
16298 Unrecognized parts of the date will default to the current day, month, year,
16299 hour and minute. If this command is called to replace a timestamp at point,
16300 or to enter the second timestamp of a range, the default time is taken
16301 from the existing stamp. Furthermore, the command prefers the future,
16302 so if you are giving a date where the year is not given, and the day-month
16303 combination is already past in the current year, it will assume you
16304 mean next year. For details, see the manual. A few examples:
16306 3-2-5 --> 2003-02-05
16307 feb 15 --> currentyear-02-15
16308 2/15 --> currentyear-02-15
16309 sep 12 9 --> 2009-09-12
16310 12:45 --> today 12:45
16311 22 sept 0:34 --> currentyear-09-22 0:34
16312 12 --> currentyear-currentmonth-12
16313 Fri --> nearest Friday after today
16314 -Tue --> last Tuesday
16315 etc.
16317 Furthermore you can specify a relative date by giving, as the *first* thing
16318 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16319 change in days weeks, months, years.
16320 With a single plus or minus, the date is relative to today. With a double
16321 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16322 +4d --> four days from today
16323 +4 --> same as above
16324 +2w --> two weeks from today
16325 ++5 --> five days from default date
16327 The function understands only English month and weekday abbreviations.
16329 While prompting, a calendar is popped up - you can also select the
16330 date with the mouse (button 1). The calendar shows a period of three
16331 months. To scroll it to other months, use the keys `>' and `<'.
16332 If you don't like the calendar, turn it off with
16333 \(setq org-read-date-popup-calendar nil)
16335 With optional argument TO-TIME, the date will immediately be converted
16336 to an internal time.
16337 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16338 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16339 still enter a time, and this function will inform the calling routine
16340 about this change. The calling routine may then choose to change the
16341 format used to insert the time stamp into the buffer to include the time.
16342 With optional argument FROM-STRING, read from this string instead from
16343 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16344 the time/date that is used for everything that is not specified by the
16345 user."
16346 (require 'parse-time)
16347 (let* ((org-time-stamp-rounding-minutes
16348 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16349 (org-dcst org-display-custom-times)
16350 (ct (org-current-time))
16351 (org-def (or org-overriding-default-time default-time ct))
16352 (org-defdecode (decode-time org-def))
16353 (dummy (progn
16354 (when (< (nth 2 org-defdecode) org-extend-today-until)
16355 (setcar (nthcdr 2 org-defdecode) -1)
16356 (setcar (nthcdr 1 org-defdecode) 59)
16357 (setq org-def (apply 'encode-time org-defdecode)
16358 org-defdecode (decode-time org-def)))))
16359 (mouse-autoselect-window nil) ; Don't let the mouse jump
16360 (calendar-frame-setup nil)
16361 (calendar-setup nil)
16362 (calendar-move-hook nil)
16363 (calendar-view-diary-initially-flag nil)
16364 (calendar-view-holidays-initially-flag nil)
16365 (timestr (format-time-string
16366 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16367 (prompt (concat (if prompt (concat prompt " ") "")
16368 (format "Date+time [%s]: " timestr)))
16369 ans (org-ans0 "") org-ans1 org-ans2 final)
16371 (cond
16372 (from-string (setq ans from-string))
16373 (org-read-date-popup-calendar
16374 (save-excursion
16375 (save-window-excursion
16376 (calendar)
16377 (org-eval-in-calendar '(setq cursor-type nil) t)
16378 (unwind-protect
16379 (progn
16380 (calendar-forward-day (- (time-to-days org-def)
16381 (calendar-absolute-from-gregorian
16382 (calendar-current-date))))
16383 (org-eval-in-calendar nil t)
16384 (let* ((old-map (current-local-map))
16385 (map (copy-keymap calendar-mode-map))
16386 (minibuffer-local-map
16387 (copy-keymap org-read-date-minibuffer-local-map)))
16388 (org-defkey map (kbd "RET") 'org-calendar-select)
16389 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16390 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16391 (unwind-protect
16392 (progn
16393 (use-local-map map)
16394 (setq org-read-date-inactive inactive)
16395 (add-hook 'post-command-hook 'org-read-date-display)
16396 (setq org-ans0 (read-string prompt default-input
16397 'org-read-date-history nil))
16398 ;; org-ans0: from prompt
16399 ;; org-ans1: from mouse click
16400 ;; org-ans2: from calendar motion
16401 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16402 (remove-hook 'post-command-hook 'org-read-date-display)
16403 (use-local-map old-map)
16404 (when org-read-date-overlay
16405 (delete-overlay org-read-date-overlay)
16406 (setq org-read-date-overlay nil)))))
16407 (bury-buffer "*Calendar*")))))
16409 (t ; Naked prompt only
16410 (unwind-protect
16411 (setq ans (read-string prompt default-input
16412 'org-read-date-history timestr))
16413 (when org-read-date-overlay
16414 (delete-overlay org-read-date-overlay)
16415 (setq org-read-date-overlay nil)))))
16417 (setq final (org-read-date-analyze ans org-def org-defdecode))
16419 (when org-read-date-analyze-forced-year
16420 (message "Year was forced into %s"
16421 (if org-read-date-force-compatible-dates
16422 "compatible range (1970-2037)"
16423 "range representable on this machine"))
16424 (ding))
16426 ;; One round trip to get rid of 34th of August and stuff like that....
16427 (setq final (decode-time (apply 'encode-time final)))
16429 (setq org-read-date-final-answer ans)
16431 (if to-time
16432 (apply 'encode-time final)
16433 (if (and (boundp 'org-time-was-given) org-time-was-given)
16434 (format "%04d-%02d-%02d %02d:%02d"
16435 (nth 5 final) (nth 4 final) (nth 3 final)
16436 (nth 2 final) (nth 1 final))
16437 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16439 (defun org-read-date-display ()
16440 "Display the current date prompt interpretation in the minibuffer."
16441 (when org-read-date-display-live
16442 (when org-read-date-overlay
16443 (delete-overlay org-read-date-overlay))
16444 (when (minibufferp (current-buffer))
16445 (save-excursion
16446 (end-of-line 1)
16447 (while (not (equal (buffer-substring
16448 (max (point-min) (- (point) 4)) (point))
16449 " "))
16450 (insert " ")))
16451 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16452 " " (or org-ans1 org-ans2)))
16453 (org-end-time-was-given nil)
16454 (f (org-read-date-analyze ans org-def org-defdecode))
16455 (fmts (if org-dcst
16456 org-time-stamp-custom-formats
16457 org-time-stamp-formats))
16458 (fmt (if (or org-with-time
16459 (and (boundp 'org-time-was-given) org-time-was-given))
16460 (cdr fmts)
16461 (car fmts)))
16462 (txt (format-time-string fmt (apply 'encode-time f)))
16463 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16464 (txt (concat "=> " txt)))
16465 (when (and org-end-time-was-given
16466 (string-match org-plain-time-of-day-regexp txt))
16467 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16468 org-end-time-was-given
16469 (substring txt (match-end 0)))))
16470 (when org-read-date-analyze-futurep
16471 (setq txt (concat txt " (=>F)")))
16472 (setq org-read-date-overlay
16473 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16474 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16476 (defun org-read-date-analyze (ans org-def org-defdecode)
16477 "Analyze the combined answer of the date prompt."
16478 ;; FIXME: cleanup and comment
16479 (let ((nowdecode (decode-time (current-time)))
16480 delta deltan deltaw deltadef year month day
16481 hour minute second wday pm h2 m2 tl wday1
16482 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16483 (setq org-read-date-analyze-futurep nil
16484 org-read-date-analyze-forced-year nil)
16485 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16486 (setq ans "+0"))
16488 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16489 (setq ans (replace-match "" t t ans)
16490 deltan (car delta)
16491 deltaw (nth 1 delta)
16492 deltadef (nth 2 delta)))
16494 ;; Check if there is an iso week date in there. If yes, store the
16495 ;; info and postpone interpreting it until the rest of the parsing
16496 ;; is done.
16497 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16498 (setq iso-year (if (match-end 1)
16499 (org-small-year-to-year
16500 (string-to-number (match-string 1 ans))))
16501 iso-weekday (if (match-end 3)
16502 (string-to-number (match-string 3 ans)))
16503 iso-week (string-to-number (match-string 2 ans)))
16504 (setq ans (replace-match "" t t ans)))
16506 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16507 (when (string-match
16508 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16509 (setq year (if (match-end 2)
16510 (string-to-number (match-string 2 ans))
16511 (progn (setq kill-year t)
16512 (string-to-number (format-time-string "%Y"))))
16513 month (string-to-number (match-string 3 ans))
16514 day (string-to-number (match-string 4 ans)))
16515 (if (< year 100) (setq year (+ 2000 year)))
16516 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16517 t nil ans)))
16519 ;; Help matching dotted european dates
16520 (when (string-match
16521 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16522 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16523 (setq kill-year t)
16524 (string-to-number (format-time-string "%Y")))
16525 day (string-to-number (match-string 1 ans))
16526 month (string-to-number (match-string 2 ans))
16527 ans (replace-match (format "%04d-%02d-%02d" year month day)
16528 t nil ans)))
16530 ;; Help matching american dates, like 5/30 or 5/30/7
16531 (when (string-match
16532 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16533 (setq year (if (match-end 4)
16534 (string-to-number (match-string 4 ans))
16535 (progn (setq kill-year t)
16536 (string-to-number (format-time-string "%Y"))))
16537 month (string-to-number (match-string 1 ans))
16538 day (string-to-number (match-string 2 ans)))
16539 (if (< year 100) (setq year (+ 2000 year)))
16540 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16541 t nil ans)))
16542 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16543 ;; If there is a time with am/pm, and *no* time without it, we convert
16544 ;; so that matching will be successful.
16545 (loop for i from 1 to 2 do ; twice, for end time as well
16546 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16547 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16548 (setq hour (string-to-number (match-string 1 ans))
16549 minute (if (match-end 3)
16550 (string-to-number (match-string 3 ans))
16552 pm (equal ?p
16553 (string-to-char (downcase (match-string 4 ans)))))
16554 (if (and (= hour 12) (not pm))
16555 (setq hour 0)
16556 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16557 (setq ans (replace-match (format "%02d:%02d" hour minute)
16558 t t ans))))
16560 ;; Check if a time range is given as a duration
16561 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16562 (setq hour (string-to-number (match-string 1 ans))
16563 h2 (+ hour (string-to-number (match-string 3 ans)))
16564 minute (string-to-number (match-string 2 ans))
16565 m2 (+ minute (if (match-end 5) (string-to-number
16566 (match-string 5 ans))0)))
16567 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16568 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16569 t t ans)))
16571 ;; Check if there is a time range
16572 (when (boundp 'org-end-time-was-given)
16573 (setq org-time-was-given nil)
16574 (when (and (string-match org-plain-time-of-day-regexp ans)
16575 (match-end 8))
16576 (setq org-end-time-was-given (match-string 8 ans))
16577 (setq ans (concat (substring ans 0 (match-beginning 7))
16578 (substring ans (match-end 7))))))
16580 (setq tl (parse-time-string ans)
16581 day (or (nth 3 tl) (nth 3 org-defdecode))
16582 month (or (nth 4 tl)
16583 (if (and org-read-date-prefer-future
16584 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16585 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16586 (nth 4 org-defdecode)))
16587 year (or (and (not kill-year) (nth 5 tl))
16588 (if (and org-read-date-prefer-future
16589 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16590 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16591 (nth 5 org-defdecode)))
16592 hour (or (nth 2 tl) (nth 2 org-defdecode))
16593 minute (or (nth 1 tl) (nth 1 org-defdecode))
16594 second (or (nth 0 tl) 0)
16595 wday (nth 6 tl))
16597 (when (and (eq org-read-date-prefer-future 'time)
16598 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16599 (equal day (nth 3 nowdecode))
16600 (equal month (nth 4 nowdecode))
16601 (equal year (nth 5 nowdecode))
16602 (nth 2 tl)
16603 (or (< (nth 2 tl) (nth 2 nowdecode))
16604 (and (= (nth 2 tl) (nth 2 nowdecode))
16605 (nth 1 tl)
16606 (< (nth 1 tl) (nth 1 nowdecode)))))
16607 (setq day (1+ day)
16608 futurep t))
16610 ;; Special date definitions below
16611 (cond
16612 (iso-week
16613 ;; There was an iso week
16614 (require 'cal-iso)
16615 (setq futurep nil)
16616 (setq year (or iso-year year)
16617 day (or iso-weekday wday 1)
16618 wday nil ; to make sure that the trigger below does not match
16619 iso-date (calendar-gregorian-from-absolute
16620 (calendar-absolute-from-iso
16621 (list iso-week day year))))
16622 ; FIXME: Should we also push ISO weeks into the future?
16623 ; (when (and org-read-date-prefer-future
16624 ; (not iso-year)
16625 ; (< (calendar-absolute-from-gregorian iso-date)
16626 ; (time-to-days (current-time))))
16627 ; (setq year (1+ year)
16628 ; iso-date (calendar-gregorian-from-absolute
16629 ; (calendar-absolute-from-iso
16630 ; (list iso-week day year)))))
16631 (setq month (car iso-date)
16632 year (nth 2 iso-date)
16633 day (nth 1 iso-date)))
16634 (deltan
16635 (setq futurep nil)
16636 (unless deltadef
16637 (let ((now (decode-time (current-time))))
16638 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16639 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16640 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16641 ((equal deltaw "m") (setq month (+ month deltan)))
16642 ((equal deltaw "y") (setq year (+ year deltan)))))
16643 ((and wday (not (nth 3 tl)))
16644 ;; Weekday was given, but no day, so pick that day in the week
16645 ;; on or after the derived date.
16646 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16647 (unless (equal wday wday1)
16648 (setq day (+ day (% (- wday wday1 -7) 7))))))
16649 (if (and (boundp 'org-time-was-given)
16650 (nth 2 tl))
16651 (setq org-time-was-given t))
16652 (if (< year 100) (setq year (+ 2000 year)))
16653 ;; Check of the date is representable
16654 (if org-read-date-force-compatible-dates
16655 (progn
16656 (if (< year 1970)
16657 (setq year 1970 org-read-date-analyze-forced-year t))
16658 (if (> year 2037)
16659 (setq year 2037 org-read-date-analyze-forced-year t)))
16660 (condition-case nil
16661 (ignore (encode-time second minute hour day month year))
16662 (error
16663 (setq year (nth 5 org-defdecode))
16664 (setq org-read-date-analyze-forced-year t))))
16665 (setq org-read-date-analyze-futurep futurep)
16666 (list second minute hour day month year)))
16668 (defvar parse-time-weekdays)
16669 (defun org-read-date-get-relative (s today default)
16670 "Check string S for special relative date string.
16671 TODAY and DEFAULT are internal times, for today and for a default.
16672 Return shift list (N what def-flag)
16673 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16674 N is the number of WHATs to shift.
16675 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16676 the DEFAULT date rather than TODAY."
16677 (require 'parse-time)
16678 (when (and
16679 (string-match
16680 (concat
16681 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16682 "\\([0-9]+\\)?"
16683 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16684 "\\([ \t]\\|$\\)") s)
16685 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16686 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16687 (string-to-char (substring (match-string 1 s) -1))
16688 ?+))
16689 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16690 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16691 (what (if (match-end 3) (match-string 3 s) "d"))
16692 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16693 (date (if rel default today))
16694 (wday (nth 6 (decode-time date)))
16695 delta)
16696 (if wday1
16697 (progn
16698 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16699 (if (= delta 0) (setq delta 7))
16700 (if (= dir ?-)
16701 (progn
16702 (setq delta (- delta 7))
16703 (if (= delta 0) (setq delta -7))))
16704 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16705 (list delta "d" rel))
16706 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16708 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16709 "Turn a user-specified date into the internal representation.
16710 The internal representation needed by the calendar is (month day year).
16711 This is a wrapper to handle the brain-dead convention in calendar that
16712 user function argument order change dependent on argument order."
16713 (if (boundp 'calendar-date-style)
16714 (cond
16715 ((eq calendar-date-style 'american)
16716 (list arg1 arg2 arg3))
16717 ((eq calendar-date-style 'european)
16718 (list arg2 arg1 arg3))
16719 ((eq calendar-date-style 'iso)
16720 (list arg2 arg3 arg1)))
16721 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16722 (if (org-bound-and-true-p european-calendar-style)
16723 (list arg2 arg1 arg3)
16724 (list arg1 arg2 arg3)))))
16726 (defun org-eval-in-calendar (form &optional keepdate)
16727 "Eval FORM in the calendar window and return to current window.
16728 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16729 otherwise stick to the current value of `org-ans2'."
16730 (let ((sf (selected-frame))
16731 (sw (selected-window)))
16732 (select-window (get-buffer-window "*Calendar*" t))
16733 (eval form)
16734 (when (and (not keepdate) (calendar-cursor-to-date))
16735 (let* ((date (calendar-cursor-to-date))
16736 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16737 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16738 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16739 (select-window sw)
16740 (org-select-frame-set-input-focus sf)))
16742 (defun org-calendar-select ()
16743 "Return to `org-read-date' with the date currently selected.
16744 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16745 (interactive)
16746 (when (calendar-cursor-to-date)
16747 (let* ((date (calendar-cursor-to-date))
16748 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16749 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16750 (if (active-minibuffer-window) (exit-minibuffer))))
16752 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16753 "Insert a date stamp for the date given by the internal TIME.
16754 WITH-HM means use the stamp format that includes the time of the day.
16755 INACTIVE means use square brackets instead of angular ones, so that the
16756 stamp will not contribute to the agenda.
16757 PRE and POST are optional strings to be inserted before and after the
16758 stamp.
16759 The command returns the inserted time stamp."
16760 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16761 stamp)
16762 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16763 (insert-before-markers (or pre ""))
16764 (when (listp extra)
16765 (setq extra (car extra))
16766 (if (and (stringp extra)
16767 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16768 (setq extra (format "-%02d:%02d"
16769 (string-to-number (match-string 1 extra))
16770 (string-to-number (match-string 2 extra))))
16771 (setq extra nil)))
16772 (when extra
16773 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16774 (insert-before-markers (setq stamp (format-time-string fmt time)))
16775 (insert-before-markers (or post ""))
16776 (setq org-last-inserted-timestamp stamp)))
16778 (defun org-toggle-time-stamp-overlays ()
16779 "Toggle the use of custom time stamp formats."
16780 (interactive)
16781 (setq org-display-custom-times (not org-display-custom-times))
16782 (unless org-display-custom-times
16783 (let ((p (point-min)) (bmp (buffer-modified-p)))
16784 (while (setq p (next-single-property-change p 'display))
16785 (if (and (get-text-property p 'display)
16786 (eq (get-text-property p 'face) 'org-date))
16787 (remove-text-properties
16788 p (setq p (next-single-property-change p 'display))
16789 '(display t))))
16790 (set-buffer-modified-p bmp)))
16791 (if (featurep 'xemacs)
16792 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16793 (org-restart-font-lock)
16794 (setq org-table-may-need-update t)
16795 (if org-display-custom-times
16796 (message "Time stamps are overlaid with custom format")
16797 (message "Time stamp overlays removed")))
16799 (defun org-display-custom-time (beg end)
16800 "Overlay modified time stamp format over timestamp between BEG and END."
16801 (let* ((ts (buffer-substring beg end))
16802 t1 w1 with-hm tf time str w2 (off 0))
16803 (save-match-data
16804 (setq t1 (org-parse-time-string ts t))
16805 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16806 (setq off (- (match-end 0) (match-beginning 0)))))
16807 (setq end (- end off))
16808 (setq w1 (- end beg)
16809 with-hm (and (nth 1 t1) (nth 2 t1))
16810 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16811 time (org-fix-decoded-time t1)
16812 str (org-add-props
16813 (format-time-string
16814 (substring tf 1 -1) (apply 'encode-time time))
16815 nil 'mouse-face 'highlight)
16816 w2 (length str))
16817 (if (not (= w2 w1))
16818 (add-text-properties (1+ beg) (+ 2 beg)
16819 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16820 (if (featurep 'xemacs)
16821 (progn
16822 (put-text-property beg end 'invisible t)
16823 (put-text-property beg end 'end-glyph (make-glyph str)))
16824 (put-text-property beg end 'display str))))
16826 (defun org-translate-time (string)
16827 "Translate all timestamps in STRING to custom format.
16828 But do this only if the variable `org-display-custom-times' is set."
16829 (when org-display-custom-times
16830 (save-match-data
16831 (let* ((start 0)
16832 (re org-ts-regexp-both)
16833 t1 with-hm inactive tf time str beg end)
16834 (while (setq start (string-match re string start))
16835 (setq beg (match-beginning 0)
16836 end (match-end 0)
16837 t1 (save-match-data
16838 (org-parse-time-string (substring string beg end) t))
16839 with-hm (and (nth 1 t1) (nth 2 t1))
16840 inactive (equal (substring string beg (1+ beg)) "[")
16841 tf (funcall (if with-hm 'cdr 'car)
16842 org-time-stamp-custom-formats)
16843 time (org-fix-decoded-time t1)
16844 str (format-time-string
16845 (concat
16846 (if inactive "[" "<") (substring tf 1 -1)
16847 (if inactive "]" ">"))
16848 (apply 'encode-time time))
16849 string (replace-match str t t string)
16850 start (+ start (length str)))))))
16851 string)
16853 (defun org-fix-decoded-time (time)
16854 "Set 0 instead of nil for the first 6 elements of time.
16855 Don't touch the rest."
16856 (let ((n 0))
16857 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16859 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16861 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16862 "Difference between TIMESTAMP-STRING and now in days.
16863 If SECONDS is non-nil, return the difference in seconds."
16864 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16865 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16866 (funcall fdiff (current-time)))))
16868 (defun org-deadline-close (timestamp-string &optional ndays)
16869 "Is the time in TIMESTAMP-STRING close to the current date?"
16870 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16871 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16872 (not (org-entry-is-done-p))))
16874 (defun org-get-wdays (ts &optional delay zero-delay)
16875 "Get the deadline lead time appropriate for timestring TS.
16876 When DELAY is non-nil, get the delay time for scheduled items
16877 instead of the deadline lead time. When ZERO-DELAY is non-nil
16878 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16879 don't try to find the delay cookie in the scheduled timestamp."
16880 (let ((tv (if delay org-scheduled-delay-days
16881 org-deadline-warning-days)))
16882 (cond
16883 ((or (and delay (< tv 0))
16884 (and delay zero-delay (<= tv 0))
16885 (and (not delay) (<= tv 0)))
16886 ;; Enforce this value no matter what
16887 (- tv))
16888 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16889 ;; lead time is specified.
16890 (floor (* (string-to-number (match-string 1 ts))
16891 (cdr (assoc (match-string 2 ts)
16892 '(("d" . 1) ("w" . 7)
16893 ("m" . 30.4) ("y" . 365.25)
16894 ("h" . 0.041667)))))))
16895 ;; go for the default.
16896 (t tv))))
16898 (defun org-calendar-select-mouse (ev)
16899 "Return to `org-read-date' with the date currently selected.
16900 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16901 (interactive "e")
16902 (mouse-set-point ev)
16903 (when (calendar-cursor-to-date)
16904 (let* ((date (calendar-cursor-to-date))
16905 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16906 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16907 (if (active-minibuffer-window) (exit-minibuffer))))
16909 (defun org-check-deadlines (ndays)
16910 "Check if there are any deadlines due or past due.
16911 A deadline is considered due if it happens within `org-deadline-warning-days'
16912 days from today's date. If the deadline appears in an entry marked DONE,
16913 it is not shown. The prefix arg NDAYS can be used to test that many
16914 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16915 (interactive "P")
16916 (let* ((org-warn-days
16917 (cond
16918 ((equal ndays '(4)) 100000)
16919 (ndays (prefix-numeric-value ndays))
16920 (t (abs org-deadline-warning-days))))
16921 (case-fold-search nil)
16922 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16923 (callback
16924 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16926 (message "%d deadlines past-due or due within %d days"
16927 (org-occur regexp nil callback)
16928 org-warn-days)))
16930 (defsubst org-re-timestamp (type)
16931 "Return a regexp for timestamp TYPE.
16932 Allowed values for TYPE are:
16934 all: all timestamps
16935 active: only active timestamps (<...>)
16936 inactive: only inactive timestamps ([...])
16937 scheduled: only scheduled timestamps
16938 deadline: only deadline timestamps
16939 closed: only closed time-stamps
16941 When TYPE is nil, fall back on returning a regexp that matches
16942 both scheduled and deadline timestamps."
16943 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16944 ((eq type 'active) org-ts-regexp)
16945 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16946 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16947 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16948 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
16949 ((eq type 'scheduled-or-deadline)
16950 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16952 (defun org-check-before-date (date)
16953 "Check if there are deadlines or scheduled entries before DATE."
16954 (interactive (list (org-read-date)))
16955 (let ((case-fold-search nil)
16956 (regexp (org-re-timestamp org-ts-type))
16957 (callback
16958 (lambda () (time-less-p
16959 (org-time-string-to-time (match-string 1))
16960 (org-time-string-to-time date)))))
16961 (message "%d entries before %s"
16962 (org-occur regexp nil callback) date)))
16964 (defun org-check-after-date (date)
16965 "Check if there are deadlines or scheduled entries after DATE."
16966 (interactive (list (org-read-date)))
16967 (let ((case-fold-search nil)
16968 (regexp (org-re-timestamp org-ts-type))
16969 (callback
16970 (lambda () (not
16971 (time-less-p
16972 (org-time-string-to-time (match-string 1))
16973 (org-time-string-to-time date))))))
16974 (message "%d entries after %s"
16975 (org-occur regexp nil callback) date)))
16977 (defun org-check-dates-range (start-date end-date)
16978 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16979 (interactive (list (org-read-date nil nil nil "Range starts")
16980 (org-read-date nil nil nil "Range end")))
16981 (let ((case-fold-search nil)
16982 (regexp (org-re-timestamp org-ts-type))
16983 (callback
16984 (lambda ()
16985 (let ((match (match-string 1)))
16986 (and
16987 (not (time-less-p
16988 (org-time-string-to-time match)
16989 (org-time-string-to-time start-date)))
16990 (time-less-p
16991 (org-time-string-to-time match)
16992 (org-time-string-to-time end-date)))))))
16993 (message "%d entries between %s and %s"
16994 (org-occur regexp nil callback) start-date end-date)))
16996 (defun org-evaluate-time-range (&optional to-buffer)
16997 "Evaluate a time range by computing the difference between start and end.
16998 Normally the result is just printed in the echo area, but with prefix arg
16999 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17000 If the time range is actually in a table, the result is inserted into the
17001 next column.
17002 For time difference computation, a year is assumed to be exactly 365
17003 days in order to avoid rounding problems."
17004 (interactive "P")
17006 (org-clock-update-time-maybe)
17007 (save-excursion
17008 (unless (org-at-date-range-p t)
17009 (goto-char (point-at-bol))
17010 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17011 (if (not (org-at-date-range-p t))
17012 (user-error "Not at a time-stamp range, and none found in current line")))
17013 (let* ((ts1 (match-string 1))
17014 (ts2 (match-string 2))
17015 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17016 (match-end (match-end 0))
17017 (time1 (org-time-string-to-time ts1))
17018 (time2 (org-time-string-to-time ts2))
17019 (t1 (org-float-time time1))
17020 (t2 (org-float-time time2))
17021 (diff (abs (- t2 t1)))
17022 (negative (< (- t2 t1) 0))
17023 ;; (ys (floor (* 365 24 60 60)))
17024 (ds (* 24 60 60))
17025 (hs (* 60 60))
17026 (fy "%dy %dd %02d:%02d")
17027 (fy1 "%dy %dd")
17028 (fd "%dd %02d:%02d")
17029 (fd1 "%dd")
17030 (fh "%02d:%02d")
17031 y d h m align)
17032 (if havetime
17033 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17035 d (floor (/ diff ds)) diff (mod diff ds)
17036 h (floor (/ diff hs)) diff (mod diff hs)
17037 m (floor (/ diff 60)))
17038 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17040 d (floor (+ (/ diff ds) 0.5))
17041 h 0 m 0))
17042 (if (not to-buffer)
17043 (message "%s" (org-make-tdiff-string y d h m))
17044 (if (org-at-table-p)
17045 (progn
17046 (goto-char match-end)
17047 (setq align t)
17048 (and (looking-at " *|") (goto-char (match-end 0))))
17049 (goto-char match-end))
17050 (if (looking-at
17051 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17052 (replace-match ""))
17053 (if negative (insert " -"))
17054 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17055 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17056 (insert " " (format fh h m))))
17057 (if align (org-table-align))
17058 (message "Time difference inserted")))))
17060 (defun org-make-tdiff-string (y d h m)
17061 (let ((fmt "")
17062 (l nil))
17063 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
17064 l (push y l)))
17065 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
17066 l (push d l)))
17067 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
17068 l (push h l)))
17069 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
17070 l (push m l)))
17071 (apply 'format fmt (nreverse l))))
17073 (defun org-time-string-to-time (s &optional buffer pos)
17074 "Convert a timestamp string into internal time."
17075 (condition-case errdata
17076 (apply 'encode-time (org-parse-time-string s))
17077 (error (error "Bad timestamp `%s'%s\nError was: %s"
17078 s (if (not (and buffer pos))
17080 (format " at %d in buffer `%s'" pos buffer))
17081 (cdr errdata)))))
17083 (defun org-time-string-to-seconds (s)
17084 "Convert a timestamp string to a number of seconds."
17085 (org-float-time (org-time-string-to-time s)))
17087 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17088 "Convert a time stamp to an absolute day number.
17089 If there is a specifier for a cyclic time stamp, get the closest
17090 date to DAYNR.
17091 PREFER and SHOW-ALL are passed through to `org-closest-date'.
17092 The variable `date' is bound by the calendar when this is called."
17093 (cond
17094 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17095 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17096 daynr
17097 (+ daynr 1000)))
17098 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
17099 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17100 (time-to-days (current-time))) (match-string 0 s)
17101 prefer show-all))
17102 (t (time-to-days
17103 (condition-case errdata
17104 (apply 'encode-time (org-parse-time-string s))
17105 (error (error "Bad timestamp `%s'%s\nError was: %s"
17106 s (if (not (and buffer pos))
17108 (format " at %d in buffer `%s'" pos buffer))
17109 (cdr errdata))))))))
17111 (defun org-days-to-iso-week (days)
17112 "Return the iso week number."
17113 (require 'cal-iso)
17114 (car (calendar-iso-from-absolute days)))
17116 (defun org-small-year-to-year (year)
17117 "Convert 2-digit years into 4-digit years.
17118 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
17119 The year 2000 cannot be abbreviated. Any year larger than 99
17120 is returned unchanged."
17121 (if (< year 38)
17122 (setq year (+ 2000 year))
17123 (if (< year 100)
17124 (setq year (+ 1900 year))))
17125 year)
17127 (defun org-time-from-absolute (d)
17128 "Return the time corresponding to date D.
17129 D may be an absolute day number, or a calendar-type list (month day year)."
17130 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17131 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17133 (defun org-calendar-holiday ()
17134 "List of holidays, for Diary display in Org-mode."
17135 (require 'holidays)
17136 (let ((hl (funcall
17137 (if (fboundp 'calendar-check-holidays)
17138 'calendar-check-holidays 'check-calendar-holidays) date)))
17139 (if hl (mapconcat 'identity hl "; "))))
17141 (defun org-diary-sexp-entry (sexp entry date)
17142 "Process a SEXP diary ENTRY for DATE."
17143 (require 'diary-lib)
17144 (let ((result (if calendar-debug-sexp
17145 (let ((stack-trace-on-error t))
17146 (eval (car (read-from-string sexp))))
17147 (condition-case nil
17148 (eval (car (read-from-string sexp)))
17149 (error
17150 (beep)
17151 (message "Bad sexp at line %d in %s: %s"
17152 (org-current-line)
17153 (buffer-file-name) sexp)
17154 (sleep-for 2))))))
17155 (cond ((stringp result) (split-string result "; "))
17156 ((and (consp result)
17157 (not (consp (cdr result)))
17158 (stringp (cdr result))) (cdr result))
17159 ((and (consp result)
17160 (stringp (car result))) result)
17161 (result entry))))
17163 (defun org-diary-to-ical-string (frombuf)
17164 "Get iCalendar entries from diary entries in buffer FROMBUF.
17165 This uses the icalendar.el library."
17166 (let* ((tmpdir (if (featurep 'xemacs)
17167 (temp-directory)
17168 temporary-file-directory))
17169 (tmpfile (make-temp-name
17170 (expand-file-name "orgics" tmpdir)))
17171 buf rtn b e)
17172 (with-current-buffer frombuf
17173 (icalendar-export-region (point-min) (point-max) tmpfile)
17174 (setq buf (find-buffer-visiting tmpfile))
17175 (set-buffer buf)
17176 (goto-char (point-min))
17177 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17178 (setq b (match-beginning 0)))
17179 (goto-char (point-max))
17180 (if (re-search-backward "^END:VEVENT" nil t)
17181 (setq e (match-end 0)))
17182 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17183 (kill-buffer buf)
17184 (delete-file tmpfile)
17185 rtn))
17187 (defun org-closest-date (start current change prefer show-all)
17188 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17189 When PREFER is `past', return a date that is either CURRENT or past.
17190 When PREFER is `future', return a date that is either CURRENT or future.
17191 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17192 ;; Make the proper lists from the dates
17193 (catch 'exit
17194 (let ((a1 '(("h" . hour)
17195 ("d" . day)
17196 ("w" . week)
17197 ("m" . month)
17198 ("y" . year)))
17199 (shour (nth 2 (org-parse-time-string start)))
17200 dn dw sday cday n1 n2 n0
17201 d m y y1 y2 date1 date2 nmonths nm ny m2)
17203 (setq start (org-date-to-gregorian start)
17204 current (org-date-to-gregorian
17205 (if show-all
17206 current
17207 (time-to-days (current-time))))
17208 sday (calendar-absolute-from-gregorian start)
17209 cday (calendar-absolute-from-gregorian current))
17211 (if (<= cday sday) (throw 'exit sday))
17213 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17214 (setq dn (string-to-number (match-string 1 change))
17215 dw (cdr (assoc (match-string 2 change) a1)))
17216 (user-error "Invalid change specifier: %s" change))
17217 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17218 (cond
17219 ((eq dw 'hour)
17220 (let ((missing-hours
17221 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17222 dn)))
17223 (setq n1 (if (zerop missing-hours) cday
17224 (- cday (1+ (floor (/ missing-hours 24)))))
17225 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17226 ((eq dw 'day)
17227 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17228 n2 (+ n1 dn)))
17229 ((eq dw 'year)
17230 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17231 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17232 (setq date1 (list m d y1)
17233 n1 (calendar-absolute-from-gregorian date1)
17234 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17235 n2 (calendar-absolute-from-gregorian date2)))
17236 ((eq dw 'month)
17237 ;; approx number of month between the two dates
17238 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17239 ;; How often does dn fit in there?
17240 (setq d (nth 1 start) m (car start) y (nth 2 start)
17241 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17242 m (+ m nm)
17243 ny (floor (/ m 12))
17244 y (+ y ny)
17245 m (- m (* ny 12)))
17246 (while (> m 12) (setq m (- m 12) y (1+ y)))
17247 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17248 (setq m2 (+ m dn) y2 y)
17249 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17250 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17251 (while (<= n2 cday)
17252 (setq n1 n2 m m2 y y2)
17253 (setq m2 (+ m dn) y2 y)
17254 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17255 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17256 ;; Make sure n1 is the earlier date
17257 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17258 (if show-all
17259 (cond
17260 ((eq prefer 'past) (if (= cday n2) n2 n1))
17261 ((eq prefer 'future) (if (= cday n1) n1 n2))
17262 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17263 (cond
17264 ((eq prefer 'past) (if (= cday n2) n2 n1))
17265 ((eq prefer 'future) (if (= cday n1) n1 n2))
17266 (t (if (= cday n1) n1 n2)))))))
17268 (defun org-date-to-gregorian (date)
17269 "Turn any specification of DATE into a Gregorian date for the calendar."
17270 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17271 ((and (listp date) (= (length date) 3)) date)
17272 ((stringp date)
17273 (setq date (org-parse-time-string date))
17274 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17275 ((listp date)
17276 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17278 (defun org-parse-time-string (s &optional nodefault)
17279 "Parse the standard Org-mode time string.
17280 This should be a lot faster than the normal `parse-time-string'.
17281 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17282 hour and minute fields will be nil if not given."
17283 (cond ((string-match org-ts-regexp0 s)
17284 (list 0
17285 (if (or (match-beginning 8) (not nodefault))
17286 (string-to-number (or (match-string 8 s) "0")))
17287 (if (or (match-beginning 7) (not nodefault))
17288 (string-to-number (or (match-string 7 s) "0")))
17289 (string-to-number (match-string 4 s))
17290 (string-to-number (match-string 3 s))
17291 (string-to-number (match-string 2 s))
17292 nil nil nil))
17293 ((string-match "^<[^>]+>$" s)
17294 (decode-time (seconds-to-time (org-matcher-time s))))
17295 (t (error "Not a standard Org-mode time string: %s" s))))
17297 (defun org-timestamp-up (&optional arg)
17298 "Increase the date item at the cursor by one.
17299 If the cursor is on the year, change the year. If it is on the month,
17300 the day or the time, change that.
17301 With prefix ARG, change by that many units."
17302 (interactive "p")
17303 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17305 (defun org-timestamp-down (&optional arg)
17306 "Decrease the date item at the cursor by one.
17307 If the cursor is on the year, change the year. If it is on the month,
17308 the day or the time, change that.
17309 With prefix ARG, change by that many units."
17310 (interactive "p")
17311 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17313 (defun org-timestamp-up-day (&optional arg)
17314 "Increase the date in the time stamp by one day.
17315 With prefix ARG, change that many days."
17316 (interactive "p")
17317 (if (and (not (org-at-timestamp-p t))
17318 (org-at-heading-p))
17319 (org-todo 'up)
17320 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17322 (defun org-timestamp-down-day (&optional arg)
17323 "Decrease the date in the time stamp by one day.
17324 With prefix ARG, change that many days."
17325 (interactive "p")
17326 (if (and (not (org-at-timestamp-p t))
17327 (org-at-heading-p))
17328 (org-todo 'down)
17329 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17331 (defun org-at-timestamp-p (&optional inactive-ok)
17332 "Determine if the cursor is in or at a timestamp."
17333 (interactive)
17334 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17335 (pos (point))
17336 (ans (or (looking-at tsr)
17337 (save-excursion
17338 (skip-chars-backward "^[<\n\r\t")
17339 (if (> (point) (point-min)) (backward-char 1))
17340 (and (looking-at tsr)
17341 (> (- (match-end 0) pos) -1))))))
17342 (and ans
17343 (boundp 'org-ts-what)
17344 (setq org-ts-what
17345 (cond
17346 ((= pos (match-beginning 0)) 'bracket)
17347 ;; Point is considered to be "on the bracket" whether
17348 ;; it's really on it or right after it.
17349 ((= pos (1- (match-end 0))) 'bracket)
17350 ((= pos (match-end 0)) 'after)
17351 ((org-pos-in-match-range pos 2) 'year)
17352 ((org-pos-in-match-range pos 3) 'month)
17353 ((org-pos-in-match-range pos 7) 'hour)
17354 ((org-pos-in-match-range pos 8) 'minute)
17355 ((or (org-pos-in-match-range pos 4)
17356 (org-pos-in-match-range pos 5)) 'day)
17357 ((and (> pos (or (match-end 8) (match-end 5)))
17358 (< pos (match-end 0)))
17359 (- pos (or (match-end 8) (match-end 5))))
17360 (t 'day))))
17361 ans))
17363 (defun org-toggle-timestamp-type ()
17364 "Toggle the type (<active> or [inactive]) of a time stamp."
17365 (interactive)
17366 (when (org-at-timestamp-p t)
17367 (let ((beg (match-beginning 0)) (end (match-end 0))
17368 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17369 (save-excursion
17370 (goto-char beg)
17371 (while (re-search-forward "[][<>]" end t)
17372 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17373 t t)))
17374 (message "Timestamp is now %sactive"
17375 (if (equal (char-after beg) ?<) "" "in")))))
17377 (defun org-at-clock-log-p nil
17378 "Is the cursor on the clock log line?"
17379 (save-excursion
17380 (move-beginning-of-line 1)
17381 (looking-at "^[ \t]*CLOCK:")))
17383 (defvar org-clock-history) ; defined in org-clock.el
17384 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17385 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17386 "Change the date in the time stamp at point.
17387 The date will be changed by N times WHAT. WHAT can be `day', `month',
17388 `year', `minute', `second'. If WHAT is not given, the cursor position
17389 in the timestamp determines what will be changed.
17390 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17391 (let ((origin (point)) origin-cat
17392 with-hm inactive
17393 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17394 org-ts-what
17395 extra rem
17396 ts time time0 fixnext clrgx)
17397 (if (not (org-at-timestamp-p t))
17398 (user-error "Not at a timestamp"))
17399 (if (and (not what) (eq org-ts-what 'bracket))
17400 (org-toggle-timestamp-type)
17401 ;; Point isn't on brackets. Remember the part of the time-stamp
17402 ;; the point was in. Indeed, size of time-stamps may change,
17403 ;; but point must be kept in the same category nonetheless.
17404 (setq origin-cat org-ts-what)
17405 (if (and (not what) (not (eq org-ts-what 'day))
17406 org-display-custom-times
17407 (get-text-property (point) 'display)
17408 (not (get-text-property (1- (point)) 'display)))
17409 (setq org-ts-what 'day))
17410 (setq org-ts-what (or what org-ts-what)
17411 inactive (= (char-after (match-beginning 0)) ?\[)
17412 ts (match-string 0))
17413 (replace-match "")
17414 (when (string-match
17415 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17417 (setq extra (match-string 1 ts))
17418 (if suppress-tmp-delay
17419 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17420 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17421 (setq with-hm t))
17422 (setq time0 (org-parse-time-string ts))
17423 (when (and updown
17424 (eq org-ts-what 'minute)
17425 (not current-prefix-arg))
17426 ;; This looks like s-up and s-down. Change by one rounding step.
17427 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17428 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17429 (setcar (cdr time0) (+ (nth 1 time0)
17430 (if (> n 0) (- rem) (- dm rem))))))
17431 (setq time
17432 (encode-time (or (car time0) 0)
17433 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17434 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17435 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17436 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17437 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17438 (nthcdr 6 time0)))
17439 (when (and (member org-ts-what '(hour minute))
17440 extra
17441 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17442 (setq extra (org-modify-ts-extra
17443 extra
17444 (if (eq org-ts-what 'hour) 2 5)
17445 n dm)))
17446 (when (integerp org-ts-what)
17447 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17448 (if (eq what 'calendar)
17449 (let ((cal-date (org-get-date-from-calendar)))
17450 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17451 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17452 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17453 (setcar time0 (or (car time0) 0))
17454 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17455 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17456 (setq time (apply 'encode-time time0))))
17457 ;; Insert the new time-stamp, and ensure point stays in the same
17458 ;; category as before (i.e. not after the last position in that
17459 ;; category).
17460 (let ((pos (point)))
17461 ;; Stay before inserted string. `save-excursion' is of no use.
17462 (setq org-last-changed-timestamp
17463 (org-insert-time-stamp time with-hm inactive nil nil extra))
17464 (goto-char pos))
17465 (save-match-data
17466 (looking-at org-ts-regexp3)
17467 (goto-char (cond
17468 ;; `day' category ends before `hour' if any, or at
17469 ;; the end of the day name.
17470 ((eq origin-cat 'day)
17471 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17472 ((eq origin-cat 'hour) (min (match-end 7) origin))
17473 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17474 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17475 ;; `year' and `month' have both fixed size: point
17476 ;; couldn't have moved into another part.
17477 (t origin))))
17478 ;; Update clock if on a CLOCK line.
17479 (org-clock-update-time-maybe)
17480 ;; Maybe adjust the closest clock in `org-clock-history'
17481 (when org-clock-adjust-closest
17482 (if (not (and (org-at-clock-log-p)
17483 (< 1 (length (delq nil (mapcar 'marker-position
17484 org-clock-history))))))
17485 (message "No clock to adjust")
17486 (cond ((save-excursion ; fix previous clock?
17487 (re-search-backward org-ts-regexp0 nil t)
17488 (org-looking-back (concat org-clock-string " \\[")))
17489 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17490 ((save-excursion ; fix next clock?
17491 (re-search-backward org-ts-regexp0 nil t)
17492 (looking-at (concat org-ts-regexp0 "\\] =>")))
17493 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17494 (save-window-excursion
17495 ;; Find closest clock to point, adjust the previous/next one in history
17496 (let* ((p (save-excursion (org-back-to-heading t)))
17497 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17498 (clfixnth
17499 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17500 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17501 (if (not clfixpos)
17502 (message "No clock to adjust")
17503 (save-excursion
17504 (org-goto-marker-or-bmk clfixpos)
17505 (org-show-subtree)
17506 (when (re-search-forward clrgx nil t)
17507 (goto-char (match-beginning 1))
17508 (let (org-clock-adjust-closest)
17509 (org-timestamp-change n org-ts-what updown))
17510 (message "Clock adjusted in %s for heading: %s"
17511 (file-name-nondirectory (buffer-file-name))
17512 (org-get-heading t t)))))))))
17513 ;; Try to recenter the calendar window, if any.
17514 (if (and org-calendar-follow-timestamp-change
17515 (get-buffer-window "*Calendar*" t)
17516 (memq org-ts-what '(day month year)))
17517 (org-recenter-calendar (time-to-days time))))))
17519 (defun org-modify-ts-extra (s pos n dm)
17520 "Change the different parts of the lead-time and repeat fields in timestamp."
17521 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17522 ng h m new rem)
17523 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17524 (cond
17525 ((or (org-pos-in-match-range pos 2)
17526 (org-pos-in-match-range pos 3))
17527 (setq m (string-to-number (match-string 3 s))
17528 h (string-to-number (match-string 2 s)))
17529 (if (org-pos-in-match-range pos 2)
17530 (setq h (+ h n))
17531 (setq n (* dm (org-no-warnings (signum n))))
17532 (when (not (= 0 (setq rem (% m dm))))
17533 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17534 (setq m (+ m n)))
17535 (if (< m 0) (setq m (+ m 60) h (1- h)))
17536 (if (> m 59) (setq m (- m 60) h (1+ h)))
17537 (setq h (min 24 (max 0 h)))
17538 (setq ng 1 new (format "-%02d:%02d" h m)))
17539 ((org-pos-in-match-range pos 6)
17540 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17541 ((org-pos-in-match-range pos 5)
17542 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17544 ((org-pos-in-match-range pos 9)
17545 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17546 ((org-pos-in-match-range pos 8)
17547 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17549 (when ng
17550 (setq s (concat
17551 (substring s 0 (match-beginning ng))
17553 (substring s (match-end ng))))))
17556 (defun org-recenter-calendar (date)
17557 "If the calendar is visible, recenter it to DATE."
17558 (let ((cwin (get-buffer-window "*Calendar*" t)))
17559 (when cwin
17560 (let ((calendar-move-hook nil))
17561 (with-selected-window cwin
17562 (calendar-goto-date (if (listp date) date
17563 (calendar-gregorian-from-absolute date))))))))
17565 (defun org-goto-calendar (&optional arg)
17566 "Go to the Emacs calendar at the current date.
17567 If there is a time stamp in the current line, go to that date.
17568 A prefix ARG can be used to force the current date."
17569 (interactive "P")
17570 (let ((tsr org-ts-regexp) diff
17571 (calendar-move-hook nil)
17572 (calendar-view-holidays-initially-flag nil)
17573 (calendar-view-diary-initially-flag nil))
17574 (if (or (org-at-timestamp-p)
17575 (save-excursion
17576 (beginning-of-line 1)
17577 (looking-at (concat ".*" tsr))))
17578 (let ((d1 (time-to-days (current-time)))
17579 (d2 (time-to-days
17580 (org-time-string-to-time (match-string 1)))))
17581 (setq diff (- d2 d1))))
17582 (calendar)
17583 (calendar-goto-today)
17584 (if (and diff (not arg)) (calendar-forward-day diff))))
17586 (defun org-get-date-from-calendar ()
17587 "Return a list (month day year) of date at point in calendar."
17588 (with-current-buffer "*Calendar*"
17589 (save-match-data
17590 (calendar-cursor-to-date))))
17592 (defun org-date-from-calendar ()
17593 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17594 If there is already a time stamp at the cursor position, update it."
17595 (interactive)
17596 (if (org-at-timestamp-p t)
17597 (org-timestamp-change 0 'calendar)
17598 (let ((cal-date (org-get-date-from-calendar)))
17599 (org-insert-time-stamp
17600 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17602 (defcustom org-effort-durations
17603 `(("h" . 60)
17604 ("d" . ,(* 60 8))
17605 ("w" . ,(* 60 8 5))
17606 ("m" . ,(* 60 8 5 4))
17607 ("y" . ,(* 60 8 5 40)))
17608 "Conversion factor to minutes for an effort modifier.
17610 Each entry has the form (MODIFIER . MINUTES).
17612 In an effort string, a number followed by MODIFIER is multiplied
17613 by the specified number of MINUTES to obtain an effort in
17614 minutes.
17616 For example, if the value of this variable is ((\"hours\" . 60)), then an
17617 effort string \"2hours\" is equivalent to 120 minutes."
17618 :group 'org-agenda
17619 :version "24.1"
17620 :type '(alist :key-type (string :tag "Modifier")
17621 :value-type (number :tag "Minutes")))
17623 (defun org-minutes-to-clocksum-string (m)
17624 "Format number of minutes as a clocksum string.
17625 The format is determined by `org-time-clocksum-format',
17626 `org-time-clocksum-use-fractional' and
17627 `org-time-clocksum-fractional-format' and
17628 `org-time-clocksum-use-effort-durations'."
17629 (let ((clocksum "")
17630 (m (round m)) ; Don't allow fractions of minutes
17631 h d w mo y fmt n)
17632 (setq h (if org-time-clocksum-use-effort-durations
17633 (cdr (assoc "h" org-effort-durations)) 60)
17634 d (if org-time-clocksum-use-effort-durations
17635 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17636 w (if org-time-clocksum-use-effort-durations
17637 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17638 mo (if org-time-clocksum-use-effort-durations
17639 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17640 y (if org-time-clocksum-use-effort-durations
17641 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17642 ;; fractional format
17643 (if org-time-clocksum-use-fractional
17644 (cond
17645 ;; single format string
17646 ((stringp org-time-clocksum-fractional-format)
17647 (format org-time-clocksum-fractional-format (/ m (float h))))
17648 ;; choice of fractional formats for different time units
17649 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17650 (> (/ (truncate m) (* y d h)) 0))
17651 (format fmt (/ m (* y d (float h)))))
17652 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17653 (> (/ (truncate m) (* mo d h)) 0))
17654 (format fmt (/ m (* mo d (float h)))))
17655 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17656 (> (/ (truncate m) (* w d h)) 0))
17657 (format fmt (/ m (* w d (float h)))))
17658 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17659 (> (/ (truncate m) (* d h)) 0))
17660 (format fmt (/ m (* d (float h)))))
17661 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17662 (> (/ (truncate m) h) 0))
17663 (format fmt (/ m (float h))))
17664 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17665 (format fmt m))
17666 ;; fall back to smallest time unit with a format
17667 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17668 (format fmt (/ m (float h))))
17669 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17670 (format fmt (/ m (* d (float h)))))
17671 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17672 (format fmt (/ m (* w d (float h)))))
17673 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17674 (format fmt (/ m (* mo d (float h)))))
17675 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17676 (format fmt (/ m (* y d (float h))))))
17677 ;; standard (non-fractional) format, with single format string
17678 (if (stringp org-time-clocksum-format)
17679 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17680 ;; separate formats components
17681 (and (setq fmt (plist-get org-time-clocksum-format :years))
17682 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17683 (plist-get org-time-clocksum-format :require-years))
17684 (setq clocksum (concat clocksum (format fmt n))
17685 m (- m (* n y d h))))
17686 (and (setq fmt (plist-get org-time-clocksum-format :months))
17687 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17688 (plist-get org-time-clocksum-format :require-months))
17689 (setq clocksum (concat clocksum (format fmt n))
17690 m (- m (* n mo d h))))
17691 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17692 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17693 (plist-get org-time-clocksum-format :require-weeks))
17694 (setq clocksum (concat clocksum (format fmt n))
17695 m (- m (* n w d h))))
17696 (and (setq fmt (plist-get org-time-clocksum-format :days))
17697 (or (> (setq n (/ (truncate m) (* d h))) 0)
17698 (plist-get org-time-clocksum-format :require-days))
17699 (setq clocksum (concat clocksum (format fmt n))
17700 m (- m (* n d h))))
17701 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17702 (or (> (setq n (/ (truncate m) h)) 0)
17703 (plist-get org-time-clocksum-format :require-hours))
17704 (setq clocksum (concat clocksum (format fmt n))
17705 m (- m (* n h))))
17706 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17707 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17708 (setq clocksum (concat clocksum (format fmt m))))
17709 ;; return formatted time duration
17710 clocksum))))
17712 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17713 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17714 "Org mode version 8.0")
17716 (defun org-hours-to-clocksum-string (n)
17717 (org-minutes-to-clocksum-string (* n 60)))
17719 (defun org-hh:mm-string-to-minutes (s)
17720 "Convert a string H:MM to a number of minutes.
17721 If the string is just a number, interpret it as minutes.
17722 In fact, the first hh:mm or number in the string will be taken,
17723 there can be extra stuff in the string.
17724 If no number is found, the return value is 0."
17725 (cond
17726 ((integerp s) s)
17727 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17728 (+ (* (string-to-number (match-string 1 s)) 60)
17729 (string-to-number (match-string 2 s))))
17730 ((string-match "\\([0-9]+\\)" s)
17731 (string-to-number (match-string 1 s)))
17732 (t 0)))
17734 (defcustom org-image-actual-width t
17735 "Should we use the actual width of images when inlining them?
17737 When set to `t', always use the image width.
17739 When set to a number, use imagemagick (when available) to set
17740 the image's width to this value.
17742 When set to a number in a list, try to get the width from any
17743 #+ATTR.* keyword if it matches a width specification like
17745 #+ATTR_HTML: :width 300px
17747 and fall back on that number if none is found.
17749 When set to nil, try to get the width from an #+ATTR.* keyword
17750 and fall back on the original width if none is found.
17752 This requires Emacs >= 24.1, build with imagemagick support."
17753 :group 'org-appearance
17754 :version "24.4"
17755 :package-version '(Org . "8.0")
17756 :type '(choice
17757 (const :tag "Use the image width" t)
17758 (integer :tag "Use a number of pixels")
17759 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17760 (const :tag "Use #+ATTR* or don't resize" nil)))
17762 (defcustom org-agenda-inhibit-startup nil
17763 "Inhibit startup when preparing agenda buffers.
17764 When this variable is `t' (the default), the initialization of
17765 the Org agenda buffers is inhibited: e.g. the visibility state
17766 is not set, the tables are not re-aligned, etc."
17767 :type 'boolean
17768 :version "24.3"
17769 :group 'org-agenda)
17771 (defcustom org-agenda-ignore-drawer-properties nil
17772 "Avoid updating text properties when building the agenda.
17773 Properties are used to prepare buffers for effort estimates, appointments,
17774 and subtree-local categories.
17775 If you don't use these in the agenda, you can add them to this list and
17776 agenda building will be a bit faster.
17777 The value is a list, with zero or more of the symbols `effort', `appt',
17778 or `category'."
17779 :type '(set :greedy t
17780 (const effort)
17781 (const appt)
17782 (const category))
17783 :version "24.3"
17784 :group 'org-agenda)
17786 (defun org-duration-string-to-minutes (s &optional output-to-string)
17787 "Convert a duration string S to minutes.
17789 A bare number is interpreted as minutes, modifiers can be set by
17790 customizing `org-effort-durations' (which see).
17792 Entries containing a colon are interpreted as H:MM by
17793 `org-hh:mm-string-to-minutes'."
17794 (let ((result 0)
17795 (re (concat "\\([0-9.]+\\) *\\("
17796 (regexp-opt (mapcar 'car org-effort-durations))
17797 "\\)")))
17798 (while (string-match re s)
17799 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17800 (string-to-number (match-string 1 s))))
17801 (setq s (replace-match "" nil t s)))
17802 (setq result (floor result))
17803 (incf result (org-hh:mm-string-to-minutes s))
17804 (if output-to-string (number-to-string result) result)))
17806 ;;;; Files
17808 (defun org-save-all-org-buffers ()
17809 "Save all Org-mode buffers without user confirmation."
17810 (interactive)
17811 (message "Saving all Org-mode buffers...")
17812 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17813 (when (featurep 'org-id) (org-id-locations-save))
17814 (message "Saving all Org-mode buffers... done"))
17816 (defun org-revert-all-org-buffers ()
17817 "Revert all Org-mode buffers.
17818 Prompt for confirmation when there are unsaved changes.
17819 Be sure you know what you are doing before letting this function
17820 overwrite your changes.
17822 This function is useful in a setup where one tracks org files
17823 with a version control system, to revert on one machine after pulling
17824 changes from another. I believe the procedure must be like this:
17826 1. M-x org-save-all-org-buffers
17827 2. Pull changes from the other machine, resolve conflicts
17828 3. M-x org-revert-all-org-buffers"
17829 (interactive)
17830 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17831 (user-error "Abort"))
17832 (save-excursion
17833 (save-window-excursion
17834 (mapc
17835 (lambda (b)
17836 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17837 (with-current-buffer b buffer-file-name))
17838 (org-pop-to-buffer-same-window b)
17839 (revert-buffer t 'no-confirm)))
17840 (buffer-list))
17841 (when (and (featurep 'org-id) org-id-track-globally)
17842 (org-id-locations-load)))))
17844 ;;;; Agenda files
17846 ;;;###autoload
17847 (defun org-switchb (&optional arg)
17848 "Switch between Org buffers.
17849 With one prefix argument, restrict available buffers to files.
17850 With two prefix arguments, restrict available buffers to agenda files.
17852 Defaults to `iswitchb' for buffer name completion.
17853 Set `org-completion-use-ido' to make it use ido instead."
17854 (interactive "P")
17855 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17856 ((equal arg '(16)) (org-buffer-list 'agenda))
17857 (t (org-buffer-list))))
17858 (org-completion-use-iswitchb org-completion-use-iswitchb)
17859 (org-completion-use-ido org-completion-use-ido))
17860 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17861 (setq org-completion-use-iswitchb t))
17862 (org-pop-to-buffer-same-window
17863 (org-icompleting-read "Org buffer: "
17864 (mapcar 'list (mapcar 'buffer-name blist))
17865 nil t))))
17867 ;;; Define some older names previously used for this functionality
17868 ;;;###autoload
17869 (defalias 'org-ido-switchb 'org-switchb)
17870 ;;;###autoload
17871 (defalias 'org-iswitchb 'org-switchb)
17873 (defun org-buffer-list (&optional predicate exclude-tmp)
17874 "Return a list of Org buffers.
17875 PREDICATE can be `export', `files' or `agenda'.
17877 export restrict the list to Export buffers.
17878 files restrict the list to buffers visiting Org files.
17879 agenda restrict the list to buffers visiting agenda files.
17881 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17882 (let* ((bfn nil)
17883 (agenda-files (and (eq predicate 'agenda)
17884 (mapcar 'file-truename (org-agenda-files t))))
17885 (filter
17886 (cond
17887 ((eq predicate 'files)
17888 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17889 ((eq predicate 'export)
17890 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17891 ((eq predicate 'agenda)
17892 (lambda (b)
17893 (with-current-buffer b
17894 (and (derived-mode-p 'org-mode)
17895 (setq bfn (buffer-file-name b))
17896 (member (file-truename bfn) agenda-files)))))
17897 (t (lambda (b) (with-current-buffer b
17898 (or (derived-mode-p 'org-mode)
17899 (string-match "\*Org .*Export"
17900 (buffer-name b)))))))))
17901 (delq nil
17902 (mapcar
17903 (lambda(b)
17904 (if (and (funcall filter b)
17905 (or (not exclude-tmp)
17906 (not (string-match "tmp" (buffer-name b)))))
17908 nil))
17909 (buffer-list)))))
17911 (defun org-agenda-files (&optional unrestricted archives)
17912 "Get the list of agenda files.
17913 Optional UNRESTRICTED means return the full list even if a restriction
17914 is currently in place.
17915 When ARCHIVES is t, include all archive files that are really being
17916 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17917 `org-agenda-archives-mode' is t."
17918 (let ((files
17919 (cond
17920 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17921 ((stringp org-agenda-files) (org-read-agenda-file-list))
17922 ((listp org-agenda-files) org-agenda-files)
17923 (t (error "Invalid value of `org-agenda-files'")))))
17924 (setq files (apply 'append
17925 (mapcar (lambda (f)
17926 (if (file-directory-p f)
17927 (directory-files
17928 f t org-agenda-file-regexp)
17929 (list f)))
17930 files)))
17931 (when org-agenda-skip-unavailable-files
17932 (setq files (delq nil
17933 (mapcar (function
17934 (lambda (file)
17935 (and (file-readable-p file) file)))
17936 files))))
17937 (when (or (eq archives t)
17938 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17939 (setq files (org-add-archive-files files)))
17940 files))
17942 (defun org-agenda-file-p (&optional file)
17943 "Return non-nil, if FILE is an agenda file.
17944 If FILE is omitted, use the file associated with the current
17945 buffer."
17946 (member (or file (buffer-file-name))
17947 (org-agenda-files t)))
17949 (defun org-edit-agenda-file-list ()
17950 "Edit the list of agenda files.
17951 Depending on setup, this either uses customize to edit the variable
17952 `org-agenda-files', or it visits the file that is holding the list. In the
17953 latter case, the buffer is set up in a way that saving it automatically kills
17954 the buffer and restores the previous window configuration."
17955 (interactive)
17956 (if (stringp org-agenda-files)
17957 (let ((cw (current-window-configuration)))
17958 (find-file org-agenda-files)
17959 (org-set-local 'org-window-configuration cw)
17960 (org-add-hook 'after-save-hook
17961 (lambda ()
17962 (set-window-configuration
17963 (prog1 org-window-configuration
17964 (kill-buffer (current-buffer))))
17965 (org-install-agenda-files-menu)
17966 (message "New agenda file list installed"))
17967 nil 'local)
17968 (message "%s" (substitute-command-keys
17969 "Edit list and finish with \\[save-buffer]")))
17970 (customize-variable 'org-agenda-files)))
17972 (defun org-store-new-agenda-file-list (list)
17973 "Set new value for the agenda file list and save it correctly."
17974 (if (stringp org-agenda-files)
17975 (let ((fe (org-read-agenda-file-list t)) b u)
17976 (while (setq b (find-buffer-visiting org-agenda-files))
17977 (kill-buffer b))
17978 (with-temp-file org-agenda-files
17979 (insert
17980 (mapconcat
17981 (lambda (f) ;; Keep un-expanded entries.
17982 (if (setq u (assoc f fe))
17983 (cdr u)
17985 list "\n")
17986 "\n")))
17987 (let ((org-mode-hook nil) (org-inhibit-startup t)
17988 (org-insert-mode-line-in-empty-file nil))
17989 (setq org-agenda-files list)
17990 (customize-save-variable 'org-agenda-files org-agenda-files))))
17992 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17993 "Read the list of agenda files from a file.
17994 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17995 filenames, used by `org-store-new-agenda-file-list' to write back
17996 un-expanded file names."
17997 (when (file-directory-p org-agenda-files)
17998 (error "`org-agenda-files' cannot be a single directory"))
17999 (when (stringp org-agenda-files)
18000 (with-temp-buffer
18001 (insert-file-contents org-agenda-files)
18002 (mapcar
18003 (lambda (f)
18004 (let ((e (expand-file-name (substitute-in-file-name f)
18005 org-directory)))
18006 (if pair-with-expansion
18007 (cons e f)
18008 e)))
18009 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18011 ;;;###autoload
18012 (defun org-cycle-agenda-files ()
18013 "Cycle through the files in `org-agenda-files'.
18014 If the current buffer visits an agenda file, find the next one in the list.
18015 If the current buffer does not, find the first agenda file."
18016 (interactive)
18017 (let* ((fs (org-agenda-files t))
18018 (files (append fs (list (car fs))))
18019 (tcf (if buffer-file-name (file-truename buffer-file-name)))
18020 file)
18021 (unless files (user-error "No agenda files"))
18022 (catch 'exit
18023 (while (setq file (pop files))
18024 (if (equal (file-truename file) tcf)
18025 (when (car files)
18026 (find-file (car files))
18027 (throw 'exit t))))
18028 (find-file (car fs)))
18029 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
18031 (defun org-agenda-file-to-front (&optional to-end)
18032 "Move/add the current file to the top of the agenda file list.
18033 If the file is not present in the list, it is added to the front. If it is
18034 present, it is moved there. With optional argument TO-END, add/move to the
18035 end of the list."
18036 (interactive "P")
18037 (let ((org-agenda-skip-unavailable-files nil)
18038 (file-alist (mapcar (lambda (x)
18039 (cons (file-truename x) x))
18040 (org-agenda-files t)))
18041 (ctf (file-truename
18042 (or buffer-file-name
18043 (user-error "Please save the current buffer to a file"))))
18044 x had)
18045 (setq x (assoc ctf file-alist) had x)
18047 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18048 (if to-end
18049 (setq file-alist (append (delq x file-alist) (list x)))
18050 (setq file-alist (cons x (delq x file-alist))))
18051 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18052 (org-install-agenda-files-menu)
18053 (message "File %s to %s of agenda file list"
18054 (if had "moved" "added") (if to-end "end" "front"))))
18056 (defun org-remove-file (&optional file)
18057 "Remove current file from the list of files in variable `org-agenda-files'.
18058 These are the files which are being checked for agenda entries.
18059 Optional argument FILE means use this file instead of the current."
18060 (interactive)
18061 (let* ((org-agenda-skip-unavailable-files nil)
18062 (file (or file buffer-file-name
18063 (user-error "Current buffer does not visit a file")))
18064 (true-file (file-truename file))
18065 (afile (abbreviate-file-name file))
18066 (files (delq nil (mapcar
18067 (lambda (x)
18068 (if (equal true-file
18069 (file-truename x))
18070 nil x))
18071 (org-agenda-files t)))))
18072 (if (not (= (length files) (length (org-agenda-files t))))
18073 (progn
18074 (org-store-new-agenda-file-list files)
18075 (org-install-agenda-files-menu)
18076 (message "Removed file: %s" afile))
18077 (message "File was not in list: %s (not removed)" afile))))
18079 (defun org-file-menu-entry (file)
18080 (vector file (list 'find-file file) t))
18082 (defun org-check-agenda-file (file)
18083 "Make sure FILE exists. If not, ask user what to do."
18084 (when (not (file-exists-p file))
18085 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18086 (abbreviate-file-name file))
18087 (let ((r (downcase (read-char-exclusive))))
18088 (cond
18089 ((equal r ?r)
18090 (org-remove-file file)
18091 (throw 'nextfile t))
18092 (t (error "Abort"))))))
18094 (defun org-get-agenda-file-buffer (file)
18095 "Get a buffer visiting FILE. If the buffer needs to be created, add
18096 it to the list of buffers which might be released later."
18097 (let ((buf (org-find-base-buffer-visiting file)))
18098 (if buf
18099 buf ; just return it
18100 ;; Make a new buffer and remember it
18101 (setq buf (find-file-noselect file))
18102 (if buf (push buf org-agenda-new-buffers))
18103 buf)))
18105 (defun org-release-buffers (blist)
18106 "Release all buffers in list, asking the user for confirmation when needed.
18107 When a buffer is unmodified, it is just killed. When modified, it is saved
18108 \(if the user agrees) and then killed."
18109 (let (buf file)
18110 (while (setq buf (pop blist))
18111 (setq file (buffer-file-name buf))
18112 (when (and (buffer-modified-p buf)
18113 file
18114 (y-or-n-p (format "Save file %s? " file)))
18115 (with-current-buffer buf (save-buffer)))
18116 (kill-buffer buf))))
18118 (defun org-agenda-prepare-buffers (files)
18119 "Create buffers for all agenda files, protect archived trees and comments."
18120 (interactive)
18121 (let ((pa '(:org-archived t))
18122 (pc '(:org-comment t))
18123 (pall '(:org-archived t :org-comment t))
18124 (inhibit-read-only t)
18125 (org-inhibit-startup org-agenda-inhibit-startup)
18126 (rea (concat ":" org-archive-tag ":"))
18127 file re pos)
18128 (setq org-tag-alist-for-agenda nil
18129 org-tag-groups-alist-for-agenda nil)
18130 (save-window-excursion
18131 (save-restriction
18132 (while (setq file (pop files))
18133 (catch 'nextfile
18134 (if (bufferp file)
18135 (set-buffer file)
18136 (org-check-agenda-file file)
18137 (set-buffer (org-get-agenda-file-buffer file)))
18138 (widen)
18139 (org-set-regexps-and-options-for-tags)
18140 (setq pos (point))
18141 (goto-char (point-min))
18142 (let ((case-fold-search t))
18143 (when (search-forward "#+setupfile" nil t)
18144 ;; Don't set all regexps and options systematically as
18145 ;; this is only run for setting agenda tags from setup
18146 ;; file
18147 (org-set-regexps-and-options)))
18148 (or (memq 'category org-agenda-ignore-drawer-properties)
18149 (org-refresh-category-properties))
18150 (or (memq 'effort org-agenda-ignore-drawer-properties)
18151 (org-refresh-properties org-effort-property 'org-effort))
18152 (or (memq 'appt org-agenda-ignore-drawer-properties)
18153 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18154 (setq org-todo-keywords-for-agenda
18155 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18156 (setq org-done-keywords-for-agenda
18157 (append org-done-keywords-for-agenda org-done-keywords))
18158 (setq org-todo-keyword-alist-for-agenda
18159 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18160 (setq org-tag-alist-for-agenda
18161 (org-uniquify
18162 (append org-tag-alist-for-agenda
18163 org-tag-alist
18164 org-tag-persistent-alist)))
18165 (if org-group-tags
18166 (setq org-tag-groups-alist-for-agenda
18167 (org-uniquify-alist
18168 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18169 (org-with-silent-modifications
18170 (save-excursion
18171 (remove-text-properties (point-min) (point-max) pall)
18172 (when org-agenda-skip-archived-trees
18173 (goto-char (point-min))
18174 (while (re-search-forward rea nil t)
18175 (if (org-at-heading-p t)
18176 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18177 (goto-char (point-min))
18178 (setq re (format org-heading-keyword-regexp-format
18179 org-comment-string))
18180 (while (re-search-forward re nil t)
18181 (add-text-properties
18182 (match-beginning 0) (org-end-of-subtree t) pc))))
18183 (goto-char pos)))))
18184 (setq org-todo-keywords-for-agenda
18185 (org-uniquify org-todo-keywords-for-agenda))
18186 (setq org-todo-keyword-alist-for-agenda
18187 (org-uniquify org-todo-keyword-alist-for-agenda))))
18190 ;;;; CDLaTeX minor mode
18192 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18193 "Keymap for the minor `org-cdlatex-mode'.")
18195 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18196 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18197 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18198 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18199 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
18201 (defvar org-cdlatex-texmathp-advice-is-done nil
18202 "Flag remembering if we have applied the advice to texmathp already.")
18204 (define-minor-mode org-cdlatex-mode
18205 "Toggle the minor `org-cdlatex-mode'.
18206 This mode supports entering LaTeX environment and math in LaTeX fragments
18207 in Org-mode.
18208 \\{org-cdlatex-mode-map}"
18209 nil " OCDL" nil
18210 (when org-cdlatex-mode
18211 (require 'cdlatex)
18212 (run-hooks 'cdlatex-mode-hook)
18213 (cdlatex-compute-tables))
18214 (unless org-cdlatex-texmathp-advice-is-done
18215 (setq org-cdlatex-texmathp-advice-is-done t)
18216 (defadvice texmathp (around org-math-always-on activate)
18217 "Always return t in org-mode buffers.
18218 This is because we want to insert math symbols without dollars even outside
18219 the LaTeX math segments. If Orgmode thinks that point is actually inside
18220 an embedded LaTeX fragment, let texmathp do its job.
18221 \\[org-cdlatex-mode-map]"
18222 (interactive)
18223 (let (p)
18224 (cond
18225 ((not (derived-mode-p 'org-mode)) ad-do-it)
18226 ((eq this-command 'cdlatex-math-symbol)
18227 (setq ad-return-value t
18228 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18230 (let ((p (org-inside-LaTeX-fragment-p)))
18231 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18232 (setq ad-return-value t
18233 texmathp-why '("Org-mode embedded math" . 0))
18234 (if p ad-do-it)))))))))
18236 (defun turn-on-org-cdlatex ()
18237 "Unconditionally turn on `org-cdlatex-mode'."
18238 (org-cdlatex-mode 1))
18240 (defun org-try-cdlatex-tab ()
18241 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18242 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18243 - inside a LaTeX fragment, or
18244 - after the first word in a line, where an abbreviation expansion could
18245 insert a LaTeX environment."
18246 (when org-cdlatex-mode
18247 (cond
18248 ;; Before any word on the line: No expansion possible.
18249 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18250 ;; Just after first word on the line: Expand it. Make sure it
18251 ;; cannot happen on headlines, though.
18252 ((save-excursion
18253 (skip-chars-backward "a-zA-Z0-9*")
18254 (skip-chars-backward " \t")
18255 (and (bolp) (not (org-at-heading-p))))
18256 (cdlatex-tab) t)
18257 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18259 (defun org-cdlatex-underscore-caret (&optional arg)
18260 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18261 Revert to the normal definition outside of these fragments."
18262 (interactive "P")
18263 (if (org-inside-LaTeX-fragment-p)
18264 (call-interactively 'cdlatex-sub-superscript)
18265 (let (org-cdlatex-mode)
18266 (call-interactively (key-binding (vector last-input-event))))))
18268 (defun org-cdlatex-math-modify (&optional arg)
18269 "Execute `cdlatex-math-modify' in LaTeX fragments.
18270 Revert to the normal definition outside of these fragments."
18271 (interactive "P")
18272 (if (org-inside-LaTeX-fragment-p)
18273 (call-interactively 'cdlatex-math-modify)
18274 (let (org-cdlatex-mode)
18275 (call-interactively (key-binding (vector last-input-event))))))
18279 ;;;; LaTeX fragments
18281 (defun org-inside-LaTeX-fragment-p ()
18282 "Test if point is inside a LaTeX fragment.
18283 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18284 sequence appearing also before point.
18285 Even though the matchers for math are configurable, this function assumes
18286 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18287 delimiters are skipped when they have been removed by customization.
18288 The return value is nil, or a cons cell with the delimiter and the
18289 position of this delimiter.
18291 This function does a reasonably good job, but can locally be fooled by
18292 for example currency specifications. For example it will assume being in
18293 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18294 fragments that are properly closed, but during editing, we have to live
18295 with the uncertainty caused by missing closing delimiters. This function
18296 looks only before point, not after."
18297 (catch 'exit
18298 (let ((pos (point))
18299 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18300 (lim (progn
18301 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18302 (point)))
18303 dd-on str (start 0) m re)
18304 (goto-char pos)
18305 (when dodollar
18306 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18307 re (nth 1 (assoc "$" org-latex-regexps)))
18308 (while (string-match re str start)
18309 (cond
18310 ((= (match-end 0) (length str))
18311 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18312 ((= (match-end 0) (- (length str) 5))
18313 (throw 'exit nil))
18314 (t (setq start (match-end 0))))))
18315 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18316 (goto-char pos)
18317 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18318 (and (match-beginning 2) (throw 'exit nil))
18319 ;; count $$
18320 (while (re-search-backward "\\$\\$" lim t)
18321 (setq dd-on (not dd-on)))
18322 (goto-char pos)
18323 (if dd-on (cons "$$" m))))))
18325 (defun org-inside-latex-macro-p ()
18326 "Is point inside a LaTeX macro or its arguments?"
18327 (save-match-data
18328 (org-in-regexp
18329 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18331 (defvar org-latex-fragment-image-overlays nil
18332 "List of overlays carrying the images of latex fragments.")
18333 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18335 (defun org-remove-latex-fragment-image-overlays ()
18336 "Remove all overlays with LaTeX fragment images in current buffer."
18337 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18338 (setq org-latex-fragment-image-overlays nil))
18340 (defun org-preview-latex-fragment (&optional subtree)
18341 "Preview the LaTeX fragment at point, or all locally or globally.
18342 If the cursor is in a LaTeX fragment, create the image and overlay
18343 it over the source code. If there is no fragment at point, display
18344 all fragments in the current text, from one headline to the next. With
18345 prefix SUBTREE, display all fragments in the current subtree. With a
18346 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18347 the cursor is before the first headline,
18348 display all fragments in the buffer.
18349 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18350 (interactive "P")
18351 (unless buffer-file-name
18352 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18353 (when (display-graphic-p)
18354 (org-remove-latex-fragment-image-overlays)
18355 (save-excursion
18356 (save-restriction
18357 (let (beg end at msg)
18358 (cond
18359 ((or (equal subtree '(16))
18360 (not (save-excursion
18361 (re-search-backward org-outline-regexp-bol nil t))))
18362 (setq beg (point-min) end (point-max)
18363 msg "Creating images for buffer...%s"))
18364 ((equal subtree '(4))
18365 (org-back-to-heading)
18366 (setq beg (point) end (org-end-of-subtree t)
18367 msg "Creating images for subtree...%s"))
18369 (if (setq at (org-inside-LaTeX-fragment-p))
18370 (goto-char (max (point-min) (- (cdr at) 2)))
18371 (org-back-to-heading))
18372 (setq beg (point) end (progn (outline-next-heading) (point))
18373 msg (if at "Creating image...%s"
18374 "Creating images for entry...%s"))))
18375 (message msg "")
18376 (narrow-to-region beg end)
18377 (goto-char beg)
18378 (org-format-latex
18379 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18380 (file-name-nondirectory
18381 buffer-file-name)))
18382 default-directory 'overlays msg at 'forbuffer
18383 org-latex-create-formula-image-program)
18384 (message msg "done. Use `C-c C-c' to remove images."))))))
18386 (defun org-format-latex (prefix &optional dir overlays msg at
18387 forbuffer processing-type)
18388 "Replace LaTeX fragments with links to an image, and produce images.
18389 Some of the options can be changed using the variable
18390 `org-format-latex-options'."
18391 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18392 (let* ((prefixnodir (file-name-nondirectory prefix))
18393 (absprefix (expand-file-name prefix dir))
18394 (todir (file-name-directory absprefix))
18395 (opt org-format-latex-options)
18396 (optnew org-format-latex-options)
18397 (matchers (plist-get opt :matchers))
18398 (re-list org-latex-regexps)
18399 (cnt 0) txt hash link beg end re e checkdir
18400 string
18401 m n block-type block linkfile movefile ov)
18402 ;; Check the different regular expressions
18403 (while (setq e (pop re-list))
18404 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18405 block (if block-type "\n\n" ""))
18406 (when (member m matchers)
18407 (goto-char (point-min))
18408 (while (re-search-forward re nil t)
18409 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18410 (or (not overlays)
18411 (not (eq (get-char-property (match-beginning n)
18412 'org-overlay-type)
18413 'org-latex-overlay))))
18414 (cond
18415 ((eq processing-type 'verbatim))
18416 ((eq processing-type 'mathjax)
18417 ;; Prepare for MathJax processing.
18418 (setq string (match-string n))
18419 (when (member m '("$" "$1"))
18420 (save-excursion
18421 (delete-region (match-beginning n) (match-end n))
18422 (goto-char (match-beginning n))
18423 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18424 ((or (eq processing-type 'dvipng)
18425 (eq processing-type 'imagemagick))
18426 ;; Process to an image.
18427 (setq txt (match-string n)
18428 beg (match-beginning n) end (match-end n)
18429 cnt (1+ cnt))
18430 (let ((face (face-at-point))
18431 (fg (plist-get opt :foreground))
18432 (bg (plist-get opt :background))
18433 ;; Ensure full list is printed.
18434 print-length print-level)
18435 (when forbuffer
18436 ;; Get the colors from the face at point.
18437 (goto-char beg)
18438 (when (eq fg 'auto)
18439 (setq fg (face-attribute face :foreground nil 'default)))
18440 (when (eq bg 'auto)
18441 (setq bg (face-attribute face :background nil 'default)))
18442 (setq optnew (copy-sequence opt))
18443 (plist-put optnew :foreground fg)
18444 (plist-put optnew :background bg))
18445 (setq hash (sha1 (prin1-to-string
18446 (list org-format-latex-header
18447 org-latex-default-packages-alist
18448 org-latex-packages-alist
18449 org-format-latex-options
18450 forbuffer txt fg bg)))
18451 linkfile (format "%s_%s.png" prefix hash)
18452 movefile (format "%s_%s.png" absprefix hash)))
18453 (setq link (concat block "[[file:" linkfile "]]" block))
18454 (if msg (message msg cnt))
18455 (goto-char beg)
18456 (unless checkdir ; Ensure the directory exists.
18457 (setq checkdir t)
18458 (or (file-directory-p todir) (make-directory todir t)))
18459 (unless (file-exists-p movefile)
18460 (org-create-formula-image
18461 txt movefile optnew forbuffer processing-type))
18462 (if overlays
18463 (progn
18464 (mapc (lambda (o)
18465 (if (eq (overlay-get o 'org-overlay-type)
18466 'org-latex-overlay)
18467 (delete-overlay o)))
18468 (overlays-in beg end))
18469 (setq ov (make-overlay beg end))
18470 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18471 (if (featurep 'xemacs)
18472 (progn
18473 (overlay-put ov 'invisible t)
18474 (overlay-put
18475 ov 'end-glyph
18476 (make-glyph (vector 'png :file movefile))))
18477 (overlay-put
18478 ov 'display
18479 (list 'image :type 'png :file movefile :ascent 'center)))
18480 (push ov org-latex-fragment-image-overlays)
18481 (goto-char end))
18482 (delete-region beg end)
18483 (insert (org-add-props link
18484 (list 'org-latex-src
18485 (replace-regexp-in-string
18486 "\"" "" txt)
18487 'org-latex-src-embed-type
18488 (if block-type 'paragraph 'character))))))
18489 ((eq processing-type 'mathml)
18490 ;; Process to MathML
18491 (unless (save-match-data (org-format-latex-mathml-available-p))
18492 (user-error "LaTeX to MathML converter not configured"))
18493 (setq txt (match-string n)
18494 beg (match-beginning n) end (match-end n)
18495 cnt (1+ cnt))
18496 (if msg (message msg cnt))
18497 (goto-char beg)
18498 (delete-region beg end)
18499 (insert (org-format-latex-as-mathml
18500 txt block-type prefix dir)))
18502 (error "Unknown conversion type %s for LaTeX fragments"
18503 processing-type)))))))))
18505 (defun org-create-math-formula (latex-frag &optional mathml-file)
18506 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18507 Use `org-latex-to-mathml-convert-command'. If the conversion is
18508 sucessful, return the portion between \"<math...> </math>\"
18509 elements otherwise return nil. When MATHML-FILE is specified,
18510 write the results in to that file. When invoked as an
18511 interactive command, prompt for LATEX-FRAG, with initial value
18512 set to the current active region and echo the results for user
18513 inspection."
18514 (interactive (list (let ((frag (when (org-region-active-p)
18515 (buffer-substring-no-properties
18516 (region-beginning) (region-end)))))
18517 (read-string "LaTeX Fragment: " frag nil frag))))
18518 (unless latex-frag (error "Invalid LaTeX fragment"))
18519 (let* ((tmp-in-file (file-relative-name
18520 (make-temp-name (expand-file-name "ltxmathml-in"))))
18521 (ignore (write-region latex-frag nil tmp-in-file))
18522 (tmp-out-file (file-relative-name
18523 (make-temp-name (expand-file-name "ltxmathml-out"))))
18524 (cmd (format-spec
18525 org-latex-to-mathml-convert-command
18526 `((?j . ,(shell-quote-argument
18527 (expand-file-name org-latex-to-mathml-jar-file)))
18528 (?I . ,(shell-quote-argument tmp-in-file))
18529 (?o . ,(shell-quote-argument tmp-out-file)))))
18530 mathml shell-command-output)
18531 (when (org-called-interactively-p 'any)
18532 (unless (org-format-latex-mathml-available-p)
18533 (user-error "LaTeX to MathML converter not configured")))
18534 (message "Running %s" cmd)
18535 (setq shell-command-output (shell-command-to-string cmd))
18536 (setq mathml
18537 (when (file-readable-p tmp-out-file)
18538 (with-current-buffer (find-file-noselect tmp-out-file t)
18539 (goto-char (point-min))
18540 (when (re-search-forward
18541 (concat
18542 (regexp-quote
18543 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18544 "\\(.\\|\n\\)*"
18545 (regexp-quote "</math>")) nil t)
18546 (prog1 (match-string 0) (kill-buffer))))))
18547 (cond
18548 (mathml
18549 (setq mathml
18550 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18551 (when mathml-file
18552 (write-region mathml nil mathml-file))
18553 (when (org-called-interactively-p 'any)
18554 (message mathml)))
18555 ((message "LaTeX to MathML conversion failed")
18556 (message shell-command-output)))
18557 (delete-file tmp-in-file)
18558 (when (file-exists-p tmp-out-file)
18559 (delete-file tmp-out-file))
18560 mathml))
18562 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18563 prefix &optional dir)
18564 "Use `org-create-math-formula' but check local cache first."
18565 (let* ((absprefix (expand-file-name prefix dir))
18566 (print-length nil) (print-level nil)
18567 (formula-id (concat
18568 "formula-"
18569 (sha1
18570 (prin1-to-string
18571 (list latex-frag
18572 org-latex-to-mathml-convert-command)))))
18573 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18574 (formula-cache-dir (file-name-directory formula-cache)))
18576 (unless (file-directory-p formula-cache-dir)
18577 (make-directory formula-cache-dir t))
18579 (unless (file-exists-p formula-cache)
18580 (org-create-math-formula latex-frag formula-cache))
18582 (if (file-exists-p formula-cache)
18583 ;; Successful conversion. Return the link to MathML file.
18584 (org-add-props
18585 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18586 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18587 'org-latex-src-embed-type (if latex-frag-type
18588 'paragraph 'character)))
18589 ;; Failed conversion. Return the LaTeX fragment verbatim
18590 latex-frag)))
18592 (defun org-create-formula-image (string tofile options buffer &optional type)
18593 "Create an image from LaTeX source using dvipng or convert.
18594 This function calls either `org-create-formula-image-with-dvipng'
18595 or `org-create-formula-image-with-imagemagick' depending on the
18596 value of `org-latex-create-formula-image-program' or on the value
18597 of the optional TYPE variable.
18599 Note: ultimately these two function should be combined as they
18600 share a good deal of logic."
18601 (org-check-external-command
18602 "latex" "needed to convert LaTeX fragments to images")
18603 (funcall
18604 (case (or type org-latex-create-formula-image-program)
18605 ('dvipng
18606 (org-check-external-command
18607 "dvipng" "needed to convert LaTeX fragments to images")
18608 #'org-create-formula-image-with-dvipng)
18609 ('imagemagick
18610 (org-check-external-command
18611 "convert" "you need to install imagemagick")
18612 #'org-create-formula-image-with-imagemagick)
18613 (t (error
18614 "Invalid value of `org-latex-create-formula-image-program'")))
18615 string tofile options buffer))
18617 (declare-function org-export-get-backend "ox" (name))
18618 (declare-function org-export--get-global-options "ox" (&optional backend))
18619 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18620 (declare-function org-latex-guess-inputenc "ox-latex" (header))
18621 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
18622 (defun org-create-formula--latex-header ()
18623 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18624 (let ((info (org-combine-plists (org-export--get-global-options
18625 (org-export-get-backend 'latex))
18626 (org-export--get-inbuffer-options
18627 (org-export-get-backend 'latex)))))
18628 (org-latex-guess-babel-language
18629 (org-latex-guess-inputenc
18630 (org-splice-latex-header
18631 org-format-latex-header
18632 org-latex-default-packages-alist
18633 org-latex-packages-alist t
18634 (plist-get info :latex-header)))
18635 info)))
18637 ;; This function borrows from Ganesh Swami's latex2png.el
18638 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18639 "This calls dvipng."
18640 (require 'ox-latex)
18641 (let* ((tmpdir (if (featurep 'xemacs)
18642 (temp-directory)
18643 temporary-file-directory))
18644 (texfilebase (make-temp-name
18645 (expand-file-name "orgtex" tmpdir)))
18646 (texfile (concat texfilebase ".tex"))
18647 (dvifile (concat texfilebase ".dvi"))
18648 (pngfile (concat texfilebase ".png"))
18649 (fnh (if (featurep 'xemacs)
18650 (font-height (face-font 'default))
18651 (face-attribute 'default :height nil)))
18652 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18653 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18654 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18655 "Black"))
18656 (bg (or (plist-get options (if buffer :background :html-background))
18657 "Transparent")))
18658 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18659 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18660 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18661 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18662 (let ((latex-header (org-create-formula--latex-header)))
18663 (with-temp-file texfile
18664 (insert latex-header)
18665 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18666 (let ((dir default-directory))
18667 (condition-case nil
18668 (progn
18669 (cd tmpdir)
18670 (call-process "latex" nil nil nil texfile))
18671 (error nil))
18672 (cd dir))
18673 (if (not (file-exists-p dvifile))
18674 (progn (message "Failed to create dvi file from %s" texfile) nil)
18675 (condition-case nil
18676 (if (featurep 'xemacs)
18677 (call-process "dvipng" nil nil nil
18678 "-fg" fg "-bg" bg
18679 "-T" "tight"
18680 "-o" pngfile
18681 dvifile)
18682 (call-process "dvipng" nil nil nil
18683 "-fg" fg "-bg" bg
18684 "-D" dpi
18685 ;;"-x" scale "-y" scale
18686 "-T" "tight"
18687 "-o" pngfile
18688 dvifile))
18689 (error nil))
18690 (if (not (file-exists-p pngfile))
18691 (if org-format-latex-signal-error
18692 (error "Failed to create png file from %s" texfile)
18693 (message "Failed to create png file from %s" texfile)
18694 nil)
18695 ;; Use the requested file name and clean up
18696 (copy-file pngfile tofile 'replace)
18697 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18698 (if (file-exists-p (concat texfilebase e))
18699 (delete-file (concat texfilebase e))))
18700 pngfile))))
18702 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18703 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18704 "This calls convert, which is included into imagemagick."
18705 (require 'ox-latex)
18706 (let* ((tmpdir (if (featurep 'xemacs)
18707 (temp-directory)
18708 temporary-file-directory))
18709 (texfilebase (make-temp-name
18710 (expand-file-name "orgtex" tmpdir)))
18711 (texfile (concat texfilebase ".tex"))
18712 (pdffile (concat texfilebase ".pdf"))
18713 (pngfile (concat texfilebase ".png"))
18714 (fnh (if (featurep 'xemacs)
18715 (font-height (face-font 'default))
18716 (face-attribute 'default :height nil)))
18717 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18718 (dpi (number-to-string (* scale (floor (if buffer fnh 120.)))))
18719 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18720 "black"))
18721 (bg (or (plist-get options (if buffer :background :html-background))
18722 "white")))
18723 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18724 (setq fg (org-latex-color-format fg)))
18725 (if (eq bg 'default) (setq bg (org-latex-color :background))
18726 (setq bg (org-latex-color-format
18727 (if (string= bg "Transparent") "white" bg))))
18728 (let ((latex-header (org-create-formula--latex-header)))
18729 (with-temp-file texfile
18730 (insert latex-header)
18731 (insert "\n\\begin{document}\n"
18732 "\\definecolor{fg}{rgb}{" fg "}\n"
18733 "\\definecolor{bg}{rgb}{" bg "}\n"
18734 "\n\\pagecolor{bg}\n"
18735 "\n{\\color{fg}\n"
18736 string
18737 "\n}\n"
18738 "\n\\end{document}\n")))
18739 (org-latex-compile texfile t)
18740 (if (not (file-exists-p pdffile))
18741 (progn (message "Failed to create pdf file from %s" texfile) nil)
18742 (condition-case nil
18743 (if (featurep 'xemacs)
18744 (call-process "convert" nil nil nil
18745 "-density" "96"
18746 "-trim"
18747 "-antialias"
18748 pdffile
18749 "-quality" "100"
18750 ;; "-sharpen" "0x1.0"
18751 pngfile)
18752 (call-process "convert" nil nil nil
18753 "-density" dpi
18754 "-trim"
18755 "-antialias"
18756 pdffile
18757 "-quality" "100"
18758 ;; "-sharpen" "0x1.0"
18759 pngfile))
18760 (error nil))
18761 (if (not (file-exists-p pngfile))
18762 (if org-format-latex-signal-error
18763 (error "Failed to create png file from %s" texfile)
18764 (message "Failed to create png file from %s" texfile)
18765 nil)
18766 ;; Use the requested file name and clean up
18767 (copy-file pngfile tofile 'replace)
18768 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18769 (if (file-exists-p (concat texfilebase e))
18770 (delete-file (concat texfilebase e))))
18771 pngfile))))
18773 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18774 "Fill a LaTeX header template TPL.
18775 In the template, the following place holders will be recognized:
18777 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18778 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18779 [PACKAGES] \\usepackage statements for PKG
18780 [NO-PACKAGES] do not include PKG
18781 [EXTRA] the string EXTRA
18782 [NO-EXTRA] do not include EXTRA
18784 For backward compatibility, if both the positive and the negative place
18785 holder is missing, the positive one (without the \"NO-\") will be
18786 assumed to be present at the end of the template.
18787 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18788 EXTRA is a string.
18789 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18790 (let (rpl (end ""))
18791 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18792 (setq rpl (if (or (match-end 1) (not def-pkg))
18793 "" (org-latex-packages-to-string def-pkg snippets-p t))
18794 tpl (replace-match rpl t t tpl))
18795 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18797 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18798 (setq rpl (if (or (match-end 1) (not pkg))
18799 "" (org-latex-packages-to-string pkg snippets-p t))
18800 tpl (replace-match rpl t t tpl))
18801 (if pkg (setq end
18802 (concat end "\n"
18803 (org-latex-packages-to-string pkg snippets-p)))))
18805 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18806 (setq rpl (if (or (match-end 1) (not extra))
18807 "" (concat extra "\n"))
18808 tpl (replace-match rpl t t tpl))
18809 (if (and extra (string-match "\\S-" extra))
18810 (setq end (concat end "\n" extra))))
18812 (if (string-match "\\S-" end)
18813 (concat tpl "\n" end)
18814 tpl)))
18816 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18817 "Turn an alist of packages into a string with the \\usepackage macros."
18818 (setq pkg (mapconcat (lambda(p)
18819 (cond
18820 ((stringp p) p)
18821 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18822 (format "%% Package %s omitted" (cadr p)))
18823 ((equal "" (car p))
18824 (format "\\usepackage{%s}" (cadr p)))
18826 (format "\\usepackage[%s]{%s}"
18827 (car p) (cadr p)))))
18829 "\n"))
18830 (if newline (concat pkg "\n") pkg))
18832 (defun org-dvipng-color (attr)
18833 "Return a RGB color specification for dvipng."
18834 (apply 'format "rgb %s %s %s"
18835 (mapcar 'org-normalize-color
18836 (if (featurep 'xemacs)
18837 (color-rgb-components
18838 (face-property 'default
18839 (cond ((eq attr :foreground) 'foreground)
18840 ((eq attr :background) 'background))))
18841 (color-values (face-attribute 'default attr nil))))))
18843 (defun org-dvipng-color-format (color-name)
18844 "Convert COLOR-NAME to a RGB color value for dvipng."
18845 (apply 'format "rgb %s %s %s"
18846 (mapcar 'org-normalize-color
18847 (color-values color-name))))
18849 (defun org-latex-color (attr)
18850 "Return a RGB color for the LaTeX color package."
18851 (apply 'format "%s,%s,%s"
18852 (mapcar 'org-normalize-color
18853 (if (featurep 'xemacs)
18854 (color-rgb-components
18855 (face-property 'default
18856 (cond ((eq attr :foreground) 'foreground)
18857 ((eq attr :background) 'background))))
18858 (color-values (face-attribute 'default attr nil))))))
18860 (defun org-latex-color-format (color-name)
18861 "Convert COLOR-NAME to a RGB color value."
18862 (apply 'format "%s,%s,%s"
18863 (mapcar 'org-normalize-color
18864 (color-values color-name))))
18866 (defun org-normalize-color (value)
18867 "Return string to be used as color value for an RGB component."
18868 (format "%g" (/ value 65535.0)))
18872 ;; Image display
18874 (defvar org-inline-image-overlays nil)
18875 (make-variable-buffer-local 'org-inline-image-overlays)
18877 (defun org-toggle-inline-images (&optional include-linked)
18878 "Toggle the display of inline images.
18879 INCLUDE-LINKED is passed to `org-display-inline-images'."
18880 (interactive "P")
18881 (if org-inline-image-overlays
18882 (progn
18883 (org-remove-inline-images)
18884 (message "Inline image display turned off"))
18885 (org-display-inline-images include-linked)
18886 (if (and (org-called-interactively-p)
18887 org-inline-image-overlays)
18888 (message "%d images displayed inline"
18889 (length org-inline-image-overlays))
18890 (message "No images to display inline"))))
18892 (defun org-redisplay-inline-images ()
18893 "Refresh the display of inline images."
18894 (interactive)
18895 (if (not org-inline-image-overlays)
18896 (org-toggle-inline-images)
18897 (org-toggle-inline-images)
18898 (org-toggle-inline-images)))
18900 (defun org-display-inline-images (&optional include-linked refresh beg end)
18901 "Display inline images.
18903 An inline image is a link which follows either of these
18904 conventions:
18906 1. Its path is a file with an extension matching return value
18907 from `image-file-name-regexp' and it has no contents.
18909 2. Its description consists in a single link of the previous
18910 type.
18912 When optional argument INCLUDE-LINKED is non-nil, also links with
18913 a text description part will be inlined. This can be nice for
18914 a quick look at those images, but it does not reflect what
18915 exported files will look like.
18917 When optional argument REFRESH is non-nil, refresh existing
18918 images between BEG and END. This will create new image displays
18919 only if necessary. BEG and END default to the buffer
18920 boundaries."
18921 (interactive "P")
18922 (when (display-graphic-p)
18923 (unless refresh
18924 (org-remove-inline-images)
18925 (when (fboundp 'clear-image-cache) (clear-image-cache)))
18926 (org-with-wide-buffer
18927 (goto-char (or beg (point-min)))
18928 (let ((case-fold-search t)
18929 (file-extension-re (org-image-file-name-regexp)))
18930 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
18931 (let ((link (save-match-data (org-element-context))))
18932 ;; Check if we're at an inline image.
18933 (when (and (equal (org-element-property :type link) "file")
18934 (or include-linked
18935 (not (org-element-property :contents-begin link)))
18936 (let ((parent (org-element-property :parent link)))
18937 (or (not (eq (org-element-type parent) 'link))
18938 (not (cdr (org-element-contents parent)))))
18939 (org-string-match-p file-extension-re
18940 (org-element-property :path link)))
18941 (let ((file (expand-file-name (org-element-property :path link))))
18942 (when (file-exists-p file)
18943 (let ((width
18944 ;; Apply `org-image-actual-width' specifications.
18945 (cond
18946 ((not (image-type-available-p 'imagemagick)) nil)
18947 ((eq org-image-actual-width t) nil)
18948 ((listp org-image-actual-width)
18950 ;; First try to find a width among
18951 ;; attributes associated to the paragraph
18952 ;; containing link.
18953 (let ((paragraph
18954 (let ((e link))
18955 (while (and (setq e (org-element-property
18956 :parent e))
18957 (not (eq (org-element-type e)
18958 'paragraph))))
18959 e)))
18960 (when paragraph
18961 (save-excursion
18962 (goto-char (org-element-property :begin paragraph))
18963 (when (save-match-data
18964 (re-search-forward
18965 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
18966 (org-element-property
18967 :post-affiliated paragraph)
18969 (string-to-number (match-string 1))))))
18970 ;; Otherwise, fall-back to provided number.
18971 (car org-image-actual-width)))
18972 ((numberp org-image-actual-width)
18973 org-image-actual-width)))
18974 (old (get-char-property-and-overlay
18975 (org-element-property :begin link)
18976 'org-image-overlay)))
18977 (if (and (car-safe old) refresh)
18978 (image-refresh (overlay-get (cdr old) 'display))
18979 (let ((image (save-match-data
18980 (create-image file
18981 (and width 'imagemagick)
18983 :width width))))
18984 (when image
18985 (let* ((link
18986 ;; If inline image is the description
18987 ;; of another link, be sure to
18988 ;; consider the latter as the one to
18989 ;; apply the overlay on.
18990 (let ((parent
18991 (org-element-property :parent link)))
18992 (if (eq (org-element-type parent) 'link)
18993 parent
18994 link)))
18995 (ov (make-overlay
18996 (org-element-property :begin link)
18997 (progn
18998 (goto-char
18999 (org-element-property :end link))
19000 (skip-chars-backward " \t")
19001 (point)))))
19002 (overlay-put ov 'display image)
19003 (overlay-put ov 'face 'default)
19004 (overlay-put ov 'org-image-overlay t)
19005 (overlay-put
19006 ov 'modification-hooks
19007 (list 'org-display-inline-remove-overlay))
19008 (push ov org-inline-image-overlays)))))))))))))))
19010 (define-obsolete-function-alias
19011 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
19013 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
19014 "Remove inline-display overlay if a corresponding region is modified."
19015 (let ((inhibit-modification-hooks t))
19016 (when (and ov after)
19017 (delete ov org-inline-image-overlays)
19018 (delete-overlay ov))))
19020 (defun org-remove-inline-images ()
19021 "Remove inline display of images."
19022 (interactive)
19023 (mapc 'delete-overlay org-inline-image-overlays)
19024 (setq org-inline-image-overlays nil))
19026 ;;;; Key bindings
19028 ;; Outline functions from `outline-mode-prefix-map'
19029 ;; that can be remapped in Org:
19030 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19031 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
19032 (define-key org-mode-map [remap outline-forward-same-level]
19033 'org-forward-heading-same-level)
19034 (define-key org-mode-map [remap outline-backward-same-level]
19035 'org-backward-heading-same-level)
19036 (define-key org-mode-map [remap show-branches]
19037 'org-kill-note-or-show-branches)
19038 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19039 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19040 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19042 ;; Outline functions from `outline-mode-prefix-map' that can not
19043 ;; be remapped in Org:
19045 ;; - the column "key binding" shows whether the Outline function is still
19046 ;; available in Org mode on the same key that it has been bound to in
19047 ;; Outline mode:
19048 ;; - "overridden": key used for a different functionality in Org mode
19049 ;; - else: key still bound to the same Outline function in Org mode
19051 ;; | Outline function | key binding | Org replacement |
19052 ;; |------------------------------------+-------------+-----------------------|
19053 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
19054 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
19055 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19056 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19057 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19058 ;; | `show-entry' | overridden | no replacement |
19059 ;; | `show-children' | `C-c C-i' | visibility cycling |
19060 ;; | `show-branches' | `C-c C-k' | still same function |
19061 ;; | `show-subtree' | overridden | visibility cycling |
19062 ;; | `show-all' | overridden | no replacement |
19063 ;; | `hide-subtree' | overridden | visibility cycling |
19064 ;; | `hide-body' | overridden | no replacement |
19065 ;; | `hide-entry' | overridden | visibility cycling |
19066 ;; | `hide-leaves' | overridden | no replacement |
19067 ;; | `hide-sublevels' | overridden | no replacement |
19068 ;; | `hide-other' | overridden | no replacement |
19070 ;; Make `C-c C-x' a prefix key
19071 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19073 ;; TAB key with modifiers
19074 (org-defkey org-mode-map "\C-i" 'org-cycle)
19075 (org-defkey org-mode-map [(tab)] 'org-cycle)
19076 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19077 (org-defkey org-mode-map "\M-\t" 'pcomplete)
19078 ;; The following line is necessary under Suse GNU/Linux
19079 (unless (featurep 'xemacs)
19080 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
19081 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19082 (define-key org-mode-map [backtab] 'org-shifttab)
19084 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19085 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19086 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19088 ;; Cursor keys with modifiers
19089 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19090 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19091 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19092 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19094 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19095 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19096 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19097 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19099 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19100 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19101 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19102 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19104 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19105 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19106 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19107 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19109 ;; Babel keys
19110 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19111 (mapc (lambda (pair)
19112 (define-key org-babel-map (car pair) (cdr pair)))
19113 org-babel-key-bindings)
19115 ;;; Extra keys for tty access.
19116 ;; We only set them when really needed because otherwise the
19117 ;; menus don't show the simple keys
19119 (when (or org-use-extra-keys
19120 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19121 (not window-system))
19122 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19123 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19124 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19125 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19126 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19127 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19128 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19129 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19130 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19131 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19132 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19133 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19134 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19135 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19136 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19137 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19138 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19139 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19140 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19141 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19142 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19143 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19144 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
19145 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19146 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19147 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19148 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19149 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19151 ;; All the other keys
19153 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
19154 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19155 (if (boundp 'narrow-map)
19156 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19157 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19158 (if (boundp 'narrow-map)
19159 (org-defkey narrow-map "b" 'org-narrow-to-block)
19160 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19161 (if (boundp 'narrow-map)
19162 (org-defkey narrow-map "e" 'org-narrow-to-element)
19163 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19164 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19165 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19166 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19167 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19168 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19169 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19170 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19171 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19172 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19173 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19174 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
19175 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19176 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19177 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19178 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19179 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19180 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19181 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19182 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19183 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19184 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19185 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19186 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19187 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19188 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19189 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19190 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19191 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19192 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19193 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19194 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19195 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19196 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19197 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19198 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19199 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19200 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19201 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19202 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19203 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19204 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19205 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19206 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19207 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19208 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19209 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19210 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19211 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19212 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19213 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19214 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19215 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19216 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19217 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19218 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19219 (org-defkey org-mode-map "\C-c^" 'org-sort)
19220 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19221 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19222 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19223 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19224 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19225 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19226 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19227 (org-defkey org-mode-map "\C-m" 'org-return)
19228 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19229 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19230 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19231 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19232 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19233 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19234 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19235 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19236 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19237 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19238 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19239 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19240 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19241 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19242 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
19243 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19244 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19245 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19246 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19247 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19248 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19249 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19250 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19252 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19253 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19254 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19256 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19257 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19258 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19259 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19260 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19261 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19262 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19263 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19264 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19265 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19266 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
19267 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19268 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19269 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19270 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19271 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19272 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19273 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19274 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19275 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19276 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19277 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19278 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19280 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19281 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19282 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19283 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19284 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19286 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19288 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19290 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19291 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19293 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19296 (when (featurep 'xemacs)
19297 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19300 (defconst org-speed-commands-default
19302 ("Outline Navigation")
19303 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19304 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19305 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19306 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19307 ("F" . org-next-block)
19308 ("B" . org-previous-block)
19309 ("u" . (org-speed-move-safe 'outline-up-heading))
19310 ("j" . org-goto)
19311 ("g" . (org-refile t))
19312 ("Outline Visibility")
19313 ("c" . org-cycle)
19314 ("C" . org-shifttab)
19315 (" " . org-display-outline-path)
19316 ("s" . org-narrow-to-subtree)
19317 ("=" . org-columns)
19318 ("Outline Structure Editing")
19319 ("U" . org-shiftmetaup)
19320 ("D" . org-shiftmetadown)
19321 ("r" . org-metaright)
19322 ("l" . org-metaleft)
19323 ("R" . org-shiftmetaright)
19324 ("L" . org-shiftmetaleft)
19325 ("i" . (progn (forward-char 1) (call-interactively
19326 'org-insert-heading-respect-content)))
19327 ("^" . org-sort)
19328 ("w" . org-refile)
19329 ("a" . org-archive-subtree-default-with-confirmation)
19330 ("@" . org-mark-subtree)
19331 ("#" . org-toggle-comment)
19332 ("Clock Commands")
19333 ("I" . org-clock-in)
19334 ("O" . org-clock-out)
19335 ("Meta Data Editing")
19336 ("t" . org-todo)
19337 ("," . (org-priority))
19338 ("0" . (org-priority ?\ ))
19339 ("1" . (org-priority ?A))
19340 ("2" . (org-priority ?B))
19341 ("3" . (org-priority ?C))
19342 (":" . org-set-tags-command)
19343 ("e" . org-set-effort)
19344 ("E" . org-inc-effort)
19345 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19346 (org-entry-put (point) "APPT_WARNTIME" m)))
19347 ("Agenda Views etc")
19348 ("v" . org-agenda)
19349 ("/" . org-sparse-tree)
19350 ("Misc")
19351 ("o" . org-open-at-point)
19352 ("?" . org-speed-command-help)
19353 ("<" . (org-agenda-set-restriction-lock 'subtree))
19354 (">" . (org-agenda-remove-restriction-lock))
19356 "The default speed commands.")
19358 (defun org-print-speed-command (e)
19359 (if (> (length (car e)) 1)
19360 (progn
19361 (princ "\n")
19362 (princ (car e))
19363 (princ "\n")
19364 (princ (make-string (length (car e)) ?-))
19365 (princ "\n"))
19366 (princ (car e))
19367 (princ " ")
19368 (if (symbolp (cdr e))
19369 (princ (symbol-name (cdr e)))
19370 (prin1 (cdr e)))
19371 (princ "\n")))
19373 (defun org-speed-command-help ()
19374 "Show the available speed commands."
19375 (interactive)
19376 (if (not org-use-speed-commands)
19377 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19378 (with-output-to-temp-buffer "*Help*"
19379 (princ "User-defined Speed commands\n===========================\n")
19380 (mapc 'org-print-speed-command org-speed-commands-user)
19381 (princ "\n")
19382 (princ "Built-in Speed commands\n=======================\n")
19383 (mapc 'org-print-speed-command org-speed-commands-default))
19384 (with-current-buffer "*Help*"
19385 (setq truncate-lines t))))
19387 (defun org-speed-move-safe (cmd)
19388 "Execute CMD, but make sure that the cursor always ends up in a headline.
19389 If not, return to the original position and throw an error."
19390 (interactive)
19391 (let ((pos (point)))
19392 (call-interactively cmd)
19393 (unless (and (bolp) (org-at-heading-p))
19394 (goto-char pos)
19395 (error "Boundary reached while executing %s" cmd))))
19397 (defvar org-self-insert-command-undo-counter 0)
19399 (defvar org-table-auto-blank-field) ; defined in org-table.el
19400 (defvar org-speed-command nil)
19402 (define-obsolete-function-alias
19403 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19405 (defun org-speed-command-activate (keys)
19406 "Hook for activating single-letter speed commands.
19407 `org-speed-commands-default' specifies a minimal command set.
19408 Use `org-speed-commands-user' for further customization."
19409 (when (or (and (bolp) (looking-at org-outline-regexp))
19410 (and (functionp org-use-speed-commands)
19411 (funcall org-use-speed-commands)))
19412 (cdr (assoc keys (append org-speed-commands-user
19413 org-speed-commands-default)))))
19415 (define-obsolete-function-alias
19416 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19418 (defun org-babel-speed-command-activate (keys)
19419 "Hook for activating single-letter code block commands."
19420 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19421 (cdr (assoc keys org-babel-key-bindings))))
19423 (defcustom org-speed-command-hook
19424 '(org-speed-command-default-hook org-babel-speed-command-hook)
19425 "Hook for activating speed commands at strategic locations.
19426 Hook functions are called in sequence until a valid handler is
19427 found.
19429 Each hook takes a single argument, a user-pressed command key
19430 which is also a `self-insert-command' from the global map.
19432 Within the hook, examine the cursor position and the command key
19433 and return nil or a valid handler as appropriate. Handler could
19434 be one of an interactive command, a function, or a form.
19436 Set `org-use-speed-commands' to non-nil value to enable this
19437 hook. The default setting is `org-speed-command-activate'."
19438 :group 'org-structure
19439 :version "24.1"
19440 :type 'hook)
19442 (defun org-self-insert-command (N)
19443 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19444 If the cursor is in a table looking at whitespace, the whitespace is
19445 overwritten, and the table is not marked as requiring realignment."
19446 (interactive "p")
19447 (org-check-before-invisible-edit 'insert)
19448 (cond
19449 ((and org-use-speed-commands
19450 (setq org-speed-command
19451 (run-hook-with-args-until-success
19452 'org-speed-command-hook (this-command-keys))))
19453 (cond
19454 ((commandp org-speed-command)
19455 (setq this-command org-speed-command)
19456 (call-interactively org-speed-command))
19457 ((functionp org-speed-command)
19458 (funcall org-speed-command))
19459 ((and org-speed-command (listp org-speed-command))
19460 (eval org-speed-command))
19461 (t (let (org-use-speed-commands)
19462 (call-interactively 'org-self-insert-command)))))
19463 ((and
19464 (org-table-p)
19465 (progn
19466 ;; check if we blank the field, and if that triggers align
19467 (and (featurep 'org-table) org-table-auto-blank-field
19468 (member last-command
19469 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19470 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19471 ;; got extra space, this field does not determine column width
19472 (let (org-table-may-need-update) (org-table-blank-field))
19473 ;; no extra space, this field may determine column width
19474 (org-table-blank-field)))
19476 (eq N 1)
19477 (looking-at "[^|\n]* |"))
19478 (let (org-table-may-need-update)
19479 (goto-char (1- (match-end 0)))
19480 (backward-delete-char 1)
19481 (goto-char (match-beginning 0))
19482 (self-insert-command N)))
19484 (setq org-table-may-need-update t)
19485 (self-insert-command N)
19486 (org-fix-tags-on-the-fly)
19487 (if org-self-insert-cluster-for-undo
19488 (if (not (eq last-command 'org-self-insert-command))
19489 (setq org-self-insert-command-undo-counter 1)
19490 (if (>= org-self-insert-command-undo-counter 20)
19491 (setq org-self-insert-command-undo-counter 1)
19492 (and (> org-self-insert-command-undo-counter 0)
19493 buffer-undo-list (listp buffer-undo-list)
19494 (not (cadr buffer-undo-list)) ; remove nil entry
19495 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19496 (setq org-self-insert-command-undo-counter
19497 (1+ org-self-insert-command-undo-counter))))))))
19499 (defun org-check-before-invisible-edit (kind)
19500 "Check is editing if kind KIND would be dangerous with invisible text around.
19501 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19502 ;; First, try to get out of here as quickly as possible, to reduce overhead
19503 (if (and org-catch-invisible-edits
19504 (or (not (boundp 'visible-mode)) (not visible-mode))
19505 (or (get-char-property (point) 'invisible)
19506 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19507 ;; OK, we need to take a closer look
19508 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19509 (invisible-before-point (if (bobp) nil (get-char-property
19510 (1- (point)) 'invisible)))
19511 (border-and-ok-direction
19513 ;; Check if we are acting predictably before invisible text
19514 (and invisible-at-point (not invisible-before-point)
19515 (memq kind '(insert delete-backward)))
19516 ;; Check if we are acting predictably after invisible text
19517 ;; This works not well, and I have turned it off. It seems
19518 ;; better to always show and stop after invisible text.
19519 ;; (and (not invisible-at-point) invisible-before-point
19520 ;; (memq kind '(insert delete)))
19522 (when (or (memq invisible-at-point '(outline org-hide-block t))
19523 (memq invisible-before-point '(outline org-hide-block t)))
19524 (if (eq org-catch-invisible-edits 'error)
19525 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19526 (if (and org-custom-properties-overlays
19527 (y-or-n-p "Display invisible properties in this buffer? "))
19528 (org-toggle-custom-properties-visibility)
19529 ;; Make the area visible
19530 (save-excursion
19531 (if invisible-before-point
19532 (goto-char (previous-single-char-property-change
19533 (point) 'invisible)))
19534 (org-cycle))
19535 (cond
19536 ((eq org-catch-invisible-edits 'show)
19537 ;; That's it, we do the edit after showing
19538 (message
19539 "Unfolding invisible region around point before editing")
19540 (sit-for 1))
19541 ((and (eq org-catch-invisible-edits 'smart)
19542 border-and-ok-direction)
19543 (message "Unfolding invisible region around point before editing"))
19545 ;; Don't do the edit, make the user repeat it in full visibility
19546 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19548 (defun org-fix-tags-on-the-fly ()
19549 (when (and (equal (char-after (point-at-bol)) ?*)
19550 (org-at-heading-p))
19551 (org-align-tags-here org-tags-column)))
19553 (defun org-delete-backward-char (N)
19554 "Like `delete-backward-char', insert whitespace at field end in tables.
19555 When deleting backwards, in tables this function will insert whitespace in
19556 front of the next \"|\" separator, to keep the table aligned. The table will
19557 still be marked for re-alignment if the field did fill the entire column,
19558 because, in this case the deletion might narrow the column."
19559 (interactive "p")
19560 (save-match-data
19561 (org-check-before-invisible-edit 'delete-backward)
19562 (if (and (org-table-p)
19563 (eq N 1)
19564 (string-match "|" (buffer-substring (point-at-bol) (point)))
19565 (looking-at ".*?|"))
19566 (let ((pos (point))
19567 (noalign (looking-at "[^|\n\r]* |"))
19568 (c org-table-may-need-update))
19569 (backward-delete-char N)
19570 (if (not overwrite-mode)
19571 (progn
19572 (skip-chars-forward "^|")
19573 (insert " ")
19574 (goto-char (1- pos))))
19575 ;; noalign: if there were two spaces at the end, this field
19576 ;; does not determine the width of the column.
19577 (if noalign (setq org-table-may-need-update c)))
19578 (backward-delete-char N)
19579 (org-fix-tags-on-the-fly))))
19581 (defun org-delete-char (N)
19582 "Like `delete-char', but insert whitespace at field end in tables.
19583 When deleting characters, in tables this function will insert whitespace in
19584 front of the next \"|\" separator, to keep the table aligned. The table will
19585 still be marked for re-alignment if the field did fill the entire column,
19586 because, in this case the deletion might narrow the column."
19587 (interactive "p")
19588 (save-match-data
19589 (org-check-before-invisible-edit 'delete)
19590 (if (and (org-table-p)
19591 (not (bolp))
19592 (not (= (char-after) ?|))
19593 (eq N 1))
19594 (if (looking-at ".*?|")
19595 (let ((pos (point))
19596 (noalign (looking-at "[^|\n\r]* |"))
19597 (c org-table-may-need-update))
19598 (replace-match
19599 (concat (substring (match-string 0) 1 -1) " |") nil t)
19600 (goto-char pos)
19601 ;; noalign: if there were two spaces at the end, this field
19602 ;; does not determine the width of the column.
19603 (if noalign (setq org-table-may-need-update c)))
19604 (delete-char N))
19605 (delete-char N)
19606 (org-fix-tags-on-the-fly))))
19608 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19609 (put 'org-self-insert-command 'delete-selection
19610 (lambda ()
19611 (not (run-hook-with-args-until-success
19612 'self-insert-uses-region-functions))))
19613 (put 'orgtbl-self-insert-command 'delete-selection
19614 (lambda ()
19615 (not (run-hook-with-args-until-success
19616 'self-insert-uses-region-functions))))
19617 (put 'org-delete-char 'delete-selection 'supersede)
19618 (put 'org-delete-backward-char 'delete-selection 'supersede)
19619 (put 'org-yank 'delete-selection 'yank)
19621 ;; Make `flyspell-mode' delay after some commands
19622 (put 'org-self-insert-command 'flyspell-delayed t)
19623 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19624 (put 'org-delete-char 'flyspell-delayed t)
19625 (put 'org-delete-backward-char 'flyspell-delayed t)
19627 ;; Make pabbrev-mode expand after org-mode commands
19628 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19629 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19631 (defun org-remap (map &rest commands)
19632 "In MAP, remap the functions given in COMMANDS.
19633 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19634 (let (new old)
19635 (while commands
19636 (setq old (pop commands) new (pop commands))
19637 (if (fboundp 'command-remapping)
19638 (org-defkey map (vector 'remap old) new)
19639 (substitute-key-definition old new map global-map)))))
19641 (defun org-transpose-words ()
19642 "Transpose words for Org.
19643 This uses the `org-mode-transpose-word-syntax-table' syntax
19644 table, which interprets characters in `org-emphasis-alist' as
19645 word constituents."
19646 (interactive)
19647 (with-syntax-table org-mode-transpose-word-syntax-table
19648 (call-interactively 'transpose-words)))
19649 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19651 (when (eq org-enable-table-editor 'optimized)
19652 ;; If the user wants maximum table support, we need to hijack
19653 ;; some standard editing functions
19654 (org-remap org-mode-map
19655 'self-insert-command 'org-self-insert-command
19656 'delete-char 'org-delete-char
19657 'delete-backward-char 'org-delete-backward-char)
19658 (org-defkey org-mode-map "|" 'org-force-self-insert))
19660 (defvar org-ctrl-c-ctrl-c-hook nil
19661 "Hook for functions attaching themselves to `C-c C-c'.
19663 This can be used to add additional functionality to the C-c C-c
19664 key which executes context-dependent commands. This hook is run
19665 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19666 run after the last test.
19668 Each function will be called with no arguments. The function
19669 must check if the context is appropriate for it to act. If yes,
19670 it should do its thing and then return a non-nil value. If the
19671 context is wrong, just do nothing and return nil.")
19673 (defvar org-ctrl-c-ctrl-c-final-hook nil
19674 "Hook for functions attaching themselves to `C-c C-c'.
19676 This can be used to add additional functionality to the C-c C-c
19677 key which executes context-dependent commands. This hook is run
19678 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19679 before the first test.
19681 Each function will be called with no arguments. The function
19682 must check if the context is appropriate for it to act. If yes,
19683 it should do its thing and then return a non-nil value. If the
19684 context is wrong, just do nothing and return nil.")
19686 (defvar org-tab-first-hook nil
19687 "Hook for functions to attach themselves to TAB.
19688 See `org-ctrl-c-ctrl-c-hook' for more information.
19689 This hook runs as the first action when TAB is pressed, even before
19690 `org-cycle' messes around with the `outline-regexp' to cater for
19691 inline tasks and plain list item folding.
19692 If any function in this hook returns t, any other actions that
19693 would have been caused by TAB (such as table field motion or visibility
19694 cycling) will not occur.")
19696 (defvar org-tab-after-check-for-table-hook nil
19697 "Hook for functions to attach themselves to TAB.
19698 See `org-ctrl-c-ctrl-c-hook' for more information.
19699 This hook runs after it has been established that the cursor is not in a
19700 table, but before checking if the cursor is in a headline or if global cycling
19701 should be done.
19702 If any function in this hook returns t, not other actions like visibility
19703 cycling will be done.")
19705 (defvar org-tab-after-check-for-cycling-hook nil
19706 "Hook for functions to attach themselves to TAB.
19707 See `org-ctrl-c-ctrl-c-hook' for more information.
19708 This hook runs after it has been established that not table field motion and
19709 not visibility should be done because of current context. This is probably
19710 the place where a package like yasnippets can hook in.")
19712 (defvar org-tab-before-tab-emulation-hook nil
19713 "Hook for functions to attach themselves to TAB.
19714 See `org-ctrl-c-ctrl-c-hook' for more information.
19715 This hook runs after every other options for TAB have been exhausted, but
19716 before indentation and \t insertion takes place.")
19718 (defvar org-metaleft-hook nil
19719 "Hook for functions attaching themselves to `M-left'.
19720 See `org-ctrl-c-ctrl-c-hook' for more information.")
19721 (defvar org-metaright-hook nil
19722 "Hook for functions attaching themselves to `M-right'.
19723 See `org-ctrl-c-ctrl-c-hook' for more information.")
19724 (defvar org-metaup-hook nil
19725 "Hook for functions attaching themselves to `M-up'.
19726 See `org-ctrl-c-ctrl-c-hook' for more information.")
19727 (defvar org-metadown-hook nil
19728 "Hook for functions attaching themselves to `M-down'.
19729 See `org-ctrl-c-ctrl-c-hook' for more information.")
19730 (defvar org-shiftmetaleft-hook nil
19731 "Hook for functions attaching themselves to `M-S-left'.
19732 See `org-ctrl-c-ctrl-c-hook' for more information.")
19733 (defvar org-shiftmetaright-hook nil
19734 "Hook for functions attaching themselves to `M-S-right'.
19735 See `org-ctrl-c-ctrl-c-hook' for more information.")
19736 (defvar org-shiftmetaup-hook nil
19737 "Hook for functions attaching themselves to `M-S-up'.
19738 See `org-ctrl-c-ctrl-c-hook' for more information.")
19739 (defvar org-shiftmetadown-hook nil
19740 "Hook for functions attaching themselves to `M-S-down'.
19741 See `org-ctrl-c-ctrl-c-hook' for more information.")
19742 (defvar org-metareturn-hook nil
19743 "Hook for functions attaching themselves to `M-RET'.
19744 See `org-ctrl-c-ctrl-c-hook' for more information.")
19745 (defvar org-shiftup-hook nil
19746 "Hook for functions attaching themselves to `S-up'.
19747 See `org-ctrl-c-ctrl-c-hook' for more information.")
19748 (defvar org-shiftup-final-hook nil
19749 "Hook for functions attaching themselves to `S-up'.
19750 This one runs after all other options except shift-select have been excluded.
19751 See `org-ctrl-c-ctrl-c-hook' for more information.")
19752 (defvar org-shiftdown-hook nil
19753 "Hook for functions attaching themselves to `S-down'.
19754 See `org-ctrl-c-ctrl-c-hook' for more information.")
19755 (defvar org-shiftdown-final-hook nil
19756 "Hook for functions attaching themselves to `S-down'.
19757 This one runs after all other options except shift-select have been excluded.
19758 See `org-ctrl-c-ctrl-c-hook' for more information.")
19759 (defvar org-shiftleft-hook nil
19760 "Hook for functions attaching themselves to `S-left'.
19761 See `org-ctrl-c-ctrl-c-hook' for more information.")
19762 (defvar org-shiftleft-final-hook nil
19763 "Hook for functions attaching themselves to `S-left'.
19764 This one runs after all other options except shift-select have been excluded.
19765 See `org-ctrl-c-ctrl-c-hook' for more information.")
19766 (defvar org-shiftright-hook nil
19767 "Hook for functions attaching themselves to `S-right'.
19768 See `org-ctrl-c-ctrl-c-hook' for more information.")
19769 (defvar org-shiftright-final-hook nil
19770 "Hook for functions attaching themselves to `S-right'.
19771 This one runs after all other options except shift-select have been excluded.
19772 See `org-ctrl-c-ctrl-c-hook' for more information.")
19774 (defun org-modifier-cursor-error ()
19775 "Throw an error, a modified cursor command was applied in wrong context."
19776 (user-error "This command is active in special context like tables, headlines or items"))
19778 (defun org-shiftselect-error ()
19779 "Throw an error because Shift-Cursor command was applied in wrong context."
19780 (if (and (boundp 'shift-select-mode) shift-select-mode)
19781 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19782 (user-error "This command works only in special context like headlines or timestamps")))
19784 (defun org-call-for-shift-select (cmd)
19785 (let ((this-command-keys-shift-translated t))
19786 (call-interactively cmd)))
19788 (defun org-shifttab (&optional arg)
19789 "Global visibility cycling or move to previous table field.
19790 Call `org-table-previous-field' within a table.
19791 When ARG is nil, cycle globally through visibility states.
19792 When ARG is a numeric prefix, show contents of this level."
19793 (interactive "P")
19794 (cond
19795 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19796 ((integerp arg)
19797 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19798 (message "Content view to level: %d" arg)
19799 (org-content (prefix-numeric-value arg2))
19800 (org-cycle-show-empty-lines t)
19801 (setq org-cycle-global-status 'overview)))
19802 (t (call-interactively 'org-global-cycle))))
19804 (defun org-shiftmetaleft ()
19805 "Promote subtree or delete table column.
19806 Calls `org-promote-subtree', `org-outdent-item-tree', or
19807 `org-table-delete-column', depending on context. See the
19808 individual commands for more information."
19809 (interactive)
19810 (cond
19811 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19812 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19813 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19814 ((if (not (org-region-active-p)) (org-at-item-p)
19815 (save-excursion (goto-char (region-beginning))
19816 (org-at-item-p)))
19817 (call-interactively 'org-outdent-item-tree))
19818 (t (org-modifier-cursor-error))))
19820 (defun org-shiftmetaright ()
19821 "Demote subtree or insert table column.
19822 Calls `org-demote-subtree', `org-indent-item-tree', or
19823 `org-table-insert-column', depending on context. See the
19824 individual commands for more information."
19825 (interactive)
19826 (cond
19827 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19828 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19829 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19830 ((if (not (org-region-active-p)) (org-at-item-p)
19831 (save-excursion (goto-char (region-beginning))
19832 (org-at-item-p)))
19833 (call-interactively 'org-indent-item-tree))
19834 (t (org-modifier-cursor-error))))
19836 (defun org-shiftmetaup (&optional arg)
19837 "Move subtree up or kill table row.
19838 Calls `org-move-subtree-up' or `org-table-kill-row' or
19839 `org-move-item-up' or `org-timestamp-up', depending on context.
19840 See the individual commands for more information."
19841 (interactive "P")
19842 (cond
19843 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19844 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19845 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19846 ((org-at-item-p) (call-interactively 'org-move-item-up))
19847 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19848 (call-interactively 'org-timestamp-up)))
19849 (t (call-interactively 'org-drag-line-backward))))
19851 (defun org-shiftmetadown (&optional arg)
19852 "Move subtree down or insert table row.
19853 Calls `org-move-subtree-down' or `org-table-insert-row' or
19854 `org-move-item-down' or `org-timestamp-up', depending on context.
19855 See the individual commands for more information."
19856 (interactive "P")
19857 (cond
19858 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19859 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19860 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19861 ((org-at-item-p) (call-interactively 'org-move-item-down))
19862 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19863 (call-interactively 'org-timestamp-down)))
19864 (t (call-interactively 'org-drag-line-forward))))
19866 (defsubst org-hidden-tree-error ()
19867 (user-error
19868 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19870 (defun org-metaleft (&optional arg)
19871 "Promote heading or move table column to left.
19872 Calls `org-do-promote' or `org-table-move-column', depending on context.
19873 With no specific context, calls the Emacs default `backward-word'.
19874 See the individual commands for more information."
19875 (interactive "P")
19876 (cond
19877 ((run-hook-with-args-until-success 'org-metaleft-hook))
19878 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19879 ((org-with-limited-levels
19880 (or (org-at-heading-p)
19881 (and (org-region-active-p)
19882 (save-excursion
19883 (goto-char (region-beginning))
19884 (org-at-heading-p)))))
19885 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19886 (call-interactively 'org-do-promote))
19887 ;; At an inline task.
19888 ((org-at-heading-p)
19889 (call-interactively 'org-inlinetask-promote))
19890 ((or (org-at-item-p)
19891 (and (org-region-active-p)
19892 (save-excursion
19893 (goto-char (region-beginning))
19894 (org-at-item-p))))
19895 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19896 (call-interactively 'org-outdent-item))
19897 (t (call-interactively 'backward-word))))
19899 (defun org-metaright (&optional arg)
19900 "Demote a subtree, a list item or move table column to right.
19901 In front of a drawer or a block keyword, indent it correctly.
19902 With no specific context, calls the Emacs default `forward-word'.
19903 See the individual commands for more information."
19904 (interactive "P")
19905 (cond
19906 ((run-hook-with-args-until-success 'org-metaright-hook))
19907 ((org-at-table-p) (call-interactively 'org-table-move-column))
19908 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19909 ((org-at-block-p) (call-interactively 'org-indent-block))
19910 ((org-with-limited-levels
19911 (or (org-at-heading-p)
19912 (and (org-region-active-p)
19913 (save-excursion
19914 (goto-char (region-beginning))
19915 (org-at-heading-p)))))
19916 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19917 (call-interactively 'org-do-demote))
19918 ;; At an inline task.
19919 ((org-at-heading-p)
19920 (call-interactively 'org-inlinetask-demote))
19921 ((or (org-at-item-p)
19922 (and (org-region-active-p)
19923 (save-excursion
19924 (goto-char (region-beginning))
19925 (org-at-item-p))))
19926 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19927 (call-interactively 'org-indent-item))
19928 (t (call-interactively 'forward-word))))
19930 (defun org-check-for-hidden (what)
19931 "Check if there are hidden headlines/items in the current visual line.
19932 WHAT can be either `headlines' or `items'. If the current line is
19933 an outline or item heading and it has a folded subtree below it,
19934 this function returns t, nil otherwise."
19935 (let ((re (cond
19936 ((eq what 'headlines) org-outline-regexp-bol)
19937 ((eq what 'items) (org-item-beginning-re))
19938 (t (error "This should not happen"))))
19939 beg end)
19940 (save-excursion
19941 (catch 'exit
19942 (unless (org-region-active-p)
19943 (setq beg (point-at-bol))
19944 (beginning-of-line 2)
19945 (while (and (not (eobp)) ;; this is like `next-line'
19946 (get-char-property (1- (point)) 'invisible))
19947 (beginning-of-line 2))
19948 (setq end (point))
19949 (goto-char beg)
19950 (goto-char (point-at-eol))
19951 (setq end (max end (point)))
19952 (while (re-search-forward re end t)
19953 (if (get-char-property (match-beginning 0) 'invisible)
19954 (throw 'exit t))))
19955 nil))))
19957 (defun org-metaup (&optional arg)
19958 "Move subtree up or move table row up.
19959 Calls `org-move-subtree-up' or `org-table-move-row' or
19960 `org-move-item-up', depending on context. See the individual commands
19961 for more information."
19962 (interactive "P")
19963 (cond
19964 ((run-hook-with-args-until-success 'org-metaup-hook))
19965 ((org-region-active-p)
19966 (let* ((a (min (region-beginning) (region-end)))
19967 (b (1- (max (region-beginning) (region-end))))
19968 (c (save-excursion (goto-char a)
19969 (move-beginning-of-line 0)))
19970 (d (save-excursion (goto-char a)
19971 (move-end-of-line 0) (point))))
19972 (transpose-regions a b c d)
19973 (goto-char c)))
19974 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19975 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19976 ((org-at-item-p) (call-interactively 'org-move-item-up))
19977 (t (org-drag-element-backward))))
19979 (defun org-metadown (&optional arg)
19980 "Move subtree down or move table row down.
19981 Calls `org-move-subtree-down' or `org-table-move-row' or
19982 `org-move-item-down', depending on context. See the individual
19983 commands for more information."
19984 (interactive "P")
19985 (cond
19986 ((run-hook-with-args-until-success 'org-metadown-hook))
19987 ((org-region-active-p)
19988 (let* ((a (min (region-beginning) (region-end)))
19989 (b (max (region-beginning) (region-end)))
19990 (c (save-excursion (goto-char b)
19991 (move-beginning-of-line 1)))
19992 (d (save-excursion (goto-char b)
19993 (move-end-of-line 1) (1+ (point)))))
19994 (transpose-regions a b c d)
19995 (goto-char d)))
19996 ((org-at-table-p) (call-interactively 'org-table-move-row))
19997 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19998 ((org-at-item-p) (call-interactively 'org-move-item-down))
19999 (t (org-drag-element-forward))))
20001 (defun org-shiftup (&optional arg)
20002 "Increase item in timestamp or increase priority of current headline.
20003 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20004 depending on context. See the individual commands for more information."
20005 (interactive "P")
20006 (cond
20007 ((run-hook-with-args-until-success 'org-shiftup-hook))
20008 ((and org-support-shift-select (org-region-active-p))
20009 (org-call-for-shift-select 'previous-line))
20010 ((org-at-timestamp-p t)
20011 (call-interactively (if org-edit-timestamp-down-means-later
20012 'org-timestamp-down 'org-timestamp-up)))
20013 ((and (not (eq org-support-shift-select 'always))
20014 org-enable-priority-commands
20015 (org-at-heading-p))
20016 (call-interactively 'org-priority-up))
20017 ((and (not org-support-shift-select) (org-at-item-p))
20018 (call-interactively 'org-previous-item))
20019 ((org-clocktable-try-shift 'up arg))
20020 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20021 (org-support-shift-select
20022 (org-call-for-shift-select 'previous-line))
20023 (t (org-shiftselect-error))))
20025 (defun org-shiftdown (&optional arg)
20026 "Decrease item in timestamp or decrease priority of current headline.
20027 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20028 depending on context. See the individual commands for more information."
20029 (interactive "P")
20030 (cond
20031 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20032 ((and org-support-shift-select (org-region-active-p))
20033 (org-call-for-shift-select 'next-line))
20034 ((org-at-timestamp-p t)
20035 (call-interactively (if org-edit-timestamp-down-means-later
20036 'org-timestamp-up 'org-timestamp-down)))
20037 ((and (not (eq org-support-shift-select 'always))
20038 org-enable-priority-commands
20039 (org-at-heading-p))
20040 (call-interactively 'org-priority-down))
20041 ((and (not org-support-shift-select) (org-at-item-p))
20042 (call-interactively 'org-next-item))
20043 ((org-clocktable-try-shift 'down arg))
20044 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20045 (org-support-shift-select
20046 (org-call-for-shift-select 'next-line))
20047 (t (org-shiftselect-error))))
20049 (defun org-shiftright (&optional arg)
20050 "Cycle the thing at point or in the current line, depending on context.
20051 Depending on context, this does one of the following:
20053 - switch a timestamp at point one day into the future
20054 - on a headline, switch to the next TODO keyword.
20055 - on an item, switch entire list to the next bullet type
20056 - on a property line, switch to the next allowed value
20057 - on a clocktable definition line, move time block into the future"
20058 (interactive "P")
20059 (cond
20060 ((run-hook-with-args-until-success 'org-shiftright-hook))
20061 ((and org-support-shift-select (org-region-active-p))
20062 (org-call-for-shift-select 'forward-char))
20063 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20064 ((and (not (eq org-support-shift-select 'always))
20065 (org-at-heading-p))
20066 (let ((org-inhibit-logging
20067 (not org-treat-S-cursor-todo-selection-as-state-change))
20068 (org-inhibit-blocking
20069 (not org-treat-S-cursor-todo-selection-as-state-change)))
20070 (org-call-with-arg 'org-todo 'right)))
20071 ((or (and org-support-shift-select
20072 (not (eq org-support-shift-select 'always))
20073 (org-at-item-bullet-p))
20074 (and (not org-support-shift-select) (org-at-item-p)))
20075 (org-call-with-arg 'org-cycle-list-bullet nil))
20076 ((and (not (eq org-support-shift-select 'always))
20077 (org-at-property-p))
20078 (call-interactively 'org-property-next-allowed-value))
20079 ((org-clocktable-try-shift 'right arg))
20080 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20081 (org-support-shift-select
20082 (org-call-for-shift-select 'forward-char))
20083 (t (org-shiftselect-error))))
20085 (defun org-shiftleft (&optional arg)
20086 "Cycle the thing at point or in the current line, depending on context.
20087 Depending on context, this does one of the following:
20089 - switch a timestamp at point one day into the past
20090 - on a headline, switch to the previous TODO keyword.
20091 - on an item, switch entire list to the previous bullet type
20092 - on a property line, switch to the previous allowed value
20093 - on a clocktable definition line, move time block into the past"
20094 (interactive "P")
20095 (cond
20096 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20097 ((and org-support-shift-select (org-region-active-p))
20098 (org-call-for-shift-select 'backward-char))
20099 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20100 ((and (not (eq org-support-shift-select 'always))
20101 (org-at-heading-p))
20102 (let ((org-inhibit-logging
20103 (not org-treat-S-cursor-todo-selection-as-state-change))
20104 (org-inhibit-blocking
20105 (not org-treat-S-cursor-todo-selection-as-state-change)))
20106 (org-call-with-arg 'org-todo 'left)))
20107 ((or (and org-support-shift-select
20108 (not (eq org-support-shift-select 'always))
20109 (org-at-item-bullet-p))
20110 (and (not org-support-shift-select) (org-at-item-p)))
20111 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20112 ((and (not (eq org-support-shift-select 'always))
20113 (org-at-property-p))
20114 (call-interactively 'org-property-previous-allowed-value))
20115 ((org-clocktable-try-shift 'left arg))
20116 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20117 (org-support-shift-select
20118 (org-call-for-shift-select 'backward-char))
20119 (t (org-shiftselect-error))))
20121 (defun org-shiftcontrolright ()
20122 "Switch to next TODO set."
20123 (interactive)
20124 (cond
20125 ((and org-support-shift-select (org-region-active-p))
20126 (org-call-for-shift-select 'forward-word))
20127 ((and (not (eq org-support-shift-select 'always))
20128 (org-at-heading-p))
20129 (org-call-with-arg 'org-todo 'nextset))
20130 (org-support-shift-select
20131 (org-call-for-shift-select 'forward-word))
20132 (t (org-shiftselect-error))))
20134 (defun org-shiftcontrolleft ()
20135 "Switch to previous TODO set."
20136 (interactive)
20137 (cond
20138 ((and org-support-shift-select (org-region-active-p))
20139 (org-call-for-shift-select 'backward-word))
20140 ((and (not (eq org-support-shift-select 'always))
20141 (org-at-heading-p))
20142 (org-call-with-arg 'org-todo 'previousset))
20143 (org-support-shift-select
20144 (org-call-for-shift-select 'backward-word))
20145 (t (org-shiftselect-error))))
20147 (defun org-shiftcontrolup (&optional n)
20148 "Change timestamps synchronously up in CLOCK log lines.
20149 Optional argument N tells to change by that many units."
20150 (interactive "P")
20151 (cond ((and (not org-support-shift-select)
20152 (org-at-clock-log-p)
20153 (org-at-timestamp-p t))
20154 (org-clock-timestamps-up n))
20155 (t (org-shiftselect-error))))
20157 (defun org-shiftcontroldown (&optional n)
20158 "Change timestamps synchronously down in CLOCK log lines.
20159 Optional argument N tells to change by that many units."
20160 (interactive "P")
20161 (cond ((and (not org-support-shift-select)
20162 (org-at-clock-log-p)
20163 (org-at-timestamp-p t))
20164 (org-clock-timestamps-down n))
20165 (t (org-shiftselect-error))))
20167 (defun org-ctrl-c-ret ()
20168 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20169 (interactive)
20170 (cond
20171 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20172 (t (call-interactively 'org-insert-heading))))
20174 (defun org-find-visible ()
20175 (let ((s (point)))
20176 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20177 (get-char-property s 'invisible)))
20179 (defun org-find-invisible ()
20180 (let ((s (point)))
20181 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20182 (not (get-char-property s 'invisible))))
20185 (defun org-copy-visible (beg end)
20186 "Copy the visible parts of the region."
20187 (interactive "r")
20188 (let (snippets s)
20189 (save-excursion
20190 (save-restriction
20191 (narrow-to-region beg end)
20192 (setq s (goto-char (point-min)))
20193 (while (not (= (point) (point-max)))
20194 (goto-char (org-find-invisible))
20195 (push (buffer-substring s (point)) snippets)
20196 (setq s (goto-char (org-find-visible))))))
20197 (kill-new (apply 'concat (nreverse snippets)))))
20199 (defun org-copy-special ()
20200 "Copy region in table or copy current subtree.
20201 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20202 See the individual commands for more information."
20203 (interactive)
20204 (call-interactively
20205 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20207 (defun org-cut-special ()
20208 "Cut region in table or cut current subtree.
20209 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20210 See the individual commands for more information."
20211 (interactive)
20212 (call-interactively
20213 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20215 (defun org-paste-special (arg)
20216 "Paste rectangular region into table, or past subtree relative to level.
20217 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20218 See the individual commands for more information."
20219 (interactive "P")
20220 (if (org-at-table-p)
20221 (org-table-paste-rectangle)
20222 (org-paste-subtree arg)))
20224 (defsubst org-in-fixed-width-region-p ()
20225 "Is point in a fixed-width region?"
20226 (save-match-data
20227 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20229 (defun org-edit-special (&optional arg)
20230 "Call a special editor for the element at point.
20231 When at a table, call the formula editor with `org-table-edit-formulas'.
20232 When in a source code block, call `org-edit-src-code'.
20233 When in a fixed-width region, call `org-edit-fixed-width-region'.
20234 When at an #+INCLUDE keyword, visit the included file.
20235 On a link, call `ffap' to visit the link at point.
20236 Otherwise, return a user error."
20237 (interactive "P")
20238 (let ((element (org-element-at-point)))
20239 (assert (not buffer-read-only) nil
20240 "Buffer is read-only: %s" (buffer-name))
20241 (case (org-element-type element)
20242 (src-block
20243 (if (not arg) (org-edit-src-code)
20244 (let* ((info (org-babel-get-src-block-info))
20245 (lang (nth 0 info))
20246 (params (nth 2 info))
20247 (session (cdr (assq :session params))))
20248 (if (not session) (org-edit-src-code)
20249 ;; At a src-block with a session and function called with
20250 ;; an ARG: switch to the buffer related to the inferior
20251 ;; process.
20252 (switch-to-buffer
20253 (funcall (intern (concat "org-babel-prep-session:" lang))
20254 session params))))))
20255 (keyword
20256 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20257 (find-file
20258 (org-remove-double-quotes
20259 (car (org-split-string (org-element-property :value element)))))
20260 (user-error "No special environment to edit here")))
20261 (table
20262 (if (eq (org-element-property :type element) 'table.el)
20263 (org-edit-src-code)
20264 (call-interactively 'org-table-edit-formulas)))
20265 ;; Only Org tables contain `table-row' type elements.
20266 (table-row (call-interactively 'org-table-edit-formulas))
20267 ((example-block export-block) (org-edit-src-code))
20268 (fixed-width (org-edit-fixed-width-region))
20269 (otherwise
20270 ;; No notable element at point. Though, we may be at a link,
20271 ;; which is an object. Thus, scan deeper.
20272 (if (eq (org-element-type (org-element-context element)) 'link)
20273 (call-interactively 'ffap)
20274 (user-error "No special environment to edit here"))))))
20276 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20277 (defun org-ctrl-c-ctrl-c (&optional arg)
20278 "Set tags in headline, or update according to changed information at point.
20280 This command does many different things, depending on context:
20282 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20283 this is what we do.
20285 - If the cursor is on a statistics cookie, update it.
20287 - If the cursor is in a headline, prompt for tags and insert them
20288 into the current line, aligned to `org-tags-column'. When called
20289 with prefix arg, realign all tags in the current buffer.
20291 - If the cursor is in one of the special #+KEYWORD lines, this
20292 triggers scanning the buffer for these lines and updating the
20293 information.
20295 - If the cursor is inside a table, realign the table. This command
20296 works even if the automatic table editor has been turned off.
20298 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20299 the entire table.
20301 - If the cursor is at a footnote reference or definition, jump to
20302 the corresponding definition or references, respectively.
20304 - If the cursor is a the beginning of a dynamic block, update it.
20306 - If the current buffer is a capture buffer, close note and file it.
20308 - If the cursor is on a <<<target>>>, update radio targets and
20309 corresponding links in this buffer.
20311 - If the cursor is on a numbered item in a plain list, renumber the
20312 ordered list.
20314 - If the cursor is on a checkbox, toggle it.
20316 - If the cursor is on a code block, evaluate it. The variable
20317 `org-confirm-babel-evaluate' can be used to control prompting
20318 before code block evaluation, by default every code block
20319 evaluation requires confirmation. Code block evaluation can be
20320 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20321 (interactive "P")
20322 (cond
20323 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20324 org-occur-highlights
20325 org-latex-fragment-image-overlays)
20326 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20327 (org-remove-occur-highlights)
20328 (org-remove-latex-fragment-image-overlays)
20329 (message "Temporary highlights/overlays removed from current buffer"))
20330 ((and (local-variable-p 'org-finish-function (current-buffer))
20331 (fboundp org-finish-function))
20332 (funcall org-finish-function))
20333 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20335 (let* ((context (org-element-context)) (type (org-element-type context)))
20336 ;; Test if point is within a blank line.
20337 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20338 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20339 (user-error "C-c C-c can do nothing useful at this location"))
20340 (case type
20341 ;; When at a link, act according to the parent instead.
20342 (link (setq context (org-element-property :parent context))
20343 (setq type (org-element-type context)))
20344 ;; Unsupported object types: check parent element instead.
20345 ((bold code entity export-snippet inline-babel-call inline-src-block
20346 italic latex-fragment line-break macro strike-through subscript
20347 superscript underline verbatim)
20348 (while (and (setq context (org-element-property :parent context))
20349 (not (memq (setq type (org-element-type context))
20350 '(paragraph verse-block)))))))
20351 ;; For convenience: at the first line of a paragraph on the
20352 ;; same line as an item, apply function on that item instead.
20353 (when (eq type 'paragraph)
20354 (let ((parent (org-element-property :parent context)))
20355 (when (and (eq (org-element-type parent) 'item)
20356 (= (point-at-bol) (org-element-property :begin parent)))
20357 (setq context parent type 'item))))
20358 ;; Act according to type of element or object at point.
20359 (case type
20360 (clock (org-clock-update-time-maybe))
20361 (dynamic-block
20362 (save-excursion
20363 (goto-char (org-element-property :post-affiliated context))
20364 (org-update-dblock)))
20365 (footnote-definition
20366 (goto-char (org-element-property :post-affiliated context))
20367 (call-interactively 'org-footnote-action))
20368 (footnote-reference (call-interactively 'org-footnote-action))
20369 ((headline inlinetask)
20370 (save-excursion (goto-char (org-element-property :begin context))
20371 (call-interactively 'org-set-tags)))
20372 (item
20373 ;; At an item: a double C-u set checkbox to "[-]"
20374 ;; unconditionally, whereas a single one will toggle its
20375 ;; presence. Without an universal argument, if the item
20376 ;; has a checkbox, toggle it. Otherwise repair the list.
20377 (let* ((box (org-element-property :checkbox context))
20378 (struct (org-element-property :structure context))
20379 (old-struct (copy-tree struct))
20380 (parents (org-list-parents-alist struct))
20381 (prevs (org-list-prevs-alist struct))
20382 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20383 (org-list-set-checkbox
20384 (org-element-property :begin context) struct
20385 (cond ((equal arg '(16)) "[-]")
20386 ((and (not box) (equal arg '(4))) "[ ]")
20387 ((or (not box) (equal arg '(4))) nil)
20388 ((eq box 'on) "[ ]")
20389 (t "[X]")))
20390 ;; Mimic `org-list-write-struct' but with grabbing
20391 ;; a return value from `org-list-struct-fix-box'.
20392 (org-list-struct-fix-ind struct parents 2)
20393 (org-list-struct-fix-item-end struct)
20394 (org-list-struct-fix-bul struct prevs)
20395 (org-list-struct-fix-ind struct parents)
20396 (let ((block-item
20397 (org-list-struct-fix-box struct parents prevs orderedp)))
20398 (if (and box (equal struct old-struct))
20399 (if (equal arg '(16))
20400 (message "Checkboxes already reset")
20401 (user-error "Cannot toggle this checkbox: %s"
20402 (if (eq box 'on)
20403 "all subitems checked"
20404 "unchecked subitems")))
20405 (org-list-struct-apply-struct struct old-struct)
20406 (org-update-checkbox-count-maybe))
20407 (when block-item
20408 (message "Checkboxes were removed due to empty box at line %d"
20409 (org-current-line block-item))))))
20410 (keyword
20411 (let ((org-inhibit-startup-visibility-stuff t)
20412 (org-startup-align-all-tables nil))
20413 (when (boundp 'org-table-coordinate-overlays)
20414 (mapc 'delete-overlay org-table-coordinate-overlays)
20415 (setq org-table-coordinate-overlays nil))
20416 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20417 (message "Local setup has been refreshed"))
20418 (plain-list
20419 ;; At a plain list, with a double C-u argument, set
20420 ;; checkboxes of each item to "[-]", whereas a single one
20421 ;; will toggle their presence according to the state of the
20422 ;; first item in the list. Without an argument, repair the
20423 ;; list.
20424 (let* ((begin (org-element-property :contents-begin context))
20425 (beginm (move-marker (make-marker) begin))
20426 (struct (org-element-property :structure context))
20427 (old-struct (copy-tree struct))
20428 (first-box (save-excursion
20429 (goto-char begin)
20430 (looking-at org-list-full-item-re)
20431 (match-string-no-properties 3)))
20432 (new-box (cond ((equal arg '(16)) "[-]")
20433 ((equal arg '(4)) (unless first-box "[ ]"))
20434 ((equal first-box "[X]") "[ ]")
20435 (t "[X]"))))
20436 (cond
20437 (arg
20438 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20439 (org-list-get-all-items
20440 begin struct (org-list-prevs-alist struct))))
20441 ((and first-box (eq (point) begin))
20442 ;; For convenience, when point is at bol on the first
20443 ;; item of the list and no argument is provided, simply
20444 ;; toggle checkbox of that item, if any.
20445 (org-list-set-checkbox begin struct new-box)))
20446 (org-list-write-struct
20447 struct (org-list-parents-alist struct) old-struct)
20448 (org-update-checkbox-count-maybe)
20449 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20450 ((property-drawer node-property)
20451 (call-interactively 'org-property-action))
20452 ((radio-target target)
20453 (call-interactively 'org-update-radio-target-regexp))
20454 (statistics-cookie
20455 (call-interactively 'org-update-statistics-cookies))
20456 ((table table-cell table-row)
20457 ;; At a table, recalculate every field and align it. Also
20458 ;; send the table if necessary. If the table has
20459 ;; a `table.el' type, just give up. At a table row or
20460 ;; cell, maybe recalculate line but always align table.
20461 (if (eq (org-element-property :type context) 'table.el)
20462 (message "Use C-c ' to edit table.el tables")
20463 (let ((org-enable-table-editor t))
20464 (if (or (eq type 'table)
20465 ;; Check if point is at a TBLFM line.
20466 (and (eq type 'table-row)
20467 (= (point) (org-element-property :end context))))
20468 (save-excursion
20469 (if (org-at-TBLFM-p)
20470 (progn (require 'org-table)
20471 (org-table-calc-current-TBLFM))
20472 (goto-char (org-element-property :contents-begin context))
20473 (org-call-with-arg 'org-table-recalculate (or arg t))
20474 (orgtbl-send-table 'maybe)))
20475 (org-table-maybe-eval-formula)
20476 (cond (arg (call-interactively 'org-table-recalculate))
20477 ((org-table-maybe-recalculate-line))
20478 (t (org-table-align)))))))
20479 (timestamp (org-timestamp-change 0 'day))
20480 (otherwise
20481 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20482 (user-error
20483 "C-c C-c can do nothing useful at this location")))))))))
20485 (defun org-mode-restart ()
20486 "Restart Org-mode, to scan again for special lines.
20487 Also updates the keyword regular expressions."
20488 (interactive)
20489 ;; this will set the mode *and* set file local variables.
20490 (normal-mode)
20491 ;; but it may leave us in some unrelated mode
20492 (unless (derived-mode-p "org-mode")
20493 (org-mode))
20494 (message "Org-mode restarted"))
20496 (defun org-kill-note-or-show-branches ()
20497 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20498 (interactive)
20499 (if (not org-finish-function)
20500 (progn
20501 (hide-subtree)
20502 (call-interactively 'show-branches))
20503 (let ((org-note-abort t))
20504 (funcall org-finish-function))))
20506 (defun org-open-line (n)
20507 "Insert a new row in tables, call `open-line' elsewhere.
20508 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
20509 (interactive "*p")
20510 (cond
20511 ((not org-special-ctrl-o)
20512 (open-line n))
20513 ((org-at-table-p)
20514 (org-table-insert-row))
20516 (open-line n))))
20518 (defun org-return (&optional indent)
20519 "Goto next table row or insert a newline.
20520 Calls `org-table-next-row' or `newline', depending on context.
20521 See the individual commands for more information."
20522 (interactive)
20523 (let (org-ts-what)
20524 (cond
20525 ((or (bobp) (org-in-src-block-p))
20526 (if indent (newline-and-indent) (newline)))
20527 ((org-at-table-p)
20528 (org-table-justify-field-maybe)
20529 (call-interactively 'org-table-next-row))
20530 ;; when `newline-and-indent' is called within a list, make sure
20531 ;; text moved stays inside the item.
20532 ((and (org-in-item-p) indent)
20533 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20534 (progn
20535 (save-match-data (newline))
20536 (org-indent-line-to (length (match-string 0))))
20537 (let ((ind (org-get-indentation)))
20538 (newline)
20539 (if (org-looking-back org-list-end-re)
20540 (org-indent-line)
20541 (org-indent-line-to ind)))))
20542 ((and org-return-follows-link
20543 (org-at-timestamp-p t)
20544 (not (eq org-ts-what 'after)))
20545 (org-follow-timestamp-link))
20546 ((and org-return-follows-link
20547 (let ((tprop (get-text-property (point) 'face)))
20548 (or (eq tprop 'org-link)
20549 (and (listp tprop) (memq 'org-link tprop)))))
20550 (call-interactively 'org-open-at-point))
20551 ((and (org-at-heading-p)
20552 (looking-at
20553 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20554 (org-show-entry)
20555 (end-of-line 1)
20556 (newline))
20557 (t (if indent (newline-and-indent) (newline))))))
20559 (defun org-return-indent ()
20560 "Goto next table row or insert a newline and indent.
20561 Calls `org-table-next-row' or `newline-and-indent', depending on
20562 context. See the individual commands for more information."
20563 (interactive)
20564 (org-return t))
20566 (defun org-ctrl-c-star ()
20567 "Compute table, or change heading status of lines.
20568 Calls `org-table-recalculate' or `org-toggle-heading',
20569 depending on context."
20570 (interactive)
20571 (cond
20572 ((org-at-table-p)
20573 (call-interactively 'org-table-recalculate))
20575 ;; Convert all lines in region to list items
20576 (call-interactively 'org-toggle-heading))))
20578 (defun org-ctrl-c-minus ()
20579 "Insert separator line in table or modify bullet status of line.
20580 Also turns a plain line or a region of lines into list items.
20581 Calls `org-table-insert-hline', `org-toggle-item', or
20582 `org-cycle-list-bullet', depending on context."
20583 (interactive)
20584 (cond
20585 ((org-at-table-p)
20586 (call-interactively 'org-table-insert-hline))
20587 ((org-region-active-p)
20588 (call-interactively 'org-toggle-item))
20589 ((org-in-item-p)
20590 (call-interactively 'org-cycle-list-bullet))
20592 (call-interactively 'org-toggle-item))))
20594 (defun org-toggle-item (arg)
20595 "Convert headings or normal lines to items, items to normal lines.
20596 If there is no active region, only the current line is considered.
20598 If the first non blank line in the region is a headline, convert
20599 all headlines to items, shifting text accordingly.
20601 If it is an item, convert all items to normal lines.
20603 If it is normal text, change region into a list of items.
20604 With a prefix argument ARG, change the region in a single item."
20605 (interactive "P")
20606 (let ((shift-text
20607 (function
20608 ;; Shift text in current section to IND, from point to END.
20609 ;; The function leaves point to END line.
20610 (lambda (ind end)
20611 (let ((min-i 1000) (end (copy-marker end)))
20612 ;; First determine the minimum indentation (MIN-I) of
20613 ;; the text.
20614 (save-excursion
20615 (catch 'exit
20616 (while (< (point) end)
20617 (let ((i (org-get-indentation)))
20618 (cond
20619 ;; Skip blank lines and inline tasks.
20620 ((looking-at "^[ \t]*$"))
20621 ((looking-at org-outline-regexp-bol))
20622 ;; We can't find less than 0 indentation.
20623 ((zerop i) (throw 'exit (setq min-i 0)))
20624 ((< i min-i) (setq min-i i))))
20625 (forward-line))))
20626 ;; Then indent each line so that a line indented to
20627 ;; MIN-I becomes indented to IND. Ignore blank lines
20628 ;; and inline tasks in the process.
20629 (let ((delta (- ind min-i)))
20630 (while (< (point) end)
20631 (unless (or (looking-at "^[ \t]*$")
20632 (looking-at org-outline-regexp-bol))
20633 (org-indent-line-to (+ (org-get-indentation) delta)))
20634 (forward-line)))))))
20635 (skip-blanks
20636 (function
20637 ;; Return beginning of first non-blank line, starting from
20638 ;; line at POS.
20639 (lambda (pos)
20640 (save-excursion
20641 (goto-char pos)
20642 (skip-chars-forward " \r\t\n")
20643 (point-at-bol)))))
20644 beg end)
20645 ;; Determine boundaries of changes.
20646 (if (org-region-active-p)
20647 (setq beg (funcall skip-blanks (region-beginning))
20648 end (copy-marker (region-end)))
20649 (setq beg (funcall skip-blanks (point-at-bol))
20650 end (copy-marker (point-at-eol))))
20651 ;; Depending on the starting line, choose an action on the text
20652 ;; between BEG and END.
20653 (org-with-limited-levels
20654 (save-excursion
20655 (goto-char beg)
20656 (cond
20657 ;; Case 1. Start at an item: de-itemize. Note that it only
20658 ;; happens when a region is active: `org-ctrl-c-minus'
20659 ;; would call `org-cycle-list-bullet' otherwise.
20660 ((org-at-item-p)
20661 (while (< (point) end)
20662 (when (org-at-item-p)
20663 (skip-chars-forward " \t")
20664 (delete-region (point) (match-end 0)))
20665 (forward-line)))
20666 ;; Case 2. Start at an heading: convert to items.
20667 ((org-at-heading-p)
20668 (let* ((bul (org-list-bullet-string "-"))
20669 (bul-len (length bul))
20670 ;; Indentation of the first heading. It should be
20671 ;; relative to the indentation of its parent, if any.
20672 (start-ind (save-excursion
20673 (cond
20674 ((not org-adapt-indentation) 0)
20675 ((not (outline-previous-heading)) 0)
20676 (t (length (match-string 0))))))
20677 ;; Level of first heading. Further headings will be
20678 ;; compared to it to determine hierarchy in the list.
20679 (ref-level (org-reduced-level (org-outline-level))))
20680 (while (< (point) end)
20681 (let* ((level (org-reduced-level (org-outline-level)))
20682 (delta (max 0 (- level ref-level))))
20683 ;; If current headline is less indented than the first
20684 ;; one, set it as reference, in order to preserve
20685 ;; subtrees.
20686 (when (< level ref-level) (setq ref-level level))
20687 (replace-match bul t t)
20688 (org-indent-line-to (+ start-ind (* delta bul-len)))
20689 ;; Ensure all text down to END (or SECTION-END) belongs
20690 ;; to the newly created item.
20691 (let ((section-end (save-excursion
20692 (or (outline-next-heading) (point)))))
20693 (forward-line)
20694 (funcall shift-text
20695 (+ start-ind (* (1+ delta) bul-len))
20696 (min end section-end)))))))
20697 ;; Case 3. Normal line with ARG: make the first line of region
20698 ;; an item, and shift indentation of others lines to
20699 ;; set them as item's body.
20700 (arg (let* ((bul (org-list-bullet-string "-"))
20701 (bul-len (length bul))
20702 (ref-ind (org-get-indentation)))
20703 (skip-chars-forward " \t")
20704 (insert bul)
20705 (forward-line)
20706 (while (< (point) end)
20707 ;; Ensure that lines less indented than first one
20708 ;; still get included in item body.
20709 (funcall shift-text
20710 (+ ref-ind bul-len)
20711 (min end (save-excursion (or (outline-next-heading)
20712 (point)))))
20713 (forward-line))))
20714 ;; Case 4. Normal line without ARG: turn each non-item line
20715 ;; into an item.
20717 (while (< (point) end)
20718 (unless (or (org-at-heading-p) (org-at-item-p))
20719 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20720 (replace-match
20721 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20722 (forward-line))))))))
20724 (defun org-toggle-heading (&optional nstars)
20725 "Convert headings to normal text, or items or text to headings.
20726 If there is no active region, only convert the current line.
20728 With a \\[universal-argument] prefix, convert the whole list at
20729 point into heading.
20731 In a region:
20733 - If the first non blank line is a headline, remove the stars
20734 from all headlines in the region.
20736 - If it is a normal line, turn each and every normal line (i.e.,
20737 not an heading or an item) in the region into headings. If you
20738 want to convert only the first line of this region, use one
20739 universal prefix argument.
20741 - If it is a plain list item, turn all plain list items into headings.
20743 When converting a line into a heading, the number of stars is chosen
20744 such that the lines become children of the current entry. However,
20745 when a numeric prefix argument is given, its value determines the
20746 number of stars to add."
20747 (interactive "P")
20748 (let ((skip-blanks
20749 (function
20750 ;; Return beginning of first non-blank line, starting from
20751 ;; line at POS.
20752 (lambda (pos)
20753 (save-excursion
20754 (goto-char pos)
20755 (while (org-at-comment-p) (forward-line))
20756 (skip-chars-forward " \r\t\n")
20757 (point-at-bol)))))
20758 beg end toggled)
20759 ;; Determine boundaries of changes. If a universal prefix has
20760 ;; been given, put the list in a region. If region ends at a bol,
20761 ;; do not consider the last line to be in the region.
20763 (when (and current-prefix-arg (org-at-item-p))
20764 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20765 (org-mark-element))
20767 (if (org-region-active-p)
20768 (setq beg (funcall skip-blanks (region-beginning))
20769 end (copy-marker (save-excursion
20770 (goto-char (region-end))
20771 (if (bolp) (point) (point-at-eol)))))
20772 (setq beg (funcall skip-blanks (point-at-bol))
20773 end (copy-marker (point-at-eol))))
20774 ;; Ensure inline tasks don't count as headings.
20775 (org-with-limited-levels
20776 (save-excursion
20777 (goto-char beg)
20778 (cond
20779 ;; Case 1. Started at an heading: de-star headings.
20780 ((org-at-heading-p)
20781 (while (< (point) end)
20782 (when (org-at-heading-p t)
20783 (looking-at org-outline-regexp) (replace-match "")
20784 (setq toggled t))
20785 (forward-line)))
20786 ;; Case 2. Started at an item: change items into headlines.
20787 ;; One star will be added by `org-list-to-subtree'.
20788 ((org-at-item-p)
20789 (let* ((stars (make-string
20790 ;; subtract the star that will be added again by
20791 ;; `org-list-to-subtree'
20792 (if (numberp nstars) (1- nstars)
20793 (or (org-current-level) 0))
20794 ?*))
20795 (add-stars
20796 (cond (nstars "") ; stars from prefix only
20797 ((equal stars "") "") ; before first heading
20798 (org-odd-levels-only "*") ; inside heading, odd
20799 (t "")))) ; inside heading, oddeven
20800 (while (< (point) end)
20801 (when (org-at-item-p)
20802 ;; Pay attention to cases when region ends before list.
20803 (let* ((struct (org-list-struct))
20804 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20805 (save-restriction
20806 (narrow-to-region (point) list-end)
20807 (insert
20808 (org-list-to-subtree
20809 (org-list-parse-list t)
20810 '(:istart (concat stars add-stars (funcall get-stars depth))
20811 :icount (concat stars add-stars (funcall get-stars depth)))))))
20812 (setq toggled t))
20813 (forward-line))))
20814 ;; Case 3. Started at normal text: make every line an heading,
20815 ;; skipping headlines and items.
20816 (t (let* ((stars
20817 (make-string
20818 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20819 (add-stars
20820 (cond (nstars "") ; stars from prefix only
20821 ((equal stars "") "*") ; before first heading
20822 (org-odd-levels-only "**") ; inside heading, odd
20823 (t "*"))) ; inside heading, oddeven
20824 (rpl (concat stars add-stars " "))
20825 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20826 (while (< (point) (if (equal nstars '(4)) lend end))
20827 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20828 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20829 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20830 (forward-line)))))))
20831 (unless toggled (message "Cannot toggle heading from here"))))
20833 (defun org-meta-return (&optional arg)
20834 "Insert a new heading or wrap a region in a table.
20835 Calls `org-insert-heading' or `org-table-wrap-region', depending
20836 on context. See the individual commands for more information."
20837 (interactive "P")
20838 (org-check-before-invisible-edit 'insert)
20839 (or (run-hook-with-args-until-success 'org-metareturn-hook)
20840 (let* ((element (org-element-at-point))
20841 (type (org-element-type element)))
20842 (when (eq type 'table-row)
20843 (setq element (org-element-property :parent element))
20844 (setq type 'table))
20845 (if (and (eq type 'table)
20846 (eq (org-element-property :type element) 'org)
20847 (>= (point) (org-element-property :contents-begin element))
20848 (< (point) (org-element-property :contents-end element)))
20849 (call-interactively 'org-table-wrap-region)
20850 (call-interactively 'org-insert-heading)))))
20852 ;;; Menu entries
20854 (defsubst org-in-subtree-not-table-p ()
20855 "Are we in a subtree and not in a table?"
20856 (and (not (org-before-first-heading-p))
20857 (not (org-at-table-p))))
20859 ;; Define the Org-mode menus
20860 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20861 '("Tbl"
20862 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20863 ["Next Field" org-cycle (org-at-table-p)]
20864 ["Previous Field" org-shifttab (org-at-table-p)]
20865 ["Next Row" org-return (org-at-table-p)]
20866 "--"
20867 ["Blank Field" org-table-blank-field (org-at-table-p)]
20868 ["Edit Field" org-table-edit-field (org-at-table-p)]
20869 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20870 "--"
20871 ("Column"
20872 ["Move Column Left" org-metaleft (org-at-table-p)]
20873 ["Move Column Right" org-metaright (org-at-table-p)]
20874 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20875 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20876 ("Row"
20877 ["Move Row Up" org-metaup (org-at-table-p)]
20878 ["Move Row Down" org-metadown (org-at-table-p)]
20879 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20880 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20881 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20882 "--"
20883 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20884 ("Rectangle"
20885 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20886 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20887 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20888 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20889 "--"
20890 ("Calculate"
20891 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20892 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20893 ["Edit Formulas" org-edit-special (org-at-table-p)]
20894 "--"
20895 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20896 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20897 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20898 "--"
20899 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20900 "--"
20901 ["Sum Column/Rectangle" org-table-sum
20902 (or (org-at-table-p) (org-region-active-p))]
20903 ["Which Column?" org-table-current-column (org-at-table-p)])
20904 ["Debug Formulas"
20905 org-table-toggle-formula-debugger
20906 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20907 ["Show Col/Row Numbers"
20908 org-table-toggle-coordinate-overlays
20909 :style toggle
20910 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20911 "--"
20912 ["Create" org-table-create (and (not (org-at-table-p))
20913 org-enable-table-editor)]
20914 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20915 ["Import from File" org-table-import (not (org-at-table-p))]
20916 ["Export to File" org-table-export (org-at-table-p)]
20917 "--"
20918 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20920 (easy-menu-define org-org-menu org-mode-map "Org menu"
20921 '("Org"
20922 ("Show/Hide"
20923 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20924 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20925 ["Sparse Tree..." org-sparse-tree t]
20926 ["Reveal Context" org-reveal t]
20927 ["Show All" show-all t]
20928 "--"
20929 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20930 "--"
20931 ["New Heading" org-insert-heading t]
20932 ("Navigate Headings"
20933 ["Up" outline-up-heading t]
20934 ["Next" outline-next-visible-heading t]
20935 ["Previous" outline-previous-visible-heading t]
20936 ["Next Same Level" outline-forward-same-level t]
20937 ["Previous Same Level" outline-backward-same-level t]
20938 "--"
20939 ["Jump" org-goto t])
20940 ("Edit Structure"
20941 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20942 "--"
20943 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20944 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20945 "--"
20946 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20947 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20948 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20949 "--"
20950 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20951 "--"
20952 ["Copy visible text" org-copy-visible t]
20953 "--"
20954 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20955 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20956 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20957 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20958 "--"
20959 ["Sort Region/Children" org-sort t]
20960 "--"
20961 ["Convert to odd levels" org-convert-to-odd-levels t]
20962 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20963 ("Editing"
20964 ["Emphasis..." org-emphasize t]
20965 ["Edit Source Example" org-edit-special t]
20966 "--"
20967 ["Footnote new/jump" org-footnote-action t]
20968 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20969 ("Archive"
20970 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20971 "--"
20972 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20973 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20974 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20976 "--"
20977 ("Hyperlinks"
20978 ["Store Link (Global)" org-store-link t]
20979 ["Find existing link to here" org-occur-link-in-agenda-files t]
20980 ["Insert Link" org-insert-link t]
20981 ["Follow Link" org-open-at-point t]
20982 "--"
20983 ["Next link" org-next-link t]
20984 ["Previous link" org-previous-link t]
20985 "--"
20986 ["Descriptive Links"
20987 org-toggle-link-display
20988 :style radio
20989 :selected org-descriptive-links
20991 ["Literal Links"
20992 org-toggle-link-display
20993 :style radio
20994 :selected (not org-descriptive-links)])
20995 "--"
20996 ("TODO Lists"
20997 ["TODO/DONE/-" org-todo t]
20998 ("Select keyword"
20999 ["Next keyword" org-shiftright (org-at-heading-p)]
21000 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21001 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21002 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21003 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21004 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21005 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21006 "--"
21007 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21008 :selected org-enforce-todo-dependencies :style toggle :active t]
21009 "Settings for tree at point"
21010 ["Do Children sequentially" org-toggle-ordered-property :style radio
21011 :selected (org-entry-get nil "ORDERED")
21012 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21013 ["Do Children parallel" org-toggle-ordered-property :style radio
21014 :selected (not (org-entry-get nil "ORDERED"))
21015 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21016 "--"
21017 ["Set Priority" org-priority t]
21018 ["Priority Up" org-shiftup t]
21019 ["Priority Down" org-shiftdown t]
21020 "--"
21021 ["Get news from all feeds" org-feed-update-all t]
21022 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21023 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21024 ("TAGS and Properties"
21025 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21026 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21027 "--"
21028 ["Set property" org-set-property (not (org-before-first-heading-p))]
21029 ["Column view of properties" org-columns t]
21030 ["Insert Column View DBlock" org-insert-columns-dblock t])
21031 ("Dates and Scheduling"
21032 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21033 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21034 ("Change Date"
21035 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21036 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21037 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21038 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21039 ["Compute Time Range" org-evaluate-time-range t]
21040 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21041 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21042 "--"
21043 ["Custom time format" org-toggle-time-stamp-overlays
21044 :style radio :selected org-display-custom-times]
21045 "--"
21046 ["Goto Calendar" org-goto-calendar t]
21047 ["Date from Calendar" org-date-from-calendar t]
21048 "--"
21049 ["Start/Restart Timer" org-timer-start t]
21050 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21051 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21052 ["Insert Timer String" org-timer t]
21053 ["Insert Timer Item" org-timer-item t])
21054 ("Logging work"
21055 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21056 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21057 ["Clock out" org-clock-out t]
21058 ["Clock cancel" org-clock-cancel t]
21059 "--"
21060 ["Mark as default task" org-clock-mark-default-task t]
21061 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21062 ["Goto running clock" org-clock-goto t]
21063 "--"
21064 ["Display times" org-clock-display t]
21065 ["Create clock table" org-clock-report t]
21066 "--"
21067 ["Record DONE time"
21068 (progn (setq org-log-done (not org-log-done))
21069 (message "Switching to %s will %s record a timestamp"
21070 (car org-done-keywords)
21071 (if org-log-done "automatically" "not")))
21072 :style toggle :selected org-log-done])
21073 "--"
21074 ["Agenda Command..." org-agenda t]
21075 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21076 ("File List for Agenda")
21077 ("Special views current file"
21078 ["TODO Tree" org-show-todo-tree t]
21079 ["Check Deadlines" org-check-deadlines t]
21080 ["Timeline" org-timeline t]
21081 ["Tags/Property tree" org-match-sparse-tree t])
21082 "--"
21083 ["Export/Publish..." org-export-dispatch t]
21084 ("LaTeX"
21085 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21086 :selected org-cdlatex-mode]
21087 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21088 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21089 ["Modify math symbol" org-cdlatex-math-modify
21090 (org-inside-LaTeX-fragment-p)]
21091 ["Insert citation" org-reftex-citation t]
21092 "--"
21093 ["Template for BEAMER" (org-beamer-insert-options-template) t])
21094 "--"
21095 ("MobileOrg"
21096 ["Push Files and Views" org-mobile-push t]
21097 ["Get Captured and Flagged" org-mobile-pull t]
21098 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21099 "--"
21100 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21101 "--"
21102 ("Documentation"
21103 ["Show Version" org-version t]
21104 ["Info Documentation" org-info t])
21105 ("Customize"
21106 ["Browse Org Group" org-customize t]
21107 "--"
21108 ["Expand This Menu" org-create-customize-menu
21109 (fboundp 'customize-menu-create)])
21110 ["Send bug report" org-submit-bug-report t]
21111 "--"
21112 ("Refresh/Reload"
21113 ["Refresh setup current buffer" org-mode-restart t]
21114 ["Reload Org (after update)" org-reload t]
21115 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21118 (defun org-info (&optional node)
21119 "Read documentation for Org-mode in the info system.
21120 With optional NODE, go directly to that node."
21121 (interactive)
21122 (info (format "(org)%s" (or node ""))))
21124 ;;;###autoload
21125 (defun org-submit-bug-report ()
21126 "Submit a bug report on Org-mode via mail.
21128 Don't hesitate to report any problems or inaccurate documentation.
21130 If you don't have setup sending mail from (X)Emacs, please copy the
21131 output buffer into your mail program, as it gives us important
21132 information about your Org-mode version and configuration."
21133 (interactive)
21134 (require 'reporter)
21135 (org-load-modules-maybe)
21136 (org-require-autoloaded-modules)
21137 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21138 (reporter-submit-bug-report
21139 "emacs-orgmode@gnu.org"
21140 (org-version nil 'full)
21141 (let (list)
21142 (save-window-excursion
21143 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21144 (delete-other-windows)
21145 (erase-buffer)
21146 (insert "You are about to submit a bug report to the Org-mode mailing list.
21148 We would like to add your full Org-mode and Outline configuration to the
21149 bug report. This greatly simplifies the work of the maintainer and
21150 other experts on the mailing list.
21152 HOWEVER, some variables you have customized may contain private
21153 information. The names of customers, colleagues, or friends, might
21154 appear in the form of file names, tags, todo states, or search strings.
21155 If you answer yes to the prompt, you might want to check and remove
21156 such private information before sending the email.")
21157 (add-text-properties (point-min) (point-max) '(face org-warning))
21158 (when (yes-or-no-p "Include your Org-mode configuration ")
21159 (mapatoms
21160 (lambda (v)
21161 (and (boundp v)
21162 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21163 (or (and (symbol-value v)
21164 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21165 (and
21166 (get v 'custom-type) (get v 'standard-value)
21167 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21168 (push v list)))))
21169 (kill-buffer (get-buffer "*Warn about privacy*"))
21170 list))
21171 nil nil
21172 "Remember to cover the basics, that is, what you expected to happen and
21173 what in fact did happen. You don't know how to make a good report? See
21175 http://orgmode.org/manual/Feedback.html#Feedback
21177 Your bug report will be posted to the Org-mode mailing list.
21178 ------------------------------------------------------------------------")
21179 (save-excursion
21180 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21181 (replace-match "\\1Bug: \\3 [\\2]")))))
21184 (defun org-install-agenda-files-menu ()
21185 (let ((bl (buffer-list)))
21186 (save-excursion
21187 (while bl
21188 (set-buffer (pop bl))
21189 (if (derived-mode-p 'org-mode) (setq bl nil)))
21190 (when (derived-mode-p 'org-mode)
21191 (easy-menu-change
21192 '("Org") "File List for Agenda"
21193 (append
21194 (list
21195 ["Edit File List" (org-edit-agenda-file-list) t]
21196 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21197 ["Remove Current File from List" org-remove-file t]
21198 ["Cycle through agenda files" org-cycle-agenda-files t]
21199 ["Occur in all agenda files" org-occur-in-agenda-files t]
21200 "--")
21201 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21203 ;;;; Documentation
21205 (defun org-require-autoloaded-modules ()
21206 (interactive)
21207 (mapc 'require
21208 '(org-agenda org-archive org-attach org-clock org-colview org-id
21209 org-table org-timer)))
21211 ;;;###autoload
21212 (defun org-reload (&optional uncompiled)
21213 "Reload all org lisp files.
21214 With prefix arg UNCOMPILED, load the uncompiled versions."
21215 (interactive "P")
21216 (require 'loadhist)
21217 (let* ((org-dir (org-find-library-dir "org"))
21218 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21219 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21220 (remove-re (mapconcat 'identity
21221 (mapcar (lambda (f) (concat "^" f "$"))
21222 (list (if (featurep 'xemacs)
21223 "org-colview"
21224 "org-colview-xemacs")
21225 "org" "org-loaddefs" "org-version"))
21226 "\\|"))
21227 (feats (delete-dups
21228 (mapcar 'file-name-sans-extension
21229 (mapcar 'file-name-nondirectory
21230 (delq nil
21231 (mapcar 'feature-file
21232 features))))))
21233 (lfeat (append
21234 (sort
21235 (setq feats
21236 (delq nil (mapcar
21237 (lambda (f)
21238 (if (and (string-match feature-re f)
21239 (not (string-match remove-re f)))
21240 f nil))
21241 feats)))
21242 'string-lessp)
21243 (list "org-version" "org")))
21244 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21245 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21246 load-uncore load-misses)
21247 (setq load-misses
21248 (delq 't
21249 (mapcar (lambda (f)
21250 (or (org-load-noerror-mustsuffix (concat org-dir f))
21251 (and (string= org-dir contrib-dir)
21252 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21253 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21254 (add-to-list 'load-uncore f 'append)
21257 lfeat)))
21258 (if load-uncore
21259 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21260 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21261 (if load-misses
21262 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21263 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21264 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21266 ;;;###autoload
21267 (defun org-customize ()
21268 "Call the customize function with org as argument."
21269 (interactive)
21270 (org-load-modules-maybe)
21271 (org-require-autoloaded-modules)
21272 (customize-browse 'org))
21274 (defun org-create-customize-menu ()
21275 "Create a full customization menu for Org-mode, insert it into the menu."
21276 (interactive)
21277 (org-load-modules-maybe)
21278 (org-require-autoloaded-modules)
21279 (if (fboundp 'customize-menu-create)
21280 (progn
21281 (easy-menu-change
21282 '("Org") "Customize"
21283 `(["Browse Org group" org-customize t]
21284 "--"
21285 ,(customize-menu-create 'org)
21286 ["Set" Custom-set t]
21287 ["Save" Custom-save t]
21288 ["Reset to Current" Custom-reset-current t]
21289 ["Reset to Saved" Custom-reset-saved t]
21290 ["Reset to Standard Settings" Custom-reset-standard t]))
21291 (message "\"Org\"-menu now contains full customization menu"))
21292 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21294 ;;;; Miscellaneous stuff
21296 ;;; Generally useful functions
21298 (defun org-get-at-bol (property)
21299 "Get text property PROPERTY at beginning of line."
21300 (get-text-property (point-at-bol) property))
21302 (defun org-find-text-property-in-string (prop s)
21303 "Return the first non-nil value of property PROP in string S."
21304 (or (get-text-property 0 prop s)
21305 (get-text-property (or (next-single-property-change 0 prop s) 0)
21306 prop s)))
21308 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21309 "Display the given MESSAGE as a warning."
21310 (if (fboundp 'display-warning)
21311 (display-warning 'org message
21312 (if (featurep 'xemacs) 'warning :warning))
21313 (let ((buf (get-buffer-create "*Org warnings*")))
21314 (with-current-buffer buf
21315 (goto-char (point-max))
21316 (insert "Warning (Org): " message)
21317 (unless (bolp)
21318 (newline)))
21319 (display-buffer buf)
21320 (sit-for 0))))
21322 (defun org-eval (form)
21323 "Eval FORM and return result."
21324 (condition-case error
21325 (eval form)
21326 (error (format "%%![Error: %s]" error))))
21328 (defun org-in-clocktable-p ()
21329 "Check if the cursor is in a clocktable."
21330 (let ((pos (point)) start)
21331 (save-excursion
21332 (end-of-line 1)
21333 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21334 (setq start (match-beginning 0))
21335 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21336 (>= (match-end 0) pos)
21337 start))))
21339 (defun org-in-commented-line ()
21340 "Is point in a line starting with `#'?"
21341 (equal (char-after (point-at-bol)) ?#))
21343 (defun org-in-indented-comment-line ()
21344 "Is point in a line starting with `#' after some white space?"
21345 (save-excursion
21346 (save-match-data
21347 (goto-char (point-at-bol))
21348 (looking-at "[ \t]*#"))))
21350 (defun org-in-verbatim-emphasis ()
21351 (save-match-data
21352 (and (org-in-regexp org-emph-re 2)
21353 (>= (point) (match-beginning 3))
21354 (<= (point) (match-end 4))
21355 (member (match-string 3) '("=" "~")))))
21357 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21358 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21359 (if (and marker (marker-buffer marker)
21360 (buffer-live-p (marker-buffer marker)))
21361 (progn
21362 (org-pop-to-buffer-same-window (marker-buffer marker))
21363 (if (or (> marker (point-max)) (< marker (point-min)))
21364 (widen))
21365 (goto-char marker)
21366 (org-show-context 'org-goto))
21367 (if bookmark
21368 (bookmark-jump bookmark)
21369 (error "Cannot find location"))))
21371 (defun org-quote-csv-field (s)
21372 "Quote field for inclusion in CSV material."
21373 (if (string-match "[\",]" s)
21374 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21377 (defun org-force-self-insert (N)
21378 "Needed to enforce self-insert under remapping."
21379 (interactive "p")
21380 (self-insert-command N))
21382 (defun org-string-width (s)
21383 "Compute width of string, ignoring invisible characters.
21384 This ignores character with invisibility property `org-link', and also
21385 characters with property `org-cwidth', because these will become invisible
21386 upon the next fontification round."
21387 (let (b l)
21388 (when (or (eq t buffer-invisibility-spec)
21389 (assq 'org-link buffer-invisibility-spec))
21390 (while (setq b (text-property-any 0 (length s)
21391 'invisible 'org-link s))
21392 (setq s (concat (substring s 0 b)
21393 (substring s (or (next-single-property-change
21394 b 'invisible s) (length s)))))))
21395 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21396 (setq s (concat (substring s 0 b)
21397 (substring s (or (next-single-property-change
21398 b 'org-cwidth s) (length s))))))
21399 (setq l (string-width s) b -1)
21400 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21401 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21404 (defun org-shorten-string (s maxlength)
21405 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21406 If the string is shorter or has length MAXLENGTH, just return the
21407 original string. If it is longer, the functions finds a space in the
21408 string, breaks this string off at that locations and adds three dots
21409 as ellipsis. Including the ellipsis, the string will not be longer
21410 than MAXLENGTH. If finding a good breaking point in the string does
21411 not work, the string is just chopped off in the middle of a word
21412 if necessary."
21413 (if (<= (length s) maxlength)
21415 (let* ((n (max (- maxlength 4) 1))
21416 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21417 (if (string-match re s)
21418 (concat (match-string 1 s) "...")
21419 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21421 (defun org-get-indentation (&optional line)
21422 "Get the indentation of the current line, interpreting tabs.
21423 When LINE is given, assume it represents a line and compute its indentation."
21424 (if line
21425 (if (string-match "^ *" (org-remove-tabs line))
21426 (match-end 0))
21427 (save-excursion
21428 (beginning-of-line 1)
21429 (skip-chars-forward " \t")
21430 (current-column))))
21432 (defun org-get-string-indentation (s)
21433 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21434 (let ((n -1) (i 0) (w tab-width) c)
21435 (catch 'exit
21436 (while (< (setq n (1+ n)) (length s))
21437 (setq c (aref s n))
21438 (cond ((= c ?\ ) (setq i (1+ i)))
21439 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21440 (t (throw 'exit t)))))
21443 (defun org-remove-tabs (s &optional width)
21444 "Replace tabulators in S with spaces.
21445 Assumes that s is a single line, starting in column 0."
21446 (setq width (or width tab-width))
21447 (while (string-match "\t" s)
21448 (setq s (replace-match
21449 (make-string
21450 (- (* width (/ (+ (match-beginning 0) width) width))
21451 (match-beginning 0)) ?\ )
21452 t t s)))
21455 (defun org-fix-indentation (line ind)
21456 "Fix indentation in LINE.
21457 IND is a cons cell with target and minimum indentation.
21458 If the current indentation in LINE is smaller than the minimum,
21459 leave it alone. If it is larger than ind, set it to the target."
21460 (let* ((l (org-remove-tabs line))
21461 (i (org-get-indentation l))
21462 (i1 (car ind)) (i2 (cdr ind)))
21463 (if (>= i i2) (setq l (substring line i2)))
21464 (if (> i1 0)
21465 (concat (make-string i1 ?\ ) l)
21466 l)))
21468 (defun org-remove-indentation (code &optional n)
21469 "Remove the maximum common indentation from the lines in CODE.
21470 N may optionally be the number of spaces to remove."
21471 (with-temp-buffer
21472 (insert code)
21473 (org-do-remove-indentation n)
21474 (buffer-string)))
21476 (defun org-do-remove-indentation (&optional n)
21477 "Remove the maximum common indentation from the buffer."
21478 (untabify (point-min) (point-max))
21479 (let ((min 10000) re)
21480 (if n
21481 (setq min n)
21482 (goto-char (point-min))
21483 (while (re-search-forward "^ *[^ \n]" nil t)
21484 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21485 (unless (or (= min 0) (= min 10000))
21486 (setq re (format "^ \\{%d\\}" min))
21487 (goto-char (point-min))
21488 (while (re-search-forward re nil t)
21489 (replace-match "")
21490 (end-of-line 1))
21491 min)))
21493 (defun org-fill-template (template alist)
21494 "Find each %key of ALIST in TEMPLATE and replace it."
21495 (let ((case-fold-search nil)
21496 entry key value)
21497 (setq alist (sort (copy-sequence alist)
21498 (lambda (a b) (< (length (car a)) (length (car b))))))
21499 (while (setq entry (pop alist))
21500 (setq template
21501 (replace-regexp-in-string
21502 (concat "%" (regexp-quote (car entry)))
21503 (or (cdr entry) "") template t t)))
21504 template))
21506 (defun org-base-buffer (buffer)
21507 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21508 (if (not buffer)
21509 buffer
21510 (or (buffer-base-buffer buffer)
21511 buffer)))
21513 (defun org-trim (s)
21514 "Remove whitespace at beginning and end of string."
21515 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
21516 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
21519 (defun org-wrap (string &optional width lines)
21520 "Wrap string to either a number of lines, or a width in characters.
21521 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21522 that costs. If there is a word longer than WIDTH, the text is actually
21523 wrapped to the length of that word.
21524 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21525 many lines, whatever width that takes.
21526 The return value is a list of lines, without newlines at the end."
21527 (let* ((words (org-split-string string "[ \t\n]+"))
21528 (maxword (apply 'max (mapcar 'org-string-width words)))
21529 w ll)
21530 (cond (width
21531 (org-do-wrap words (max maxword width)))
21532 (lines
21533 (setq w maxword)
21534 (setq ll (org-do-wrap words maxword))
21535 (if (<= (length ll) lines)
21537 (setq ll words)
21538 (while (> (length ll) lines)
21539 (setq w (1+ w))
21540 (setq ll (org-do-wrap words w)))
21541 ll))
21542 (t (error "Cannot wrap this")))))
21544 (defun org-do-wrap (words width)
21545 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21546 (let (lines line)
21547 (while words
21548 (setq line (pop words))
21549 (while (and words (< (+ (length line) (length (car words))) width))
21550 (setq line (concat line " " (pop words))))
21551 (setq lines (push line lines)))
21552 (nreverse lines)))
21554 (defun org-split-string (string &optional separators)
21555 "Splits STRING into substrings at SEPARATORS.
21556 No empty strings are returned if there are matches at the beginning
21557 and end of string."
21558 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21559 (start 0)
21560 notfirst
21561 (list nil))
21562 (while (and (string-match rexp string
21563 (if (and notfirst
21564 (= start (match-beginning 0))
21565 (< start (length string)))
21566 (1+ start) start))
21567 (< (match-beginning 0) (length string)))
21568 (setq notfirst t)
21569 (or (eq (match-beginning 0) 0)
21570 (and (eq (match-beginning 0) (match-end 0))
21571 (eq (match-beginning 0) start))
21572 (setq list
21573 (cons (substring string start (match-beginning 0))
21574 list)))
21575 (setq start (match-end 0)))
21576 (or (eq start (length string))
21577 (setq list
21578 (cons (substring string start)
21579 list)))
21580 (nreverse list)))
21582 (defun org-quote-vert (s)
21583 "Replace \"|\" with \"\\vert\"."
21584 (while (string-match "|" s)
21585 (setq s (replace-match "\\vert" t t s)))
21588 (defun org-uuidgen-p (s)
21589 "Is S an ID created by UUIDGEN?"
21590 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21592 (defun org-in-src-block-p (&optional inside)
21593 "Whether point is in a code source block.
21594 When INSIDE is non-nil, don't consider we are within a src block
21595 when point is at #+BEGIN_SRC or #+END_SRC."
21596 (let ((case-fold-search t) ov)
21597 (or (and (setq ov (overlays-at (point)))
21598 (memq 'org-block-background
21599 (overlay-properties (car ov))))
21600 (and (not inside)
21601 (save-match-data
21602 (save-excursion
21603 (beginning-of-line)
21604 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21606 (defun org-context ()
21607 "Return a list of contexts of the current cursor position.
21608 If several contexts apply, all are returned.
21609 Each context entry is a list with a symbol naming the context, and
21610 two positions indicating start and end of the context. Possible
21611 contexts are:
21613 :headline anywhere in a headline
21614 :headline-stars on the leading stars in a headline
21615 :todo-keyword on a TODO keyword (including DONE) in a headline
21616 :tags on the TAGS in a headline
21617 :priority on the priority cookie in a headline
21618 :item on the first line of a plain list item
21619 :item-bullet on the bullet/number of a plain list item
21620 :checkbox on the checkbox in a plain list item
21621 :table in an org-mode table
21622 :table-special on a special filed in a table
21623 :table-table in a table.el table
21624 :clocktable in a clocktable
21625 :src-block in a source block
21626 :link on a hyperlink
21627 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21628 :target on a <<target>>
21629 :radio-target on a <<<radio-target>>>
21630 :latex-fragment on a LaTeX fragment
21631 :latex-preview on a LaTeX fragment with overlaid preview image
21633 This function expects the position to be visible because it uses font-lock
21634 faces as a help to recognize the following contexts: :table-special, :link,
21635 and :keyword."
21636 (let* ((f (get-text-property (point) 'face))
21637 (faces (if (listp f) f (list f)))
21638 (case-fold-search t)
21639 (p (point)) clist o)
21640 ;; First the large context
21641 (cond
21642 ((org-at-heading-p t)
21643 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21644 (when (progn
21645 (beginning-of-line 1)
21646 (looking-at org-todo-line-tags-regexp))
21647 (push (org-point-in-group p 1 :headline-stars) clist)
21648 (push (org-point-in-group p 2 :todo-keyword) clist)
21649 (push (org-point-in-group p 4 :tags) clist))
21650 (goto-char p)
21651 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21652 (if (looking-at "\\[#[A-Z0-9]\\]")
21653 (push (org-point-in-group p 0 :priority) clist)))
21655 ((org-at-item-p)
21656 (push (org-point-in-group p 2 :item-bullet) clist)
21657 (push (list :item (point-at-bol)
21658 (save-excursion (org-end-of-item) (point)))
21659 clist)
21660 (and (org-at-item-checkbox-p)
21661 (push (org-point-in-group p 0 :checkbox) clist)))
21663 ((org-at-table-p)
21664 (push (list :table (org-table-begin) (org-table-end)) clist)
21665 (if (memq 'org-formula faces)
21666 (push (list :table-special
21667 (previous-single-property-change p 'face)
21668 (next-single-property-change p 'face)) clist)))
21669 ((org-at-table-p 'any)
21670 (push (list :table-table) clist)))
21671 (goto-char p)
21673 (let ((case-fold-search t))
21674 ;; New the "medium" contexts: clocktables, source blocks
21675 (cond ((org-in-clocktable-p)
21676 (push (list :clocktable
21677 (and (or (looking-at "#\\+BEGIN: clocktable")
21678 (search-backward "#+BEGIN: clocktable" nil t))
21679 (match-beginning 0))
21680 (and (re-search-forward "#\\+END:?" nil t)
21681 (match-end 0))) clist))
21682 ((org-in-src-block-p)
21683 (push (list :src-block
21684 (and (or (looking-at "#\\+BEGIN_SRC")
21685 (search-backward "#+BEGIN_SRC" nil t))
21686 (match-beginning 0))
21687 (and (search-forward "#+END_SRC" nil t)
21688 (match-beginning 0))) clist))))
21689 (goto-char p)
21691 ;; Now the small context
21692 (cond
21693 ((org-at-timestamp-p)
21694 (push (org-point-in-group p 0 :timestamp) clist))
21695 ((memq 'org-link faces)
21696 (push (list :link
21697 (previous-single-property-change p 'face)
21698 (next-single-property-change p 'face)) clist))
21699 ((memq 'org-special-keyword faces)
21700 (push (list :keyword
21701 (previous-single-property-change p 'face)
21702 (next-single-property-change p 'face)) clist))
21703 ((org-at-target-p)
21704 (push (org-point-in-group p 0 :target) clist)
21705 (goto-char (1- (match-beginning 0)))
21706 (if (looking-at org-radio-target-regexp)
21707 (push (org-point-in-group p 0 :radio-target) clist))
21708 (goto-char p))
21709 ((setq o (car (delq nil
21710 (mapcar
21711 (lambda (x)
21712 (if (memq x org-latex-fragment-image-overlays) x))
21713 (overlays-at (point))))))
21714 (push (list :latex-fragment
21715 (overlay-start o) (overlay-end o)) clist)
21716 (push (list :latex-preview
21717 (overlay-start o) (overlay-end o)) clist))
21718 ((org-inside-LaTeX-fragment-p)
21719 ;; FIXME: positions wrong.
21720 (push (list :latex-fragment (point) (point)) clist)))
21722 (setq clist (nreverse (delq nil clist)))
21723 clist))
21725 ;; FIXME: Compare with at-regexp-p Do we need both?
21726 (defun org-in-regexp (re &optional nlines visually)
21727 "Check if point is inside a match of regexp.
21728 Normally only the current line is checked, but you can include NLINES extra
21729 lines both before and after point into the search.
21730 If VISUALLY is set, require that the cursor is not after the match but
21731 really on, so that the block visually is on the match."
21732 (catch 'exit
21733 (let ((pos (point))
21734 (eol (point-at-eol (+ 1 (or nlines 0))))
21735 (inc (if visually 1 0)))
21736 (save-excursion
21737 (beginning-of-line (- 1 (or nlines 0)))
21738 (while (re-search-forward re eol t)
21739 (if (and (<= (match-beginning 0) pos)
21740 (>= (+ inc (match-end 0)) pos))
21741 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21743 (defun org-at-regexp-p (regexp)
21744 "Is point inside a match of REGEXP in the current line?"
21745 (catch 'exit
21746 (save-excursion
21747 (let ((pos (point)) (end (point-at-eol)))
21748 (beginning-of-line 1)
21749 (while (re-search-forward regexp end t)
21750 (if (and (<= (match-beginning 0) pos)
21751 (>= (match-end 0) pos))
21752 (throw 'exit t)))
21753 nil))))
21755 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21756 "Non-nil when point is between matches of START-RE and END-RE.
21758 Also return a non-nil value when point is on one of the matches.
21760 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21761 buffer positions. Default values are the positions of headlines
21762 surrounding the point.
21764 The functions returns a cons cell whose car (resp. cdr) is the
21765 position before START-RE (resp. after END-RE)."
21766 (save-match-data
21767 (let ((pos (point))
21768 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21769 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21770 beg end)
21771 (save-excursion
21772 ;; Point is on a block when on START-RE or if START-RE can be
21773 ;; found before it...
21774 (and (or (org-at-regexp-p start-re)
21775 (re-search-backward start-re limit-up t))
21776 (setq beg (match-beginning 0))
21777 ;; ... and END-RE after it...
21778 (goto-char (match-end 0))
21779 (re-search-forward end-re limit-down t)
21780 (> (setq end (match-end 0)) pos)
21781 ;; ... without another START-RE in-between.
21782 (goto-char (match-beginning 0))
21783 (not (re-search-backward start-re (1+ beg) t))
21784 ;; Return value.
21785 (cons beg end))))))
21787 (defun org-in-block-p (names)
21788 "Non-nil when point belongs to a block whose name belongs to NAMES.
21790 NAMES is a list of strings containing names of blocks.
21792 Return first block name matched, or nil. Beware that in case of
21793 nested blocks, the returned name may not belong to the closest
21794 block from point."
21795 (save-match-data
21796 (catch 'exit
21797 (let ((case-fold-search t)
21798 (lim-up (save-excursion (outline-previous-heading)))
21799 (lim-down (save-excursion (outline-next-heading))))
21800 (mapc (lambda (name)
21801 (let ((n (regexp-quote name)))
21802 (when (org-between-regexps-p
21803 (concat "^[ \t]*#\\+begin_" n)
21804 (concat "^[ \t]*#\\+end_" n)
21805 lim-up lim-down)
21806 (throw 'exit n))))
21807 names))
21808 nil)))
21810 (defun org-in-drawer-p ()
21811 "Non-nil if point is within a drawer.
21812 If point is within a drawer, return it, as parsed data."
21813 (let ((element (save-match-data (org-element-at-point))))
21814 (while (and element (not (memq (org-element-type element)
21815 '(drawer property-drawer))))
21816 (setq element (org-element-property :parent element)))
21817 element))
21819 (defun org-occur-in-agenda-files (regexp &optional nlines)
21820 "Call `multi-occur' with buffers for all agenda files."
21821 (interactive "sOrg-files matching: \np")
21822 (let* ((files (org-agenda-files))
21823 (tnames (mapcar 'file-truename files))
21824 (extra org-agenda-text-search-extra-files)
21826 (when (eq (car extra) 'agenda-archives)
21827 (setq extra (cdr extra))
21828 (setq files (org-add-archive-files files)))
21829 (while (setq f (pop extra))
21830 (unless (member (file-truename f) tnames)
21831 (add-to-list 'files f 'append)
21832 (add-to-list 'tnames (file-truename f) 'append)))
21833 (multi-occur
21834 (mapcar (lambda (x)
21835 (with-current-buffer
21836 (or (get-file-buffer x) (find-file-noselect x))
21837 (widen)
21838 (current-buffer)))
21839 files)
21840 regexp)))
21842 (if (boundp 'occur-mode-find-occurrence-hook)
21843 ;; Emacs 23
21844 (add-hook 'occur-mode-find-occurrence-hook
21845 (lambda ()
21846 (when (derived-mode-p 'org-mode)
21847 (org-reveal))))
21848 ;; Emacs 22
21849 (defadvice occur-mode-goto-occurrence
21850 (after org-occur-reveal activate)
21851 (and (derived-mode-p 'org-mode) (org-reveal)))
21852 (defadvice occur-mode-goto-occurrence-other-window
21853 (after org-occur-reveal activate)
21854 (and (derived-mode-p 'org-mode) (org-reveal)))
21855 (defadvice occur-mode-display-occurrence
21856 (after org-occur-reveal activate)
21857 (when (derived-mode-p 'org-mode)
21858 (let ((pos (occur-mode-find-occurrence)))
21859 (with-current-buffer (marker-buffer pos)
21860 (save-excursion
21861 (goto-char pos)
21862 (org-reveal)))))))
21864 (defun org-occur-link-in-agenda-files ()
21865 "Create a link and search for it in the agendas.
21866 The link is not stored in `org-stored-links', it is just created
21867 for the search purpose."
21868 (interactive)
21869 (let ((link (condition-case nil
21870 (org-store-link nil)
21871 (error "Unable to create a link to here"))))
21872 (org-occur-in-agenda-files (regexp-quote link))))
21874 (defun org-reverse-string (string)
21875 "Return the reverse of STRING."
21876 (apply 'string (reverse (string-to-list string))))
21878 (defun org-uniquify-alist (alist)
21879 "Merge elements of ALIST with the same key.
21881 For example, in this alist:
21883 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
21884 => '((a 1 3) (b 2))
21886 merge (a 1) and (a 3) into (a 1 3).
21888 The function returns the new ALIST."
21889 (let (rtn)
21890 (mapc
21891 (lambda (e)
21892 (let (n)
21893 (if (not (assoc (car e) rtn))
21894 (push e rtn)
21895 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
21896 (setq rtn (assq-delete-all (car e) rtn))
21897 (push n rtn))))
21898 alist)
21899 rtn))
21901 (defun org-delete-all (elts list)
21902 "Remove all elements in ELTS from LIST."
21903 (while elts
21904 (setq list (delete (pop elts) list)))
21905 list)
21907 (defun org-count (cl-item cl-seq)
21908 "Count the number of occurrences of ITEM in SEQ.
21909 Taken from `count' in cl-seq.el with all keyword arguments removed."
21910 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21911 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21912 (while (< cl-start cl-end)
21913 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21914 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21915 (setq cl-start (1+ cl-start)))
21916 cl-count))
21918 (defun org-remove-if (predicate seq)
21919 "Remove everything from SEQ that fulfills PREDICATE."
21920 (let (res e)
21921 (while seq
21922 (setq e (pop seq))
21923 (if (not (funcall predicate e)) (push e res)))
21924 (nreverse res)))
21926 (defun org-remove-if-not (predicate seq)
21927 "Remove everything from SEQ that does not fulfill PREDICATE."
21928 (let (res e)
21929 (while seq
21930 (setq e (pop seq))
21931 (if (funcall predicate e) (push e res)))
21932 (nreverse res)))
21934 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21935 "Reduce two-argument FUNCTION across SEQ.
21936 Taken from `reduce' in cl-seq.el with all keyword arguments but
21937 \":initial-value\" removed."
21938 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21939 (cadr (memq :initial-value cl-keys)))
21940 (cl-seq (pop cl-seq))
21941 (t (funcall cl-func)))))
21942 (while cl-seq
21943 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21944 cl-accum))
21946 (defun org-every (pred seq)
21947 "Return true if PREDICATE is true of every element of SEQ.
21948 Adapted from `every' in cl.el."
21949 (catch 'org-every
21950 (mapc (lambda (e) (unless (funcall pred e) (throw 'org-every nil))) seq)
21953 (defun org-some (pred seq)
21954 "Return true if PREDICATE is true of any element of SEQ.
21955 Adapted from `some' in cl.el."
21956 (catch 'org-some
21957 (mapc (lambda (e) (when (funcall pred e) (throw 'org-some t))) seq)
21958 nil))
21960 (defun org-back-over-empty-lines ()
21961 "Move backwards over whitespace, to the beginning of the first empty line.
21962 Returns the number of empty lines passed."
21963 (let ((pos (point)))
21964 (if (cdr (assoc 'heading org-blank-before-new-entry))
21965 (skip-chars-backward " \t\n\r")
21966 (unless (eobp)
21967 (forward-line -1)))
21968 (beginning-of-line 2)
21969 (goto-char (min (point) pos))
21970 (count-lines (point) pos)))
21972 (defun org-skip-whitespace ()
21973 (skip-chars-forward " \t\n\r"))
21975 (defun org-point-in-group (point group &optional context)
21976 "Check if POINT is in match-group GROUP.
21977 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21978 match. If the match group does not exist or point is not inside it,
21979 return nil."
21980 (and (match-beginning group)
21981 (>= point (match-beginning group))
21982 (<= point (match-end group))
21983 (if context
21984 (list context (match-beginning group) (match-end group))
21985 t)))
21987 (defun org-switch-to-buffer-other-window (&rest args)
21988 "Switch to buffer in a second window on the current frame.
21989 In particular, do not allow pop-up frames.
21990 Returns the newly created buffer."
21991 (org-no-popups
21992 (apply 'switch-to-buffer-other-window args)))
21994 (defun org-combine-plists (&rest plists)
21995 "Create a single property list from all plists in PLISTS.
21996 The process starts by copying the first list, and then setting properties
21997 from the other lists. Settings in the last list are the most significant
21998 ones and overrule settings in the other lists."
21999 (let ((rtn (copy-sequence (pop plists)))
22000 p v ls)
22001 (while plists
22002 (setq ls (pop plists))
22003 (while ls
22004 (setq p (pop ls) v (pop ls))
22005 (setq rtn (plist-put rtn p v))))
22006 rtn))
22008 (defun org-replace-escapes (string table)
22009 "Replace %-escapes in STRING with values in TABLE.
22010 TABLE is an association list with keys like \"%a\" and string values.
22011 The sequences in STRING may contain normal field width and padding information,
22012 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22013 so values can contain further %-escapes if they are define later in TABLE."
22014 (let ((tbl (copy-alist table))
22015 (case-fold-search nil)
22016 (pchg 0)
22017 e re rpl)
22018 (while (setq e (pop tbl))
22019 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22020 (when (and (cdr e) (string-match re (cdr e)))
22021 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22022 (safe "SREF"))
22023 (add-text-properties 0 3 (list 'sref sref) safe)
22024 (setcdr e (replace-match safe t t (cdr e)))))
22025 (while (string-match re string)
22026 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22027 (cdr e)))
22028 (setq string (replace-match rpl t t string))))
22029 (while (setq pchg (next-property-change pchg string))
22030 (let ((sref (get-text-property pchg 'sref string)))
22031 (when (and sref (string-match "SREF" string pchg))
22032 (setq string (replace-match sref t t string)))))
22033 string))
22035 (defun org-sublist (list start end)
22036 "Return a section of LIST, from START to END.
22037 Counting starts at 1."
22038 (let (rtn (c start))
22039 (setq list (nthcdr (1- start) list))
22040 (while (and list (<= c end))
22041 (push (pop list) rtn)
22042 (setq c (1+ c)))
22043 (nreverse rtn)))
22045 (defun org-find-base-buffer-visiting (file)
22046 "Like `find-buffer-visiting' but always return the base buffer and
22047 not an indirect buffer."
22048 (let ((buf (or (get-file-buffer file)
22049 (find-buffer-visiting file))))
22050 (if buf
22051 (or (buffer-base-buffer buf) buf)
22052 nil)))
22054 (defun org-image-file-name-regexp (&optional extensions)
22055 "Return regexp matching the file names of images.
22056 If EXTENSIONS is given, only match these."
22057 (if (and (not extensions) (fboundp 'image-file-name-regexp))
22058 (image-file-name-regexp)
22059 (let ((image-file-name-extensions
22060 (or extensions
22061 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
22062 "xbm" "xpm" "pbm" "pgm" "ppm"))))
22063 (concat "\\."
22064 (regexp-opt (nconc (mapcar 'upcase
22065 image-file-name-extensions)
22066 image-file-name-extensions)
22068 "\\'"))))
22070 (defun org-file-image-p (file &optional extensions)
22071 "Return non-nil if FILE is an image."
22072 (save-match-data
22073 (string-match (org-image-file-name-regexp extensions) file)))
22075 (defun org-get-cursor-date (&optional with-time)
22076 "Return the date at cursor in as a time.
22077 This works in the calendar and in the agenda, anywhere else it just
22078 returns the current time.
22079 If WITH-TIME is non-nil, returns the time of the event at point (in
22080 the agenda) or the current time of the day."
22081 (let (date day defd tp tm hod mod)
22082 (when with-time
22083 (setq tp (get-text-property (point) 'time))
22084 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22085 (setq hod (string-to-number (match-string 1 tp))
22086 mod (string-to-number (match-string 2 tp))))
22087 (or tp (setq hod (nth 2 (decode-time (current-time)))
22088 mod (nth 1 (decode-time (current-time))))))
22089 (cond
22090 ((eq major-mode 'calendar-mode)
22091 (setq date (calendar-cursor-to-date)
22092 defd (encode-time 0 (or mod 0) (or hod 0)
22093 (nth 1 date) (nth 0 date) (nth 2 date))))
22094 ((eq major-mode 'org-agenda-mode)
22095 (setq day (get-text-property (point) 'day))
22096 (if day
22097 (setq date (calendar-gregorian-from-absolute day)
22098 defd (encode-time 0 (or mod 0) (or hod 0)
22099 (nth 1 date) (nth 0 date) (nth 2 date))))))
22100 (or defd (current-time))))
22102 (defun org-mark-subtree (&optional up)
22103 "Mark the current subtree.
22104 This puts point at the start of the current subtree, and mark at
22105 the end. If a numeric prefix UP is given, move up into the
22106 hierarchy of headlines by UP levels before marking the subtree."
22107 (interactive "P")
22108 (org-with-limited-levels
22109 (cond ((org-at-heading-p) (beginning-of-line))
22110 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22111 (t (outline-previous-visible-heading 1))))
22112 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
22113 (if (org-called-interactively-p 'any)
22114 (call-interactively 'org-mark-element)
22115 (org-mark-element)))
22118 ;;; Indentation
22120 (defun org-indent-line ()
22121 "Indent line depending on context."
22122 (interactive)
22123 (let* ((pos (point))
22124 (itemp (org-at-item-p))
22125 (case-fold-search t)
22126 (org-drawer-regexp (or org-drawer-regexp "\000"))
22127 (inline-task-p (and (featurep 'org-inlinetask)
22128 (org-inlinetask-in-task-p)))
22129 (inline-re (and inline-task-p
22130 (org-inlinetask-outline-regexp)))
22131 column)
22132 (if (and orgstruct-is-++ (eq pos (point)))
22133 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
22134 (indent-according-to-mode))
22135 (beginning-of-line 1)
22136 (cond
22137 ;; Headings
22138 ((looking-at org-outline-regexp) (setq column 0))
22139 ;; Footnote definition
22140 ((looking-at org-footnote-definition-re) (setq column 0))
22141 ;; Literal examples
22142 ((looking-at "[ \t]*:\\( \\|$\\)")
22143 (setq column (org-get-indentation))) ; do nothing
22144 ;; Lists
22145 ((ignore-errors (goto-char (org-in-item-p)))
22146 (setq column (if itemp
22147 (org-get-indentation)
22148 (org-list-item-body-column (point))))
22149 (goto-char pos))
22150 ;; Drawers
22151 ((and (looking-at "[ \t]*:END:")
22152 (save-excursion (re-search-backward org-drawer-regexp nil t)))
22153 (save-excursion
22154 (goto-char (1- (match-beginning 1)))
22155 (setq column (current-column))))
22156 ;; Special blocks
22157 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
22158 (save-excursion
22159 (re-search-backward
22160 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
22161 (setq column (org-get-indentation (match-string 0))))
22162 ((and (not (looking-at "[ \t]*#\\+begin_"))
22163 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
22164 (save-excursion
22165 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
22166 (setq column
22167 (cond ((equal (downcase (match-string 1)) "src")
22168 ;; src blocks: let `org-edit-src-exit' handle them
22169 (org-get-indentation))
22170 ((equal (downcase (match-string 1)) "example")
22171 (max (org-get-indentation)
22172 (org-get-indentation (match-string 0))))
22174 (org-get-indentation (match-string 0))))))
22175 ;; This line has nothing special, look at the previous relevant
22176 ;; line to compute indentation
22178 (beginning-of-line 0)
22179 (while (and (not (bobp))
22180 (not (looking-at org-table-line-regexp))
22181 (not (looking-at org-drawer-regexp))
22182 ;; When point started in an inline task, do not move
22183 ;; above task starting line.
22184 (not (and inline-task-p (looking-at inline-re)))
22185 ;; Skip drawers, blocks, empty lines, verbatim,
22186 ;; comments, tables, footnotes definitions, lists,
22187 ;; inline tasks.
22188 (or (and (looking-at "[ \t]*:END:")
22189 (re-search-backward org-drawer-regexp nil t))
22190 (and (looking-at "[ \t]*#\\+end_")
22191 (re-search-backward "[ \t]*#\\+begin_"nil t))
22192 (looking-at "[ \t]*[\n:#|]")
22193 (looking-at org-footnote-definition-re)
22194 (and (not inline-task-p)
22195 (featurep 'org-inlinetask)
22196 (org-inlinetask-in-task-p)
22197 (or (org-inlinetask-goto-beginning) t))))
22198 (beginning-of-line 0))
22199 (cond
22200 ;; There was a list item above.
22201 ((ignore-errors (goto-char (org-in-item-p)))
22202 (goto-char (org-list-get-top-point (org-list-struct)))
22203 (setq column (org-get-indentation)))
22204 ;; There was an heading above.
22205 ((looking-at "\\*+[ \t]+")
22206 (if (not org-adapt-indentation)
22207 (setq column 0)
22208 (goto-char (match-end 0))
22209 (setq column (current-column))))
22210 ;; A drawer had started and is unfinished
22211 ((looking-at org-drawer-regexp)
22212 (goto-char (1- (match-beginning 1)))
22213 (setq column (current-column)))
22214 ;; Else, nothing noticeable found: get indentation and go on.
22215 (t (setq column (org-get-indentation))))))
22216 ;; Now apply indentation and move cursor accordingly
22217 (goto-char pos)
22218 (if (<= (current-column) (current-indentation))
22219 (org-indent-line-to column)
22220 (save-excursion (org-indent-line-to column)))
22221 ;; Special polishing for properties, see `org-property-format'
22222 (setq column (current-column))
22223 (beginning-of-line 1)
22224 (if (looking-at org-property-re)
22225 (replace-match (concat (match-string 4)
22226 (format org-property-format
22227 (match-string 1) (match-string 3)))
22228 t t))
22229 (org-move-to-column column))))
22231 (defun org-indent-drawer ()
22232 "Indent the drawer at point."
22233 (interactive)
22234 (let ((p (point))
22235 (e (and (save-excursion (re-search-forward ":END:" nil t))
22236 (match-end 0)))
22237 (folded
22238 (save-excursion
22239 (end-of-line)
22240 (when (overlays-at (point))
22241 (member 'invisible (overlay-properties
22242 (car (overlays-at (point)))))))))
22243 (when folded (org-cycle))
22244 (indent-for-tab-command)
22245 (while (and (move-beginning-of-line 2) (< (point) e))
22246 (indent-for-tab-command))
22247 (goto-char p)
22248 (when folded (org-cycle)))
22249 (message "Drawer at point indented"))
22251 (defun org-indent-block ()
22252 "Indent the block at point."
22253 (interactive)
22254 (let ((p (point))
22255 (case-fold-search t)
22256 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
22257 (match-end 0)))
22258 (folded
22259 (save-excursion
22260 (end-of-line)
22261 (when (overlays-at (point))
22262 (member 'invisible (overlay-properties
22263 (car (overlays-at (point)))))))))
22264 (when folded (org-cycle))
22265 (indent-for-tab-command)
22266 (while (and (move-beginning-of-line 2) (< (point) e))
22267 (indent-for-tab-command))
22268 (goto-char p)
22269 (when folded (org-cycle)))
22270 (message "Block at point indented"))
22272 (defun org-indent-region (start end)
22273 "Indent region."
22274 (interactive "r")
22275 (save-excursion
22276 (let ((line-end (org-current-line end)))
22277 (goto-char start)
22278 (while (< (org-current-line) line-end)
22279 (cond ((org-in-src-block-p t) (org-src-native-tab-command-maybe))
22280 (t (call-interactively 'org-indent-line)))
22281 (move-beginning-of-line 2)))))
22284 ;;; Filling
22286 ;; We use our own fill-paragraph and auto-fill functions.
22288 ;; `org-fill-paragraph' relies on adaptive filling and context
22289 ;; checking. Appropriate `fill-prefix' is computed with
22290 ;; `org-adaptive-fill-function'.
22292 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22293 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22294 ;; `org-adaptive-fill-function' value. Internally,
22295 ;; `org-comment-line-break-function' breaks the line.
22297 ;; `org-setup-filling' installs filling and auto-filling related
22298 ;; variables during `org-mode' initialization.
22300 (defvar org-element-paragraph-separate) ; org-element.el
22301 (defun org-setup-filling ()
22302 (require 'org-element)
22303 ;; Prevent auto-fill from inserting unwanted new items.
22304 (when (boundp 'fill-nobreak-predicate)
22305 (org-set-local
22306 'fill-nobreak-predicate
22307 (org-uniquify
22308 (append fill-nobreak-predicate
22309 '(org-fill-line-break-nobreak-p
22310 org-fill-paragraph-with-timestamp-nobreak-p)))))
22311 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22312 (org-set-local 'paragraph-start paragraph-ending)
22313 (org-set-local 'paragraph-separate paragraph-ending))
22314 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22315 (org-set-local 'auto-fill-inhibit-regexp nil)
22316 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22317 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22318 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22320 (defun org-fill-line-break-nobreak-p ()
22321 "Non-nil when a new line at point would create an Org line break."
22322 (save-excursion
22323 (skip-chars-backward "[ \t]")
22324 (skip-chars-backward "\\\\")
22325 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22327 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22328 "Non-nil when a new line at point would split a timestamp."
22329 (and (org-at-timestamp-p t)
22330 (not (looking-at org-ts-regexp-both))))
22332 (declare-function message-in-body-p "message" ())
22333 (defvar orgtbl-line-start-regexp) ; From org-table.el
22334 (defun org-adaptive-fill-function ()
22335 "Compute a fill prefix for the current line.
22336 Return fill prefix, as a string, or nil if current line isn't
22337 meant to be filled. For convenience, if `adaptive-fill-regexp'
22338 matches in paragraphs or comments, use it."
22339 (catch 'exit
22340 (when (derived-mode-p 'message-mode)
22341 (save-excursion
22342 (beginning-of-line)
22343 (cond ((or (not (message-in-body-p))
22344 (looking-at orgtbl-line-start-regexp))
22345 (throw 'exit nil))
22346 ((looking-at message-cite-prefix-regexp)
22347 (throw 'exit (match-string-no-properties 0)))
22348 ((looking-at org-outline-regexp)
22349 (throw 'exit (make-string (length (match-string 0)) ? ))))))
22350 (org-with-wide-buffer
22351 (let* ((p (line-beginning-position))
22352 (element (save-excursion
22353 (beginning-of-line)
22354 (or (ignore-errors (org-element-at-point))
22355 (user-error "An element cannot be parsed line %d"
22356 (line-number-at-pos (point))))))
22357 (type (org-element-type element))
22358 (post-affiliated (org-element-property :post-affiliated element)))
22359 (unless (and post-affiliated (< p post-affiliated))
22360 (case type
22361 (comment
22362 (save-excursion
22363 (beginning-of-line)
22364 (looking-at "[ \t]*")
22365 (concat (match-string 0) "# ")))
22366 (footnote-definition "")
22367 ((item plain-list)
22368 (make-string (org-list-item-body-column
22369 (or post-affiliated
22370 (org-element-property :begin element)))
22371 ? ))
22372 (paragraph
22373 ;; Fill prefix is usually the same as the current line,
22374 ;; unless the paragraph is at the beginning of an item.
22375 (let ((parent (org-element-property :parent element)))
22376 (save-excursion
22377 (beginning-of-line)
22378 (cond ((eq (org-element-type parent) 'item)
22379 (make-string (org-list-item-body-column
22380 (org-element-property :begin parent))
22381 ? ))
22382 ((and adaptive-fill-regexp
22383 ;; Locally disable
22384 ;; `adaptive-fill-function' to let
22385 ;; `fill-context-prefix' handle
22386 ;; `adaptive-fill-regexp' variable.
22387 (let (adaptive-fill-function)
22388 (fill-context-prefix
22389 post-affiliated
22390 (org-element-property :end element)))))
22391 ((looking-at "[ \t]+") (match-string 0))
22392 (t "")))))
22393 (comment-block
22394 ;; Only fill contents if P is within block boundaries.
22395 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22396 (forward-line)
22397 (point)))
22398 (cend (save-excursion
22399 (goto-char (org-element-property :end element))
22400 (skip-chars-backward " \r\t\n")
22401 (line-beginning-position))))
22402 (when (and (>= p cbeg) (< p cend))
22403 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22404 (match-string 0)
22405 ""))))))))))
22407 (declare-function message-goto-body "message" ())
22408 (defvar message-cite-prefix-regexp) ; From message.el
22409 (defun org-fill-paragraph (&optional justify)
22410 "Fill element at point, when applicable.
22412 This function only applies to comment blocks, comments, example
22413 blocks and paragraphs. Also, as a special case, re-align table
22414 when point is at one.
22416 If JUSTIFY is non-nil (interactively, with prefix argument),
22417 justify as well. If `sentence-end-double-space' is non-nil, then
22418 period followed by one space does not end a sentence, so don't
22419 break a line there. The variable `fill-column' controls the
22420 width for filling.
22422 For convenience, when point is at a plain list, an item or
22423 a footnote definition, try to fill the first paragraph within."
22424 (interactive)
22425 (if (and (derived-mode-p 'message-mode)
22426 (or (not (message-in-body-p))
22427 (save-excursion (move-beginning-of-line 1)
22428 (looking-at message-cite-prefix-regexp))))
22429 ;; First ensure filling is correct in message-mode.
22430 (let ((fill-paragraph-function
22431 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22432 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22433 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22434 (paragraph-separate
22435 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22436 (fill-paragraph nil))
22437 (with-syntax-table org-mode-transpose-word-syntax-table
22438 ;; Move to end of line in order to get the first paragraph
22439 ;; within a plain list or a footnote definition.
22440 (let ((element (save-excursion
22441 (end-of-line)
22442 (or (ignore-errors (org-element-at-point))
22443 (user-error "An element cannot be parsed line %d"
22444 (line-number-at-pos (point)))))))
22445 ;; First check if point is in a blank line at the beginning of
22446 ;; the buffer. In that case, ignore filling.
22447 (case (org-element-type element)
22448 ;; Use major mode filling function is src blocks.
22449 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22450 ;; Align Org tables, leave table.el tables as-is.
22451 (table-row (org-table-align) t)
22452 (table
22453 (when (eq (org-element-property :type element) 'org)
22454 (save-excursion
22455 (goto-char (org-element-property :post-affiliated element))
22456 (org-table-align)))
22458 (paragraph
22459 ;; Paragraphs may contain `line-break' type objects.
22460 (let ((beg (max (point-min)
22461 (org-element-property :contents-begin element)))
22462 (end (min (point-max)
22463 (org-element-property :contents-end element))))
22464 ;; Do nothing if point is at an affiliated keyword.
22465 (if (< (line-end-position) beg) t
22466 (when (derived-mode-p 'message-mode)
22467 ;; In `message-mode', do not fill following citation
22468 ;; in current paragraph nor text before message body.
22469 (let ((body-start (save-excursion (message-goto-body))))
22470 (when body-start (setq beg (max body-start beg))))
22471 (when (save-excursion
22472 (re-search-forward
22473 (concat "^" message-cite-prefix-regexp) end t))
22474 (setq end (match-beginning 0))))
22475 ;; Fill paragraph, taking line breaks into account.
22476 ;; For that, slice the paragraph using line breaks as
22477 ;; separators, and fill the parts in reverse order to
22478 ;; avoid messing with markers.
22479 (save-excursion
22480 (goto-char end)
22481 (mapc
22482 (lambda (pos)
22483 (fill-region-as-paragraph pos (point) justify)
22484 (goto-char pos))
22485 ;; Find the list of ending positions for line breaks
22486 ;; in the current paragraph. Add paragraph
22487 ;; beginning to include first slice.
22488 (nreverse
22489 (cons beg
22490 (org-element-map
22491 (org-element--parse-objects
22492 beg end nil (org-element-restriction 'paragraph))
22493 'line-break
22494 (lambda (lb) (org-element-property :end lb)))))))
22495 t)))
22496 ;; Contents of `comment-block' type elements should be
22497 ;; filled as plain text, but only if point is within block
22498 ;; markers.
22499 (comment-block
22500 (let* ((case-fold-search t)
22501 (beg (save-excursion
22502 (goto-char (org-element-property :begin element))
22503 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22504 (forward-line)
22505 (point)))
22506 (end (save-excursion
22507 (goto-char (org-element-property :end element))
22508 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22509 (line-beginning-position))))
22510 (if (or (< (point) beg) (> (point) end)) t
22511 (fill-region-as-paragraph
22512 (save-excursion (end-of-line)
22513 (re-search-backward "^[ \t]*$" beg 'move)
22514 (line-beginning-position))
22515 (save-excursion (beginning-of-line)
22516 (re-search-forward "^[ \t]*$" end 'move)
22517 (line-beginning-position))
22518 justify))))
22519 ;; Fill comments.
22520 (comment
22521 (let ((begin (org-element-property :post-affiliated element))
22522 (end (org-element-property :end element)))
22523 (when (and (>= (point) begin) (<= (point) end))
22524 (let ((begin (save-excursion
22525 (end-of-line)
22526 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22527 (progn (forward-line) (point))
22528 begin)))
22529 (end (save-excursion
22530 (end-of-line)
22531 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22532 (1- (line-beginning-position))
22533 (skip-chars-backward " \r\t\n")
22534 (line-end-position)))))
22535 ;; Do not fill comments when at a blank line.
22536 (when (> end begin)
22537 (let ((fill-prefix
22538 (save-excursion
22539 (beginning-of-line)
22540 (looking-at "[ \t]*#")
22541 (let ((comment-prefix (match-string 0)))
22542 (goto-char (match-end 0))
22543 (if (looking-at adaptive-fill-regexp)
22544 (concat comment-prefix (match-string 0))
22545 (concat comment-prefix " "))))))
22546 (save-excursion
22547 (fill-region-as-paragraph begin end justify))))))
22549 ;; Ignore every other element.
22550 (otherwise t))))))
22552 (defun org-auto-fill-function ()
22553 "Auto-fill function."
22554 ;; Check if auto-filling is meaningful.
22555 (let ((fc (current-fill-column)))
22556 (when (and fc (> (current-column) fc))
22557 (let* ((fill-prefix (org-adaptive-fill-function))
22558 ;; Enforce empty fill prefix, if required. Otherwise, it
22559 ;; will be computed again.
22560 (adaptive-fill-mode (not (equal fill-prefix ""))))
22561 (when fill-prefix (do-auto-fill))))))
22563 (defun org-comment-line-break-function (&optional soft)
22564 "Break line at point and indent, continuing comment if within one.
22565 The inserted newline is marked hard if variable
22566 `use-hard-newlines' is true, unless optional argument SOFT is
22567 non-nil."
22568 (if soft (insert-and-inherit ?\n) (newline 1))
22569 (save-excursion (forward-char -1) (delete-horizontal-space))
22570 (delete-horizontal-space)
22571 (indent-to-left-margin)
22572 (insert-before-markers-and-inherit fill-prefix))
22575 ;;; Comments
22577 ;; Org comments syntax is quite complex. It requires the entire line
22578 ;; to be just a comment. Also, even with the right syntax at the
22579 ;; beginning of line, some some elements (i.e. verse-block or
22580 ;; example-block) don't accept comments. Usual Emacs comment commands
22581 ;; cannot cope with those requirements. Therefore, Org replaces them.
22583 ;; Org still relies on `comment-dwim', but cannot trust
22584 ;; `comment-only-p'. So, `comment-region-function' and
22585 ;; `uncomment-region-function' both point
22586 ;; to`org-comment-or-uncomment-region'. Eventually,
22587 ;; `org-insert-comment' takes care of insertion of comments at the
22588 ;; beginning of line.
22590 ;; `org-setup-comments-handling' install comments related variables
22591 ;; during `org-mode' initialization.
22593 (defun org-setup-comments-handling ()
22594 (interactive)
22595 (org-set-local 'comment-use-syntax nil)
22596 (org-set-local 'comment-start "# ")
22597 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22598 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22599 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22600 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22602 (defun org-insert-comment ()
22603 "Insert an empty comment above current line.
22604 If the line is empty, insert comment at its beginning. When
22605 point is within a source block, comment according to the related
22606 major mode."
22607 (if (let ((element (org-element-at-point)))
22608 (and (eq (org-element-type element) 'src-block)
22609 (< (save-excursion
22610 (goto-char (org-element-property :post-affiliated element))
22611 (line-end-position))
22612 (point))
22613 (> (save-excursion
22614 (goto-char (org-element-property :end element))
22615 (skip-chars-backward " \r\t\n")
22616 (line-beginning-position))
22617 (point))))
22618 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim))
22619 (beginning-of-line)
22620 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
22621 (open-line 1))
22622 (org-indent-line)
22623 (insert "# ")))
22625 (defvar comment-empty-lines) ; From newcomment.el.
22626 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22627 "Comment or uncomment each non-blank line in the region.
22628 Uncomment each non-blank line between BEG and END if it only
22629 contains commented lines. Otherwise, comment them. If region is
22630 strictly within a source block, use appropriate comment syntax."
22631 (if (let ((element (org-element-at-point)))
22632 (and (eq (org-element-type element) 'src-block)
22633 (< (save-excursion
22634 (goto-char (org-element-property :post-affiliated element))
22635 (line-end-position))
22636 beg)
22637 (>= (save-excursion
22638 (goto-char (org-element-property :end element))
22639 (skip-chars-backward " \r\t\n")
22640 (line-beginning-position))
22641 end)))
22642 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim))
22643 (save-restriction
22644 ;; Restrict region
22645 (narrow-to-region (save-excursion (goto-char beg)
22646 (skip-chars-forward " \r\t\n" end)
22647 (line-beginning-position))
22648 (save-excursion (goto-char end)
22649 (skip-chars-backward " \r\t\n" beg)
22650 (line-end-position)))
22651 (let ((uncommentp
22652 ;; UNCOMMENTP is non-nil when every non blank line between
22653 ;; BEG and END is a comment.
22654 (save-excursion
22655 (goto-char (point-min))
22656 (while (and (not (eobp))
22657 (let ((element (org-element-at-point)))
22658 (and (eq (org-element-type element) 'comment)
22659 (goto-char (min (point-max)
22660 (org-element-property
22661 :end element)))))))
22662 (eobp))))
22663 (if uncommentp
22664 ;; Only blank lines and comments in region: uncomment it.
22665 (save-excursion
22666 (goto-char (point-min))
22667 (while (not (eobp))
22668 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22669 (replace-match "" nil nil nil 1))
22670 (forward-line)))
22671 ;; Comment each line in region.
22672 (let ((min-indent (point-max)))
22673 ;; First find the minimum indentation across all lines.
22674 (save-excursion
22675 (goto-char (point-min))
22676 (while (and (not (eobp)) (not (zerop min-indent)))
22677 (unless (looking-at "[ \t]*$")
22678 (setq min-indent (min min-indent (current-indentation))))
22679 (forward-line)))
22680 ;; Then loop over all lines.
22681 (save-excursion
22682 (goto-char (point-min))
22683 (while (not (eobp))
22684 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22685 ;; Don't get fooled by invisible text (e.g. link path)
22686 ;; when moving to column MIN-INDENT.
22687 (let ((buffer-invisibility-spec nil))
22688 (org-move-to-column min-indent t))
22689 (insert comment-start))
22690 (forward-line)))))))))
22692 (defun org-comment-dwim (arg)
22693 (interactive "*P")
22694 "Call `comment-dwim' within a source edit buffer if needed."
22695 (if (org-in-src-block-p)
22696 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim))
22697 (call-interactively #'comment-dwim)))
22700 ;;; Planning
22702 ;; This section contains tools to operate on timestamp objects, as
22703 ;; returned by, e.g. `org-element-context'.
22705 (defun org-timestamp-has-time-p (timestamp)
22706 "Non-nil when TIMESTAMP has a time specified."
22707 (org-element-property :hour-start timestamp))
22709 (defun org-timestamp-format (timestamp format &optional end utc)
22710 "Format a TIMESTAMP element into a string.
22712 FORMAT is a format specifier to be passed to
22713 `format-time-string'.
22715 When optional argument END is non-nil, use end of date-range or
22716 time-range, if possible.
22718 When optional argument UTC is non-nil, time will be expressed as
22719 Universal Time."
22720 (format-time-string
22721 format
22722 (apply 'encode-time
22723 (cons 0
22724 (mapcar
22725 (lambda (prop) (or (org-element-property prop timestamp) 0))
22726 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22727 '(:minute-start :hour-start :day-start :month-start
22728 :year-start)))))
22729 utc))
22731 (defun org-timestamp-split-range (timestamp &optional end)
22732 "Extract a timestamp object from a date or time range.
22734 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22735 the end of the range. Otherwise, extract its start.
22737 Return a new timestamp object sharing the same parent as
22738 TIMESTAMP."
22739 (let ((type (org-element-property :type timestamp)))
22740 (if (memq type '(active inactive diary)) timestamp
22741 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22742 ;; Set new type.
22743 (org-element-put-property
22744 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22745 ;; Copy start properties over end properties if END is
22746 ;; non-nil. Otherwise, copy end properties over `start' ones.
22747 (let ((p-alist '((:minute-start . :minute-end)
22748 (:hour-start . :hour-end)
22749 (:day-start . :day-end)
22750 (:month-start . :month-end)
22751 (:year-start . :year-end))))
22752 (dolist (p-cell p-alist)
22753 (org-element-put-property
22754 split-ts
22755 (funcall (if end 'car 'cdr) p-cell)
22756 (org-element-property
22757 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22758 ;; Eventually refresh `:raw-value'.
22759 (org-element-put-property split-ts :raw-value nil)
22760 (org-element-put-property
22761 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22763 (defun org-timestamp-translate (timestamp &optional boundary)
22764 "Apply `org-translate-time' on a TIMESTAMP object.
22765 When optional argument BOUNDARY is non-nil, it is either the
22766 symbol `start' or `end'. In this case, only translate the
22767 starting or ending part of TIMESTAMP if it is a date or time
22768 range. Otherwise, translate both parts."
22769 (if (and (not boundary)
22770 (memq (org-element-property :type timestamp)
22771 '(active-range inactive-range)))
22772 (concat
22773 (org-translate-time
22774 (org-element-property :raw-value
22775 (org-timestamp-split-range timestamp)))
22776 "--"
22777 (org-translate-time
22778 (org-element-property :raw-value
22779 (org-timestamp-split-range timestamp t))))
22780 (org-translate-time
22781 (org-element-property
22782 :raw-value
22783 (if (not boundary) timestamp
22784 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22788 ;;; Other stuff.
22790 (defun org-toggle-fixed-width-section (arg)
22791 "Toggle the fixed-width export.
22792 If there is no active region, the QUOTE keyword at the current headline is
22793 inserted or removed. When present, it causes the text between this headline
22794 and the next to be exported as fixed-width text, and unmodified.
22795 If there is an active region, this command adds or removes a colon as the
22796 first character of this line. If the first character of a line is a colon,
22797 this line is also exported in fixed-width font."
22798 (interactive "P")
22799 (let* ((cc 0)
22800 (regionp (org-region-active-p))
22801 (beg (if regionp (region-beginning) (point)))
22802 (end (if regionp (region-end)))
22803 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22804 (case-fold-search nil)
22805 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22806 off)
22807 (if regionp
22808 (save-excursion
22809 (goto-char beg)
22810 (setq cc (current-column))
22811 (beginning-of-line 1)
22812 (setq off (looking-at re))
22813 (while (> nlines 0)
22814 (setq nlines (1- nlines))
22815 (beginning-of-line 1)
22816 (cond
22817 (arg
22818 (org-move-to-column cc t)
22819 (insert ": \n")
22820 (forward-line -1))
22821 ((and off (looking-at re))
22822 (replace-match "" t t nil 1))
22823 ((not off) (org-move-to-column cc t) (insert ": ")))
22824 (forward-line 1)))
22825 (save-excursion
22826 (org-back-to-heading)
22827 (cond
22828 ((looking-at (format org-heading-keyword-regexp-format
22829 org-quote-string))
22830 (goto-char (match-end 1))
22831 (looking-at (concat " +" org-quote-string))
22832 (replace-match "" t t)
22833 (when (eolp) (insert " ")))
22834 ((looking-at org-outline-regexp)
22835 (goto-char (match-end 0))
22836 (insert org-quote-string " ")))))))
22838 (defun org-reftex-citation ()
22839 "Use reftex-citation to insert a citation into the buffer.
22840 This looks for a line like
22842 #+BIBLIOGRAPHY: foo plain option:-d
22844 and derives from it that foo.bib is the bibliography file relevant
22845 for this document. It then installs the necessary environment for RefTeX
22846 to work in this buffer and calls `reftex-citation' to insert a citation
22847 into the buffer.
22849 Export of such citations to both LaTeX and HTML is handled by the contributed
22850 package ox-bibtex by Taru Karttunen."
22851 (interactive)
22852 (let ((reftex-docstruct-symbol 'rds)
22853 (reftex-cite-format "\\cite{%l}")
22854 rds bib)
22855 (save-excursion
22856 (save-restriction
22857 (widen)
22858 (let ((case-fold-search t)
22859 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22860 (if (not (save-excursion
22861 (or (re-search-forward re nil t)
22862 (re-search-backward re nil t))))
22863 (error "No bibliography defined in file")
22864 (setq bib (concat (match-string 1) ".bib")
22865 rds (list (list 'bib bib)))))))
22866 (call-interactively 'reftex-citation)))
22868 ;;;; Functions extending outline functionality
22870 (defun org-beginning-of-line (&optional arg)
22871 "Go to the beginning of the current line. If that is invisible, continue
22872 to a visible line beginning. This makes the function of C-a more intuitive.
22873 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22874 first attempt, and only move to after the tags when the cursor is already
22875 beyond the end of the headline."
22876 (interactive "P")
22877 (let ((pos (point))
22878 (special (if (consp org-special-ctrl-a/e)
22879 (car org-special-ctrl-a/e)
22880 org-special-ctrl-a/e))
22881 deactivate-mark refpos)
22882 (if (org-bound-and-true-p visual-line-mode)
22883 (beginning-of-visual-line 1)
22884 (beginning-of-line 1))
22885 (if (and arg (fboundp 'move-beginning-of-line))
22886 (call-interactively 'move-beginning-of-line)
22887 (if (bobp)
22889 (backward-char 1)
22890 (if (org-truely-invisible-p)
22891 (while (and (not (bobp)) (org-truely-invisible-p))
22892 (backward-char 1)
22893 (beginning-of-line 1))
22894 (forward-char 1))))
22895 (when special
22896 (cond
22897 ((and (looking-at org-complex-heading-regexp)
22898 (= (char-after (match-end 1)) ?\ ))
22899 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22900 (point-at-eol)))
22901 (goto-char
22902 (if (eq special t)
22903 (cond ((> pos refpos) refpos)
22904 ((= pos (point)) refpos)
22905 (t (point)))
22906 (cond ((> pos (point)) (point))
22907 ((not (eq last-command this-command)) (point))
22908 (t refpos)))))
22909 ((org-at-item-p)
22910 ;; Being at an item and not looking at an the item means point
22911 ;; was previously moved to beginning of a visual line, which
22912 ;; doesn't contain the item. Therefore, do nothing special,
22913 ;; just stay here.
22914 (when (looking-at org-list-full-item-re)
22915 ;; Set special position at first white space character after
22916 ;; bullet, and check-box, if any.
22917 (let ((after-bullet
22918 (let ((box (match-end 3)))
22919 (if (not box) (match-end 1)
22920 (let ((after (char-after box)))
22921 (if (and after (= after ? )) (1+ box) box))))))
22922 ;; Special case: Move point to special position when
22923 ;; currently after it or at beginning of line.
22924 (if (eq special t)
22925 (when (or (> pos after-bullet) (= (point) pos))
22926 (goto-char after-bullet))
22927 ;; Reversed case: Move point to special position when
22928 ;; point was already at beginning of line and command is
22929 ;; repeated.
22930 (when (and (= (point) pos) (eq last-command this-command))
22931 (goto-char after-bullet))))))))
22932 (org-no-warnings
22933 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22934 (setq disable-point-adjustment
22935 (or (not (invisible-p (point)))
22936 (not (invisible-p (max (point-min) (1- (point))))))))
22938 (defun org-end-of-line (&optional arg)
22939 "Go to the end of the line.
22940 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22941 tags on the first attempt, and only move to after the tags when
22942 the cursor is already beyond the end of the headline."
22943 (interactive "P")
22944 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22945 org-special-ctrl-a/e))
22946 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22947 'end-of-visual-line)
22948 ((fboundp 'move-end-of-line) 'move-end-of-line)
22949 (t 'end-of-line)))
22950 deactivate-mark)
22951 (if (or (not special) arg) (call-interactively move-fun)
22952 (let* ((element (save-excursion (beginning-of-line)
22953 (org-element-at-point)))
22954 (type (org-element-type element)))
22955 (cond
22956 ((memq type '(headline inlinetask))
22957 (let ((pos (point)))
22958 (beginning-of-line 1)
22959 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22960 (if (eq special t)
22961 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22962 (goto-char (match-beginning 1))
22963 (goto-char (match-end 0)))
22964 (if (or (< pos (match-end 0))
22965 (not (eq this-command last-command)))
22966 (goto-char (match-end 0))
22967 (goto-char (match-beginning 1))))
22968 (call-interactively move-fun))))
22969 ((outline-invisible-p (line-end-position))
22970 ;; If element is hidden, `move-end-of-line' would put point
22971 ;; after it. Use `end-of-line' to stay on current line.
22972 (call-interactively 'end-of-line))
22973 (t (call-interactively move-fun)))))
22974 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22975 (setq disable-point-adjustment
22976 (or (not (invisible-p (point)))
22977 (not (invisible-p (max (point-min) (1- (point))))))))
22979 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22980 (define-key org-mode-map "\C-e" 'org-end-of-line)
22982 (defun org-backward-sentence (&optional arg)
22983 "Go to beginning of sentence, or beginning of table field.
22984 This will call `backward-sentence' or `org-table-beginning-of-field',
22985 depending on context."
22986 (interactive "P")
22987 (cond
22988 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22989 (t (call-interactively 'backward-sentence))))
22991 (defun org-forward-sentence (&optional arg)
22992 "Go to end of sentence, or end of table field.
22993 This will call `forward-sentence' or `org-table-end-of-field',
22994 depending on context."
22995 (interactive "P")
22996 (cond
22997 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22998 (t (call-interactively 'forward-sentence))))
23000 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23001 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23003 (defun org-kill-line (&optional arg)
23004 "Kill line, to tags or end of line."
23005 (interactive "P")
23006 (cond
23007 ((or (not org-special-ctrl-k)
23008 (bolp)
23009 (not (org-at-heading-p)))
23010 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23011 org-ctrl-k-protect-subtree)
23012 (if (or (eq org-ctrl-k-protect-subtree 'error)
23013 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
23014 (user-error "C-k aborted as it would kill a hidden subtree")))
23015 (call-interactively
23016 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23017 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
23018 (kill-region (point) (match-beginning 1))
23019 (org-set-tags nil t))
23020 (t (kill-region (point) (point-at-eol)))))
23022 (define-key org-mode-map "\C-k" 'org-kill-line)
23024 (defun org-yank (&optional arg)
23025 "Yank. If the kill is a subtree, treat it specially.
23026 This command will look at the current kill and check if is a single
23027 subtree, or a series of subtrees[1]. If it passes the test, and if the
23028 cursor is at the beginning of a line or after the stars of a currently
23029 empty headline, then the yank is handled specially. How exactly depends
23030 on the value of the following variables, both set by default.
23032 org-yank-folded-subtrees
23033 When set, the subtree(s) will be folded after insertion, but only
23034 if doing so would now swallow text after the yanked text.
23036 org-yank-adjusted-subtrees
23037 When set, the subtree will be promoted or demoted in order to
23038 fit into the local outline tree structure, which means that the level
23039 will be adjusted so that it becomes the smaller one of the two
23040 *visible* surrounding headings.
23042 Any prefix to this command will cause `yank' to be called directly with
23043 no special treatment. In particular, a simple \\[universal-argument] prefix \
23044 will just
23045 plainly yank the text as it is.
23047 \[1] The test checks if the first non-white line is a heading
23048 and if there are no other headings with fewer stars."
23049 (interactive "P")
23050 (org-yank-generic 'yank arg))
23052 (defun org-yank-generic (command arg)
23053 "Perform some yank-like command.
23055 This function implements the behavior described in the `org-yank'
23056 documentation. However, it has been generalized to work for any
23057 interactive command with similar behavior."
23059 ;; pretend to be command COMMAND
23060 (setq this-command command)
23062 (if arg
23063 (call-interactively command)
23065 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23066 (and (org-kill-is-subtree-p)
23067 (or (bolp)
23068 (and (looking-at "[ \t]*$")
23069 (string-match
23070 "\\`\\*+\\'"
23071 (buffer-substring (point-at-bol) (point)))))))
23072 swallowp)
23073 (cond
23074 ((and subtreep org-yank-folded-subtrees)
23075 (let ((beg (point))
23076 end)
23077 (if (and subtreep org-yank-adjusted-subtrees)
23078 (org-paste-subtree nil nil 'for-yank)
23079 (call-interactively command))
23081 (setq end (point))
23082 (goto-char beg)
23083 (when (and (bolp) subtreep
23084 (not (setq swallowp
23085 (org-yank-folding-would-swallow-text beg end))))
23086 (org-with-limited-levels
23087 (or (looking-at org-outline-regexp)
23088 (re-search-forward org-outline-regexp-bol end t))
23089 (while (and (< (point) end) (looking-at org-outline-regexp))
23090 (hide-subtree)
23091 (org-cycle-show-empty-lines 'folded)
23092 (condition-case nil
23093 (outline-forward-same-level 1)
23094 (error (goto-char end))))))
23095 (when swallowp
23096 (message
23097 "Inserted text not folded because that would swallow text"))
23099 (goto-char end)
23100 (skip-chars-forward " \t\n\r")
23101 (beginning-of-line 1)
23102 (push-mark beg 'nomsg)))
23103 ((and subtreep org-yank-adjusted-subtrees)
23104 (let ((beg (point-at-bol)))
23105 (org-paste-subtree nil nil 'for-yank)
23106 (push-mark beg 'nomsg)))
23108 (call-interactively command))))))
23110 (defun org-yank-folding-would-swallow-text (beg end)
23111 "Would hide-subtree at BEG swallow any text after END?"
23112 (let (level)
23113 (org-with-limited-levels
23114 (save-excursion
23115 (goto-char beg)
23116 (when (or (looking-at org-outline-regexp)
23117 (re-search-forward org-outline-regexp-bol end t))
23118 (setq level (org-outline-level)))
23119 (goto-char end)
23120 (skip-chars-forward " \t\r\n\v\f")
23121 (if (or (eobp)
23122 (and (bolp) (looking-at org-outline-regexp)
23123 (<= (org-outline-level) level)))
23124 nil ; Nothing would be swallowed
23125 t))))) ; something would swallow
23127 (define-key org-mode-map "\C-y" 'org-yank)
23129 (defun org-truely-invisible-p ()
23130 "Check if point is at a character currently not visible.
23131 This version does not only check the character property, but also
23132 `visible-mode'."
23133 ;; Early versions of noutline don't have `outline-invisible-p'.
23134 (if (org-bound-and-true-p visible-mode)
23136 (outline-invisible-p)))
23138 (defun org-invisible-p2 ()
23139 "Check if point is at a character currently not visible."
23140 (save-excursion
23141 (if (and (eolp) (not (bobp))) (backward-char 1))
23142 ;; Early versions of noutline don't have `outline-invisible-p'.
23143 (outline-invisible-p)))
23145 (defun org-back-to-heading (&optional invisible-ok)
23146 "Call `outline-back-to-heading', but provide a better error message."
23147 (condition-case nil
23148 (outline-back-to-heading invisible-ok)
23149 (error (error "Before first headline at position %d in buffer %s"
23150 (point) (current-buffer)))))
23152 (defun org-before-first-heading-p ()
23153 "Before first heading?"
23154 (save-excursion
23155 (end-of-line)
23156 (null (re-search-backward org-outline-regexp-bol nil t))))
23158 (defun org-at-heading-p (&optional ignored)
23159 (outline-on-heading-p t))
23160 ;; Compatibility alias with Org versions < 7.8.03
23161 (defalias 'org-on-heading-p 'org-at-heading-p)
23163 (defun org-at-comment-p nil
23164 "Is cursor in a line starting with a # character?"
23165 (save-excursion
23166 (beginning-of-line)
23167 (looking-at "^#")))
23169 (defun org-at-drawer-p nil
23170 "Is cursor at a drawer keyword?"
23171 (save-excursion
23172 (move-beginning-of-line 1)
23173 (looking-at org-drawer-regexp)))
23175 (defun org-at-block-p nil
23176 "Is cursor at a block keyword?"
23177 (save-excursion
23178 (move-beginning-of-line 1)
23179 (looking-at org-block-regexp)))
23181 (defun org-point-at-end-of-empty-headline ()
23182 "If point is at the end of an empty headline, return t, else nil.
23183 If the heading only contains a TODO keyword, it is still still considered
23184 empty."
23185 (and (looking-at "[ \t]*$")
23186 (when org-todo-line-regexp
23187 (save-excursion
23188 (beginning-of-line 1)
23189 (let ((case-fold-search nil))
23190 (looking-at org-todo-line-regexp)
23191 (string= (match-string 3) ""))))))
23193 (defun org-at-heading-or-item-p ()
23194 (or (org-at-heading-p) (org-at-item-p)))
23196 (defun org-at-target-p ()
23197 (or (org-in-regexp org-radio-target-regexp)
23198 (org-in-regexp org-target-regexp)))
23199 ;; Compatibility alias with Org versions < 7.8.03
23200 (defalias 'org-on-target-p 'org-at-target-p)
23202 (defun org-up-heading-all (arg)
23203 "Move to the heading line of which the present line is a subheading.
23204 This function considers both visible and invisible heading lines.
23205 With argument, move up ARG levels."
23206 (if (fboundp 'outline-up-heading-all)
23207 (outline-up-heading-all arg) ; emacs 21 version of outline.el
23208 (outline-up-heading arg t))) ; emacs 22 version of outline.el
23210 (defun org-up-heading-safe ()
23211 "Move to the heading line of which the present line is a subheading.
23212 This version will not throw an error. It will return the level of the
23213 headline found, or nil if no higher level is found.
23215 Also, this function will be a lot faster than `outline-up-heading',
23216 because it relies on stars being the outline starters. This can really
23217 make a significant difference in outlines with very many siblings."
23218 (let (start-level re)
23219 (org-back-to-heading t)
23220 (setq start-level (funcall outline-level))
23221 (if (equal start-level 1)
23223 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
23224 (if (re-search-backward re nil t)
23225 (funcall outline-level)))))
23227 (defun org-first-sibling-p ()
23228 "Is this heading the first child of its parents?"
23229 (interactive)
23230 (let ((re org-outline-regexp-bol)
23231 level l)
23232 (unless (org-at-heading-p t)
23233 (user-error "Not at a heading"))
23234 (setq level (funcall outline-level))
23235 (save-excursion
23236 (if (not (re-search-backward re nil t))
23238 (setq l (funcall outline-level))
23239 (< l level)))))
23241 (defun org-goto-sibling (&optional previous)
23242 "Goto the next sibling, even if it is invisible.
23243 When PREVIOUS is set, go to the previous sibling instead. Returns t
23244 when a sibling was found. When none is found, return nil and don't
23245 move point."
23246 (let ((fun (if previous 're-search-backward 're-search-forward))
23247 (pos (point))
23248 (re org-outline-regexp-bol)
23249 level l)
23250 (when (condition-case nil (org-back-to-heading t) (error nil))
23251 (setq level (funcall outline-level))
23252 (catch 'exit
23253 (or previous (forward-char 1))
23254 (while (funcall fun re nil t)
23255 (setq l (funcall outline-level))
23256 (when (< l level) (goto-char pos) (throw 'exit nil))
23257 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23258 (goto-char pos)
23259 nil))))
23261 (defun org-show-siblings ()
23262 "Show all siblings of the current headline."
23263 (save-excursion
23264 (while (org-goto-sibling) (org-flag-heading nil)))
23265 (save-excursion
23266 (while (org-goto-sibling 'previous)
23267 (org-flag-heading nil))))
23269 (defun org-goto-first-child ()
23270 "Goto the first child, even if it is invisible.
23271 Return t when a child was found. Otherwise don't move point and
23272 return nil."
23273 (let (level (pos (point)) (re org-outline-regexp-bol))
23274 (when (condition-case nil (org-back-to-heading t) (error nil))
23275 (setq level (outline-level))
23276 (forward-char 1)
23277 (if (and (re-search-forward re nil t) (> (outline-level) level))
23278 (progn (goto-char (match-beginning 0)) t)
23279 (goto-char pos) nil))))
23281 (defun org-show-hidden-entry ()
23282 "Show an entry where even the heading is hidden."
23283 (save-excursion
23284 (org-show-entry)))
23286 (defun org-flag-heading (flag &optional entry)
23287 "Flag the current heading. FLAG non-nil means make invisible.
23288 When ENTRY is non-nil, show the entire entry."
23289 (save-excursion
23290 (org-back-to-heading t)
23291 ;; Check if we should show the entire entry
23292 (if entry
23293 (progn
23294 (org-show-entry)
23295 (save-excursion
23296 (and (outline-next-heading)
23297 (org-flag-heading nil))))
23298 (outline-flag-region (max (point-min) (1- (point)))
23299 (save-excursion (outline-end-of-heading) (point))
23300 flag))))
23302 (defun org-get-next-sibling ()
23303 "Move to next heading of the same level, and return point.
23304 If there is no such heading, return nil.
23305 This is like outline-next-sibling, but invisible headings are ok."
23306 (let ((level (funcall outline-level)))
23307 (outline-next-heading)
23308 (while (and (not (eobp)) (> (funcall outline-level) level))
23309 (outline-next-heading))
23310 (if (or (eobp) (< (funcall outline-level) level))
23312 (point))))
23314 (defun org-get-last-sibling ()
23315 "Move to previous heading of the same level, and return point.
23316 If there is no such heading, return nil."
23317 (let ((opoint (point))
23318 (level (funcall outline-level)))
23319 (outline-previous-heading)
23320 (when (and (/= (point) opoint) (outline-on-heading-p t))
23321 (while (and (> (funcall outline-level) level)
23322 (not (bobp)))
23323 (outline-previous-heading))
23324 (if (< (funcall outline-level) level)
23326 (point)))))
23328 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23329 "Goto to the end of a subtree."
23330 ;; This contains an exact copy of the original function, but it uses
23331 ;; `org-back-to-heading', to make it work also in invisible
23332 ;; trees. And is uses an invisible-ok argument.
23333 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23334 ;; Furthermore, when used inside Org, finding the end of a large subtree
23335 ;; with many children and grandchildren etc, this can be much faster
23336 ;; than the outline version.
23337 (org-back-to-heading invisible-ok)
23338 (let ((first t)
23339 (level (funcall outline-level)))
23340 (if (and (derived-mode-p 'org-mode) (< level 1000))
23341 ;; A true heading (not a plain list item), in Org-mode
23342 ;; This means we can easily find the end by looking
23343 ;; only for the right number of stars. Using a regexp to do
23344 ;; this is so much faster than using a Lisp loop.
23345 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23346 (forward-char 1)
23347 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23348 ;; something else, do it the slow way
23349 (while (and (not (eobp))
23350 (or first (> (funcall outline-level) level)))
23351 (setq first nil)
23352 (outline-next-heading)))
23353 (unless to-heading
23354 (if (memq (preceding-char) '(?\n ?\^M))
23355 (progn
23356 ;; Go to end of line before heading
23357 (forward-char -1)
23358 (if (memq (preceding-char) '(?\n ?\^M))
23359 ;; leave blank line before heading
23360 (forward-char -1))))))
23361 (point))
23363 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
23364 "Use Org version in org-mode, for dramatic speed-up."
23365 (if (derived-mode-p 'org-mode)
23366 (progn
23367 (org-end-of-subtree nil t)
23368 (unless (eobp) (backward-char 1)))
23369 ad-do-it))
23371 (defun org-end-of-meta-data-and-drawers ()
23372 "Jump to the first text after meta data and drawers in the current entry.
23373 This will move over empty lines, lines with planning time stamps,
23374 clocking lines, and drawers."
23375 (org-back-to-heading t)
23376 (let ((end (save-excursion (outline-next-heading) (point)))
23377 (re (concat "\\(" org-drawer-regexp "\\)"
23378 "\\|" "[ \t]*" org-keyword-time-regexp)))
23379 (forward-line 1)
23380 (while (re-search-forward re end t)
23381 (if (not (match-end 1))
23382 ;; empty or planning line
23383 (forward-line 1)
23384 ;; a drawer, find the end
23385 (re-search-forward "^[ \t]*:END:" end 'move)
23386 (forward-line 1)))
23387 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23388 (point)))
23390 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23391 "Move forward to the ARG'th subheading at same level as this one.
23392 Stop at the first and last subheadings of a superior heading.
23393 Normally this only looks at visible headings, but when INVISIBLE-OK is
23394 non-nil it will also look at invisible ones."
23395 (interactive "p")
23396 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23397 (if (and arg (< arg 0))
23398 (goto-char (point-min))
23399 (outline-next-heading))
23400 (org-at-heading-p)
23401 (let ((level (- (match-end 0) (match-beginning 0) 1))
23402 (f (if (and arg (< arg 0))
23403 're-search-backward
23404 're-search-forward))
23405 (count (if arg (abs arg) 1))
23406 (result (point)))
23407 (while (and (prog1 (> count 0)
23408 (forward-char (if (and arg (< arg 0)) -1 1)))
23409 (funcall f org-outline-regexp-bol nil 'move))
23410 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23411 (cond ((< l level) (setq count 0))
23412 ((and (= l level)
23413 (or invisible-ok
23414 (progn
23415 (goto-char (line-beginning-position))
23416 (not (outline-invisible-p)))))
23417 (setq count (1- count))
23418 (when (eq l level)
23419 (setq result (point)))))))
23420 (goto-char result))
23421 (beginning-of-line 1)))
23423 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23424 "Move backward to the ARG'th subheading at same level as this one.
23425 Stop at the first and last subheadings of a superior heading."
23426 (interactive "p")
23427 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23429 (defun org-next-block (arg &optional backward block-regexp)
23430 "Jump to the next block.
23431 With a prefix argument ARG, jump forward ARG many source blocks.
23432 When BACKWARD is non-nil, jump to the previous block.
23433 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23434 (interactive "p")
23435 (let ((re (or block-regexp org-block-regexp))
23436 (re-search-fn (or (and backward 're-search-backward)
23437 're-search-forward)))
23438 (if (looking-at re) (forward-char 1))
23439 (condition-case nil
23440 (funcall re-search-fn re nil nil arg)
23441 (error (error "No %s code blocks" (if backward "previous" "further" ))))
23442 (goto-char (match-beginning 0)) (org-show-context)))
23444 (defun org-previous-block (arg &optional block-regexp)
23445 "Jump to the previous block.
23446 With a prefix argument ARG, jump backward ARG many source blocks.
23447 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23448 (interactive "p")
23449 (org-next-block arg t block-regexp))
23451 (defun org-forward-paragraph ()
23452 "Move forward to beginning of next paragraph or equivalent.
23454 The function moves point to the beginning of the next visible
23455 structural element, which can be a paragraph, a table, a list
23456 item, etc. It also provides some special moves for convenience:
23458 - On an affiliated keyword, jump to the beginning of the
23459 relative element.
23460 - On an item or a footnote definition, move to the second
23461 element inside, if any.
23462 - On a table or a property drawer, jump after it.
23463 - On a verse or source block, stop after blank lines."
23464 (interactive)
23465 (when (eobp) (user-error "Cannot move further down"))
23466 (let* ((deactivate-mark nil)
23467 (element (org-element-at-point))
23468 (type (org-element-type element))
23469 (post-affiliated (org-element-property :post-affiliated element))
23470 (contents-begin (org-element-property :contents-begin element))
23471 (contents-end (org-element-property :contents-end element))
23472 (end (let ((end (org-element-property :end element)) (parent element))
23473 (while (and (setq parent (org-element-property :parent parent))
23474 (= (org-element-property :contents-end parent) end))
23475 (setq end (org-element-property :end parent)))
23476 end)))
23477 (cond ((not element)
23478 (skip-chars-forward " \r\t\n")
23479 (or (eobp) (beginning-of-line)))
23480 ;; On affiliated keywords, move to element's beginning.
23481 ((and post-affiliated (< (point) post-affiliated))
23482 (goto-char post-affiliated))
23483 ;; At a table row, move to the end of the table. Similarly,
23484 ;; at a node property, move to the end of the property
23485 ;; drawer.
23486 ((memq type '(node-property table-row))
23487 (goto-char (org-element-property
23488 :end (org-element-property :parent element))))
23489 ((memq type '(property-drawer table)) (goto-char end))
23490 ;; Consider blank lines as separators in verse and source
23491 ;; blocks to ease editing.
23492 ((memq type '(src-block verse-block))
23493 (when (eq type 'src-block)
23494 (setq contents-end
23495 (save-excursion (goto-char end)
23496 (skip-chars-backward " \r\t\n")
23497 (line-beginning-position))))
23498 (beginning-of-line)
23499 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23500 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23501 (goto-char end)
23502 (skip-chars-forward " \r\t\n")
23503 (if (= (point) contents-end) (goto-char end)
23504 (beginning-of-line))))
23505 ;; With no contents, just skip element.
23506 ((not contents-begin) (goto-char end))
23507 ;; If contents are invisible, skip the element altogether.
23508 ((outline-invisible-p (line-end-position))
23509 (case type
23510 (headline
23511 (org-with-limited-levels (outline-next-visible-heading 1)))
23512 ;; At a plain list, make sure we move to the next item
23513 ;; instead of skipping the whole list.
23514 (plain-list (forward-char)
23515 (org-forward-paragraph))
23516 (otherwise (goto-char end))))
23517 ((>= (point) contents-end) (goto-char end))
23518 ((>= (point) contents-begin)
23519 ;; This can only happen on paragraphs and plain lists.
23520 (case type
23521 (paragraph (goto-char end))
23522 ;; At a plain list, try to move to second element in
23523 ;; first item, if possible.
23524 (plain-list (end-of-line)
23525 (org-forward-paragraph))))
23526 ;; When contents start on the middle of a line (e.g. in
23527 ;; items and footnote definitions), try to reach first
23528 ;; element starting after current line.
23529 ((> (line-end-position) contents-begin)
23530 (end-of-line)
23531 (org-forward-paragraph))
23532 (t (goto-char contents-begin)))))
23534 (defun org-backward-paragraph ()
23535 "Move backward to start of previous paragraph or equivalent.
23537 The function moves point to the beginning of the current
23538 structural element, which can be a paragraph, a table, a list
23539 item, etc., or to the beginning of the previous visible one if
23540 point is already there. It also provides some special moves for
23541 convenience:
23543 - On an affiliated keyword, jump to the first one.
23544 - On a table or a property drawer, move to its beginning.
23545 - On a verse or source block, stop before blank lines."
23546 (interactive)
23547 (when (bobp) (user-error "Cannot move further up"))
23548 (let* ((deactivate-mark nil)
23549 (element (org-element-at-point))
23550 (type (org-element-type element))
23551 (contents-begin (org-element-property :contents-begin element))
23552 (contents-end (org-element-property :contents-end element))
23553 (post-affiliated (org-element-property :post-affiliated element))
23554 (begin (org-element-property :begin element)))
23555 (cond
23556 ((not element) (goto-char (point-min)))
23557 ((= (point) begin)
23558 (backward-char)
23559 (org-backward-paragraph))
23560 ((and post-affiliated (<= (point) post-affiliated)) (goto-char begin))
23561 ((memq type '(node-property table-row))
23562 (goto-char (org-element-property
23563 :post-affiliated (org-element-property :parent element))))
23564 ((memq type '(property-drawer table)) (goto-char begin))
23565 ((memq type '(src-block verse-block))
23566 (when (eq type 'src-block)
23567 (setq contents-begin
23568 (save-excursion (goto-char begin) (forward-line) (point))))
23569 (if (= (point) contents-begin) (goto-char post-affiliated)
23570 ;; Inside a verse block, see blank lines as paragraph
23571 ;; separators.
23572 (let ((origin (point)))
23573 (skip-chars-backward " \r\t\n" contents-begin)
23574 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
23575 (skip-chars-forward " \r\t\n" origin)
23576 (if (= (point) origin) (goto-char contents-begin)
23577 (beginning-of-line))))))
23578 ((not contents-begin) (goto-char (or post-affiliated begin)))
23579 ((eq type 'paragraph)
23580 (goto-char contents-begin)
23581 ;; When at first paragraph in an item or a footnote definition,
23582 ;; move directly to beginning of line.
23583 (let ((parent-contents
23584 (org-element-property
23585 :contents-begin (org-element-property :parent element))))
23586 (when (and parent-contents (= parent-contents contents-begin))
23587 (beginning-of-line))))
23588 ;; At the end of a greater element, move to the beginning of the
23589 ;; last element within.
23590 ((>= (point) contents-end)
23591 (goto-char (1- contents-end))
23592 (org-backward-paragraph))
23593 (t (goto-char (or post-affiliated begin))))
23594 ;; Ensure we never leave point invisible.
23595 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
23597 (defun org-forward-element ()
23598 "Move forward by one element.
23599 Move to the next element at the same level, when possible."
23600 (interactive)
23601 (cond ((eobp) (user-error "Cannot move further down"))
23602 ((org-with-limited-levels (org-at-heading-p))
23603 (let ((origin (point)))
23604 (goto-char (org-end-of-subtree nil t))
23605 (unless (org-with-limited-levels (org-at-heading-p))
23606 (goto-char origin)
23607 (user-error "Cannot move further down"))))
23609 (let* ((elem (org-element-at-point))
23610 (end (org-element-property :end elem))
23611 (parent (org-element-property :parent elem)))
23612 (cond ((and parent (= (org-element-property :contents-end parent) end))
23613 (goto-char (org-element-property :end parent)))
23614 ((integer-or-marker-p end) (goto-char end))
23615 (t (message "No element at point")))))))
23617 (defun org-backward-element ()
23618 "Move backward by one element.
23619 Move to the previous element at the same level, when possible."
23620 (interactive)
23621 (cond ((bobp) (user-error "Cannot move further up"))
23622 ((org-with-limited-levels (org-at-heading-p))
23623 ;; At a headline, move to the previous one, if any, or stay
23624 ;; here.
23625 (let ((origin (point)))
23626 (org-with-limited-levels (org-backward-heading-same-level 1))
23627 ;; When current headline has no sibling above, move to its
23628 ;; parent.
23629 (when (= (point) origin)
23630 (or (org-with-limited-levels (org-up-heading-safe))
23631 (progn (goto-char origin)
23632 (user-error "Cannot move further up"))))))
23634 (let* ((elem (org-element-at-point))
23635 (beg (org-element-property :begin elem)))
23636 (cond
23637 ;; Move to beginning of current element if point isn't
23638 ;; there already.
23639 ((null beg) (message "No element at point"))
23640 ((/= (point) beg) (goto-char beg))
23641 (t (goto-char beg)
23642 (skip-chars-backward " \r\t\n")
23643 (unless (bobp)
23644 (let ((prev (org-element-at-point)))
23645 (goto-char (org-element-property :begin prev))
23646 (while (and (setq prev (org-element-property :parent prev))
23647 (<= (org-element-property :end prev) beg))
23648 (goto-char (org-element-property :begin prev)))))))))))
23650 (defun org-up-element ()
23651 "Move to upper element."
23652 (interactive)
23653 (if (org-with-limited-levels (org-at-heading-p))
23654 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23655 (let* ((elem (org-element-at-point))
23656 (parent (org-element-property :parent elem)))
23657 (if parent (goto-char (org-element-property :begin parent))
23658 (if (org-with-limited-levels (org-before-first-heading-p))
23659 (user-error "No surrounding element")
23660 (org-with-limited-levels (org-back-to-heading)))))))
23662 (defvar org-element-greater-elements)
23663 (defun org-down-element ()
23664 "Move to inner element."
23665 (interactive)
23666 (let ((element (org-element-at-point)))
23667 (cond
23668 ((memq (org-element-type element) '(plain-list table))
23669 (goto-char (org-element-property :contents-begin element))
23670 (forward-char))
23671 ((memq (org-element-type element) org-element-greater-elements)
23672 ;; If contents are hidden, first disclose them.
23673 (when (outline-invisible-p (line-end-position)) (org-cycle))
23674 (goto-char (or (org-element-property :contents-begin element)
23675 (user-error "No content for this element"))))
23676 (t (user-error "No inner element")))))
23678 (defun org-drag-element-backward ()
23679 "Move backward element at point."
23680 (interactive)
23681 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
23682 (let* ((elem (org-element-at-point))
23683 (prev-elem
23684 (save-excursion
23685 (goto-char (org-element-property :begin elem))
23686 (skip-chars-backward " \r\t\n")
23687 (unless (bobp)
23688 (let* ((beg (org-element-property :begin elem))
23689 (prev (org-element-at-point))
23690 (up prev))
23691 (while (and (setq up (org-element-property :parent up))
23692 (<= (org-element-property :end prev) beg))
23693 (setq prev up))
23694 prev)))))
23695 ;; Error out if no previous element or previous element is
23696 ;; a parent of the current one.
23697 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23698 (user-error "Cannot drag element backward")
23699 (let ((pos (point)))
23700 (org-element-swap-A-B prev-elem elem)
23701 (goto-char (+ (org-element-property :begin prev-elem)
23702 (- pos (org-element-property :begin elem)))))))))
23704 (defun org-drag-element-forward ()
23705 "Move forward element at point."
23706 (interactive)
23707 (let* ((pos (point))
23708 (elem (org-element-at-point)))
23709 (when (= (point-max) (org-element-property :end elem))
23710 (user-error "Cannot drag element forward"))
23711 (goto-char (org-element-property :end elem))
23712 (let ((next-elem (org-element-at-point)))
23713 (when (or (org-element-nested-p elem next-elem)
23714 (and (eq (org-element-type next-elem) 'headline)
23715 (not (eq (org-element-type elem) 'headline))))
23716 (goto-char pos)
23717 (user-error "Cannot drag element forward"))
23718 ;; Compute new position of point: it's shifted by NEXT-ELEM
23719 ;; body's length (without final blanks) and by the length of
23720 ;; blanks between ELEM and NEXT-ELEM.
23721 (let ((size-next (- (save-excursion
23722 (goto-char (org-element-property :end next-elem))
23723 (skip-chars-backward " \r\t\n")
23724 (forward-line)
23725 ;; Small correction if buffer doesn't end
23726 ;; with a newline character.
23727 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23728 (org-element-property :begin next-elem)))
23729 (size-blank (- (org-element-property :end elem)
23730 (save-excursion
23731 (goto-char (org-element-property :end elem))
23732 (skip-chars-backward " \r\t\n")
23733 (forward-line)
23734 (point)))))
23735 (org-element-swap-A-B elem next-elem)
23736 (goto-char (+ pos size-next size-blank))))))
23738 (defun org-drag-line-forward (arg)
23739 "Drag the line at point ARG lines forward."
23740 (interactive "p")
23741 (dotimes (n (abs arg))
23742 (let ((c (current-column)))
23743 (if (< 0 arg)
23744 (progn
23745 (beginning-of-line 2)
23746 (transpose-lines 1)
23747 (beginning-of-line 0))
23748 (transpose-lines 1)
23749 (beginning-of-line -1))
23750 (org-move-to-column c))))
23752 (defun org-drag-line-backward (arg)
23753 "Drag the line at point ARG lines backward."
23754 (interactive "p")
23755 (org-drag-line-forward (- arg)))
23757 (defun org-mark-element ()
23758 "Put point at beginning of this element, mark at end.
23760 Interactively, if this command is repeated or (in Transient Mark
23761 mode) if the mark is active, it marks the next element after the
23762 ones already marked."
23763 (interactive)
23764 (let (deactivate-mark)
23765 (if (and (org-called-interactively-p 'any)
23766 (or (and (eq last-command this-command) (mark t))
23767 (and transient-mark-mode mark-active)))
23768 (set-mark
23769 (save-excursion
23770 (goto-char (mark))
23771 (goto-char (org-element-property :end (org-element-at-point)))))
23772 (let ((element (org-element-at-point)))
23773 (end-of-line)
23774 (push-mark (org-element-property :end element) t t)
23775 (goto-char (org-element-property :begin element))))))
23777 (defun org-narrow-to-element ()
23778 "Narrow buffer to current element."
23779 (interactive)
23780 (let ((elem (org-element-at-point)))
23781 (cond
23782 ((eq (car elem) 'headline)
23783 (narrow-to-region
23784 (org-element-property :begin elem)
23785 (org-element-property :end elem)))
23786 ((memq (car elem) org-element-greater-elements)
23787 (narrow-to-region
23788 (org-element-property :contents-begin elem)
23789 (org-element-property :contents-end elem)))
23791 (narrow-to-region
23792 (org-element-property :begin elem)
23793 (org-element-property :end elem))))))
23795 (defun org-transpose-element ()
23796 "Transpose current and previous elements, keeping blank lines between.
23797 Point is moved after both elements."
23798 (interactive)
23799 (org-skip-whitespace)
23800 (let ((end (org-element-property :end (org-element-at-point))))
23801 (org-drag-element-backward)
23802 (goto-char end)))
23804 (defun org-unindent-buffer ()
23805 "Un-indent the visible part of the buffer.
23806 Relative indentation (between items, inside blocks, etc.) isn't
23807 modified."
23808 (interactive)
23809 (unless (eq major-mode 'org-mode)
23810 (user-error "Cannot un-indent a buffer not in Org mode"))
23811 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23812 unindent-tree ; For byte-compiler.
23813 (unindent-tree
23814 (function
23815 (lambda (contents)
23816 (mapc
23817 (lambda (element)
23818 (if (memq (org-element-type element) '(headline section))
23819 (funcall unindent-tree (org-element-contents element))
23820 (save-excursion
23821 (save-restriction
23822 (narrow-to-region
23823 (org-element-property :begin element)
23824 (org-element-property :end element))
23825 (org-do-remove-indentation)))))
23826 (reverse contents))))))
23827 (funcall unindent-tree (org-element-contents parse-tree))))
23829 (defun org-show-subtree ()
23830 "Show everything after this heading at deeper levels."
23831 (interactive)
23832 (outline-flag-region
23833 (point)
23834 (save-excursion
23835 (org-end-of-subtree t t))
23836 nil))
23838 (defun org-show-entry ()
23839 "Show the body directly following this heading.
23840 Show the heading too, if it is currently invisible."
23841 (interactive)
23842 (save-excursion
23843 (condition-case nil
23844 (progn
23845 (org-back-to-heading t)
23846 (outline-flag-region
23847 (max (point-min) (1- (point)))
23848 (save-excursion
23849 (if (re-search-forward
23850 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23851 (match-beginning 1)
23852 (point-max)))
23853 nil)
23854 (org-cycle-hide-drawers 'children))
23855 (error nil))))
23857 (defun org-make-options-regexp (kwds &optional extra)
23858 "Make a regular expression for keyword lines."
23859 (concat
23860 "^#\\+\\("
23861 (mapconcat 'regexp-quote kwds "\\|")
23862 (if extra (concat "\\|" extra))
23863 "\\):[ \t]*\\(.*\\)"))
23865 ;; Make isearch reveal the necessary context
23866 (defun org-isearch-end ()
23867 "Reveal context after isearch exits."
23868 (when isearch-success ; only if search was successful
23869 (if (featurep 'xemacs)
23870 ;; Under XEmacs, the hook is run in the correct place,
23871 ;; we directly show the context.
23872 (org-show-context 'isearch)
23873 ;; In Emacs the hook runs *before* restoring the overlays.
23874 ;; So we have to use a one-time post-command-hook to do this.
23875 ;; (Emacs 22 has a special variable, see function `org-mode')
23876 (unless (and (boundp 'isearch-mode-end-hook-quit)
23877 isearch-mode-end-hook-quit)
23878 ;; Only when the isearch was not quitted.
23879 (org-add-hook 'post-command-hook 'org-isearch-post-command
23880 'append 'local)))
23881 (org-fix-ellipsis-at-bol)))
23883 (defun org-isearch-post-command ()
23884 "Remove self from hook, and show context."
23885 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23886 (org-show-context 'isearch))
23889 ;;;; Integration with and fixes for other packages
23891 ;;; Imenu support
23893 (defvar org-imenu-markers nil
23894 "All markers currently used by Imenu.")
23895 (make-variable-buffer-local 'org-imenu-markers)
23897 (defun org-imenu-new-marker (&optional pos)
23898 "Return a new marker for use by Imenu, and remember the marker."
23899 (let ((m (make-marker)))
23900 (move-marker m (or pos (point)))
23901 (push m org-imenu-markers)
23904 (defun org-imenu-get-tree ()
23905 "Produce the index for Imenu."
23906 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23907 (setq org-imenu-markers nil)
23908 (let* ((n org-imenu-depth)
23909 (re (concat "^" (org-get-limited-outline-regexp)))
23910 (subs (make-vector (1+ n) nil))
23911 (last-level 0)
23912 m level head0 head)
23913 (save-excursion
23914 (save-restriction
23915 (widen)
23916 (goto-char (point-max))
23917 (while (re-search-backward re nil t)
23918 (setq level (org-reduced-level (funcall outline-level)))
23919 (when (and (<= level n)
23920 (looking-at org-complex-heading-regexp)
23921 (setq head0 (org-match-string-no-properties 4)))
23922 (setq head (org-link-display-format head0)
23923 m (org-imenu-new-marker))
23924 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23925 (if (>= level last-level)
23926 (push (cons head m) (aref subs level))
23927 (push (cons head (aref subs (1+ level))) (aref subs level))
23928 (loop for i from (1+ level) to n do (aset subs i nil)))
23929 (setq last-level level)))))
23930 (aref subs 1)))
23932 (eval-after-load "imenu"
23933 '(progn
23934 (add-hook 'imenu-after-jump-hook
23935 (lambda ()
23936 (if (derived-mode-p 'org-mode)
23937 (org-show-context 'org-goto))))))
23939 (defun org-link-display-format (link)
23940 "Replace a link with its the description.
23941 If there is no description, use the link target."
23942 (save-match-data
23943 (if (string-match org-bracket-link-analytic-regexp link)
23944 (replace-match (if (match-end 5)
23945 (match-string 5 link)
23946 (concat (match-string 1 link)
23947 (match-string 3 link)))
23948 nil t link)
23949 link)))
23951 (defun org-toggle-link-display ()
23952 "Toggle the literal or descriptive display of links."
23953 (interactive)
23954 (if org-descriptive-links
23955 (progn (org-remove-from-invisibility-spec '(org-link))
23956 (org-restart-font-lock)
23957 (setq org-descriptive-links nil))
23958 (progn (add-to-invisibility-spec '(org-link))
23959 (org-restart-font-lock)
23960 (setq org-descriptive-links t))))
23962 ;; Speedbar support
23964 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23965 "Overlay marking the agenda restriction line in speedbar.")
23966 (overlay-put org-speedbar-restriction-lock-overlay
23967 'face 'org-agenda-restriction-lock)
23968 (overlay-put org-speedbar-restriction-lock-overlay
23969 'help-echo "Agendas are currently limited to this item.")
23970 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23972 (defun org-speedbar-set-agenda-restriction ()
23973 "Restrict future agenda commands to the location at point in speedbar.
23974 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23975 (interactive)
23976 (require 'org-agenda)
23977 (let (p m tp np dir txt)
23978 (cond
23979 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23980 'org-imenu t))
23981 (setq m (get-text-property p 'org-imenu-marker))
23982 (with-current-buffer (marker-buffer m)
23983 (goto-char m)
23984 (org-agenda-set-restriction-lock 'subtree)))
23985 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23986 'speedbar-function 'speedbar-find-file))
23987 (setq tp (previous-single-property-change
23988 (1+ p) 'speedbar-function)
23989 np (next-single-property-change
23990 tp 'speedbar-function)
23991 dir (speedbar-line-directory)
23992 txt (buffer-substring-no-properties (or tp (point-min))
23993 (or np (point-max))))
23994 (with-current-buffer (find-file-noselect
23995 (let ((default-directory dir))
23996 (expand-file-name txt)))
23997 (unless (derived-mode-p 'org-mode)
23998 (user-error "Cannot restrict to non-Org-mode file"))
23999 (org-agenda-set-restriction-lock 'file)))
24000 (t (user-error "Don't know how to restrict Org-mode's agenda")))
24001 (move-overlay org-speedbar-restriction-lock-overlay
24002 (point-at-bol) (point-at-eol))
24003 (setq current-prefix-arg nil)
24004 (org-agenda-maybe-redo)))
24006 (defvar speedbar-file-key-map)
24007 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24008 (eval-after-load "speedbar"
24009 '(progn
24010 (speedbar-add-supported-extension ".org")
24011 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24012 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24013 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24014 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24015 (add-hook 'speedbar-visiting-tag-hook
24016 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24018 ;;; Fixes and Hacks for problems with other packages
24020 (defun org-mode-flyspell-verify ()
24021 "Function used for `flyspell-generic-check-word-predicate'."
24022 (if (org-at-heading-p)
24023 ;; At a headline or an inlinetask, check title only. This is
24024 ;; faster than relying on `org-element-at-point'.
24025 (and (save-excursion (beginning-of-line)
24026 (and (let ((case-fold-search t))
24027 (not (looking-at "\\*+ END[ \t]*$")))
24028 (looking-at org-complex-heading-regexp)))
24029 (match-beginning 4)
24030 (>= (point) (match-beginning 4))
24031 (or (not (match-beginning 5))
24032 (< (point) (match-beginning 5))))
24033 (let* ((element (org-element-at-point))
24034 (post-affiliated (org-element-property :post-affiliated element))
24035 (object-check
24036 (function
24037 ;; Non-nil if checks can be done for object at point.
24038 (lambda ()
24039 (let ((object (save-excursion
24040 (when (org-looking-at-p "\\>") (backward-char))
24041 (org-element-context element))))
24042 (case (org-element-type object)
24043 ;; Prevent checks in links due to keybinding conflict
24044 ;; with Flyspell.
24045 ((code entity export-snippet inline-babel-call
24046 inline-src-block line-break latex-fragment link macro
24047 statistics-cookie target timestamp verbatim)
24048 nil)
24049 (footnote-reference
24050 ;; Only in inline footnotes, within the definition.
24051 (and (eq (org-element-property :type object) 'inline)
24052 (< (save-excursion
24053 (goto-char (org-element-property :begin object))
24054 (search-forward ":" nil t 2))
24055 (point))))
24056 (otherwise t)))))))
24057 (cond
24058 ;; Ignore checks in all affiliated keywords but captions.
24059 ((and post-affiliated (< (point) post-affiliated))
24060 (and (save-excursion
24061 (beginning-of-line)
24062 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
24063 (> (point) (match-end 0))
24064 (funcall object-check)))
24065 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
24066 ((and org-log-into-drawer
24067 (let ((log (or (org-string-nw-p org-log-into-drawer) "LOGBOOK"))
24068 (parent element))
24069 (while (and parent (not (eq (org-element-type parent) 'drawer)))
24070 (setq parent (org-element-property :parent parent)))
24071 (and parent
24072 (eq (compare-strings
24073 log nil nil
24074 (org-element-property :drawer-name parent) nil nil t)
24075 t))))
24076 nil)
24078 (case (org-element-type element)
24079 ((comment quote-section) t)
24080 (comment-block
24081 ;; Allow checks between block markers, not on them.
24082 (and (> (line-beginning-position)
24083 (org-element-property :post-affiliated element))
24084 (save-excursion
24085 (end-of-line)
24086 (skip-chars-forward " \r\t\n")
24087 (< (point) (org-element-property :end element)))))
24088 ;; Arbitrary list of keywords where checks are meaningful.
24089 ;; Make sure point is on the value part of the element.
24090 (keyword
24091 (and (member (org-element-property :key element)
24092 '("DESCRIPTION" "TITLE"))
24093 (< (save-excursion
24094 (beginning-of-line) (search-forward ":") (point))
24095 (point))))
24096 ;; Check is globally allowed in paragraphs verse blocks and
24097 ;; table rows (after affiliated keywords) but some objects
24098 ;; must not be affected.
24099 ((paragraph table-row verse-block)
24100 (and (>= (point) (org-element-property :contents-begin element))
24101 (< (point) (org-element-property :contents-end element))
24102 (funcall object-check)))))))))
24103 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
24105 (defun org-remove-flyspell-overlays-in (beg end)
24106 "Remove flyspell overlays in region."
24107 (and (org-bound-and-true-p flyspell-mode)
24108 (fboundp 'flyspell-delete-region-overlays)
24109 (flyspell-delete-region-overlays beg end)))
24111 (eval-after-load "flyspell"
24112 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
24114 ;; Make `bookmark-jump' shows the jump location if it was hidden.
24115 (eval-after-load "bookmark"
24116 '(if (boundp 'bookmark-after-jump-hook)
24117 ;; We can use the hook
24118 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
24119 ;; Hook not available, use advice
24120 (defadvice bookmark-jump (after org-make-visible activate)
24121 "Make the position visible."
24122 (org-bookmark-jump-unhide))))
24124 ;; Make sure saveplace shows the location if it was hidden
24125 (eval-after-load "saveplace"
24126 '(defadvice save-place-find-file-hook (after org-make-visible activate)
24127 "Make the position visible."
24128 (org-bookmark-jump-unhide)))
24130 ;; Make sure ecb shows the location if it was hidden
24131 (eval-after-load "ecb"
24132 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
24133 "Make hierarchy visible when jumping into location from ECB tree buffer."
24134 (if (derived-mode-p 'org-mode)
24135 (org-show-context))))
24137 (defun org-bookmark-jump-unhide ()
24138 "Unhide the current position, to show the bookmark location."
24139 (and (derived-mode-p 'org-mode)
24140 (or (outline-invisible-p)
24141 (save-excursion (goto-char (max (point-min) (1- (point))))
24142 (outline-invisible-p)))
24143 (org-show-context 'bookmark-jump)))
24145 ;; Make session.el ignore our circular variable
24146 (defvar session-globals-exclude)
24147 (eval-after-load "session"
24148 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24150 ;;;; Finish up
24152 (provide 'org)
24154 (run-hooks 'org-load-hook)
24156 ;;; org.el ends here