Radio targets cannot beging or end with whitespace
[org-mode.git] / lisp / org.el
blob9283d364420991d62eaf614166a57d55cdc65712
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2014 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
29 ;; project planning with a fast and effective plain-text system.
31 ;; Org-mode develops organizational tasks around NOTES files that contain
32 ;; information about projects as plain text. Org-mode is implemented on
33 ;; top of outline-mode, which makes it possible to keep the content of
34 ;; large files well structured. Visibility cycling and structure editing
35 ;; help to work with the tree. Tables are easily created with a built-in
36 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
37 ;; and scheduling. It dynamically compiles entries into an agenda that
38 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
39 ;; Plain text URL-like links connect to websites, emails, Usenet
40 ;; messages, BBDB entries, and any files related to the projects. For
41 ;; printing and sharing of notes, an Org-mode file can be exported as a
42 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
43 ;; iCalendar file. It can also serve as a publishing tool for a set of
44 ;; linked webpages.
46 ;; Installation and Activation
47 ;; ---------------------------
48 ;; See the corresponding sections in the manual at
50 ;; http://orgmode.org/org.html#Installation
52 ;; Documentation
53 ;; -------------
54 ;; The documentation of Org-mode can be found in the TeXInfo file. The
55 ;; distribution also contains a PDF version of it. At the homepage of
56 ;; Org-mode, you can read the same text online as HTML. There is also an
57 ;; excellent reference card made by Philip Rooke. This card can be found
58 ;; in the etc/ directory of Emacs 22.
60 ;; A list of recent changes can be found at
61 ;; http://orgmode.org/Changes.html
63 ;;; Code:
65 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
66 (defvar org-table-formula-constants-local nil
67 "Local version of `org-table-formula-constants'.")
68 (make-variable-buffer-local 'org-table-formula-constants-local)
70 ;;;; Require other packages
72 (eval-when-compile
73 (require 'cl)
74 (require 'gnus-sum))
76 (require 'calendar)
77 (require 'find-func)
78 (require 'format-spec)
80 (load "org-loaddefs.el" t t t)
82 (require 'org-macs)
83 (require 'org-compat)
85 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
86 ;; some places -- e.g. see the macro `org-with-limited-levels'.
88 ;; In Org buffers, the value of `outline-regexp' is that of
89 ;; `org-outline-regexp'. The only function still directly relying on
90 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
91 ;; job when `orgstruct-mode' is active.
92 (defvar org-outline-regexp "\\*+ "
93 "Regexp to match Org headlines.")
95 (defvar org-outline-regexp-bol "^\\*+ "
96 "Regexp to match Org headlines.
97 This is similar to `org-outline-regexp' but additionally makes
98 sure that we are at the beginning of the line.")
100 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
101 "Matches a headline, putting stars and text into groups.
102 Stars are put in group 1 and the trimmed body in group 2.")
104 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
105 (unless (boundp 'calendar-view-holidays-initially-flag)
106 (org-defvaralias 'calendar-view-holidays-initially-flag
107 'view-calendar-holidays-initially))
108 (unless (boundp 'calendar-view-diary-initially-flag)
109 (org-defvaralias 'calendar-view-diary-initially-flag
110 'view-diary-entries-initially))
111 (unless (boundp 'diary-fancy-buffer)
112 (org-defvaralias 'diary-fancy-buffer 'fancy-diary-buffer))
114 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
115 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
116 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
117 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
118 (declare-function org-clocktable-shift "org-clock" (dir n))
119 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
120 (declare-function org-clock-update-time-maybe "org-clock" ())
121 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
122 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
123 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
124 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
126 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
127 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body))
128 (declare-function orgtbl-mode "org-table" (&optional arg))
129 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
130 (declare-function org-beamer-mode "ox-beamer" ())
131 (declare-function org-table-blank-field "org-table" ())
132 (declare-function org-table-edit-field "org-table" (arg))
133 (declare-function org-table-insert-row "org-table" (&optional arg))
134 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
135 (declare-function org-table-set-constants "org-table" ())
136 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
137 (declare-function org-id-get-create "org-id" (&optional force))
138 (declare-function org-add-archive-files "org-archive" (files))
139 (declare-function org-id-find-id-file "org-id" (id))
140 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
141 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
142 (declare-function org-agenda-redo "org-agenda" (&optional all))
143 (declare-function org-table-align "org-table" ())
144 (declare-function org-table-begin "org-table" (&optional table-type))
145 (declare-function org-table-end "org-table" (&optional table-type))
146 (declare-function org-table-paste-rectangle "org-table" ())
147 (declare-function org-table-maybe-eval-formula "org-table" ())
148 (declare-function org-table-maybe-recalculate-line "org-table" ())
150 (declare-function org-element--parse-objects "org-element"
151 (beg end acc restriction))
152 (declare-function org-element-at-point "org-element" ())
153 (declare-function org-element-cache-reset "org-element" (&optional all))
154 (declare-function org-element-contents "org-element" (element))
155 (declare-function org-element-context "org-element" (&optional element))
156 (declare-function org-element-interpret-data "org-element"
157 (data &optional parent))
158 (declare-function org-element-map "org-element"
159 (data types fun &optional info first-match no-recursion))
160 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
161 (declare-function org-element-parse-buffer "org-element"
162 (&optional granularity visible-only))
163 (declare-function org-element-property "org-element" (property element))
164 (declare-function org-element-put-property "org-element"
165 (element property value))
166 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
167 (declare-function org-element--parse-objects "org-element"
168 (beg end acc restriction))
169 (declare-function org-element-parse-buffer "org-element"
170 (&optional granularity visible-only))
171 (declare-function org-element-restriction "org-element" (element))
172 (declare-function org-element-type "org-element" (element))
174 (defsubst org-uniquify (list)
175 "Non-destructively remove duplicate elements from LIST."
176 (let ((res (copy-sequence list))) (delete-dups res)))
178 ;; load languages based on value of `org-babel-load-languages'
179 (defvar org-babel-load-languages)
181 ;;;###autoload
182 (defun org-babel-do-load-languages (sym value)
183 "Load the languages defined in `org-babel-load-languages'."
184 (set-default sym value)
185 (mapc (lambda (pair)
186 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
187 (if active
188 (progn
189 (require (intern (concat "ob-" lang))))
190 (progn
191 (funcall 'fmakunbound
192 (intern (concat "org-babel-execute:" lang)))
193 (funcall 'fmakunbound
194 (intern (concat "org-babel-expand-body:" lang)))))))
195 org-babel-load-languages))
197 ;;;###autoload
198 (defun org-babel-load-file (file &optional compile)
199 "Load Emacs Lisp source code blocks in the Org-mode FILE.
200 This function exports the source code using `org-babel-tangle'
201 and then loads the resulting file using `load-file'. With prefix
202 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
203 file to byte-code before it is loaded."
204 (interactive "fFile to load: \nP")
205 (let* ((age (lambda (file)
206 (float-time
207 (time-subtract (current-time)
208 (nth 5 (or (file-attributes (file-truename file))
209 (file-attributes file)))))))
210 (base-name (file-name-sans-extension file))
211 (exported-file (concat base-name ".el")))
212 ;; tangle if the org-mode file is newer than the elisp file
213 (unless (and (file-exists-p exported-file)
214 (> (funcall age file) (funcall age exported-file)))
215 (setq exported-file
216 (car (org-babel-tangle-file file exported-file "emacs-lisp"))))
217 (message "%s %s"
218 (if compile
219 (progn (byte-compile-file exported-file 'load)
220 "Compiled and loaded")
221 (progn (load-file exported-file) "Loaded"))
222 exported-file)))
224 (defcustom org-babel-load-languages '((emacs-lisp . t))
225 "Languages which can be evaluated in Org-mode buffers.
226 This list can be used to load support for any of the languages
227 below, note that each language will depend on a different set of
228 system executables and/or Emacs modes. When a language is
229 \"loaded\", then code blocks in that language can be evaluated
230 with `org-babel-execute-src-block' bound by default to C-c
231 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
232 be set to remove code block evaluation from the C-c C-c
233 keybinding. By default only Emacs Lisp (which has no
234 requirements) is loaded."
235 :group 'org-babel
236 :set 'org-babel-do-load-languages
237 :version "24.1"
238 :type '(alist :tag "Babel Languages"
239 :key-type
240 (choice
241 (const :tag "Awk" awk)
242 (const :tag "C" C)
243 (const :tag "R" R)
244 (const :tag "Asymptote" asymptote)
245 (const :tag "Calc" calc)
246 (const :tag "Clojure" clojure)
247 (const :tag "CSS" css)
248 (const :tag "Ditaa" ditaa)
249 (const :tag "Dot" dot)
250 (const :tag "Emacs Lisp" emacs-lisp)
251 (const :tag "Fortran" fortran)
252 (const :tag "Gnuplot" gnuplot)
253 (const :tag "Haskell" haskell)
254 (const :tag "IO" io)
255 (const :tag "J" J)
256 (const :tag "Java" java)
257 (const :tag "Javascript" js)
258 (const :tag "LaTeX" latex)
259 (const :tag "Ledger" ledger)
260 (const :tag "Lilypond" lilypond)
261 (const :tag "Lisp" lisp)
262 (const :tag "Makefile" makefile)
263 (const :tag "Maxima" maxima)
264 (const :tag "Matlab" matlab)
265 (const :tag "Mscgen" mscgen)
266 (const :tag "Ocaml" ocaml)
267 (const :tag "Octave" octave)
268 (const :tag "Org" org)
269 (const :tag "Perl" perl)
270 (const :tag "Pico Lisp" picolisp)
271 (const :tag "PlantUML" plantuml)
272 (const :tag "Python" python)
273 (const :tag "Ruby" ruby)
274 (const :tag "Sass" sass)
275 (const :tag "Scala" scala)
276 (const :tag "Scheme" scheme)
277 (const :tag "Screen" screen)
278 (const :tag "Shell Script" shell)
279 (const :tag "Shen" shen)
280 (const :tag "Sql" sql)
281 (const :tag "Sqlite" sqlite)
282 (const :tag "ebnf2ps" ebnf2ps))
283 :value-type (boolean :tag "Activate" :value t)))
285 ;;;; Customization variables
286 (defcustom org-clone-delete-id nil
287 "Remove ID property of clones of a subtree.
288 When non-nil, clones of a subtree don't inherit the ID property.
289 Otherwise they inherit the ID property with a new unique
290 identifier."
291 :type 'boolean
292 :version "24.1"
293 :group 'org-id)
295 ;;; Version
296 (org-check-version)
298 ;;;###autoload
299 (defun org-version (&optional here full message)
300 "Show the org-mode version.
301 Interactively, or when MESSAGE is non-nil, show it in echo area.
302 With prefix argument, or when HERE is non-nil, insert it at point.
303 In non-interactive uses, a reduced version string is output unless
304 FULL is given."
305 (interactive (list current-prefix-arg t (not current-prefix-arg)))
306 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
307 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
308 (load-suffixes (list ".el"))
309 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
310 (org-trash (or
311 (and (fboundp 'org-release) (fboundp 'org-git-version))
312 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
313 (load-suffixes save-load-suffixes)
314 (org-version (org-release))
315 (git-version (org-git-version))
316 (version (format "Org-mode version %s (%s @ %s)"
317 org-version
318 git-version
319 (if org-install-dir
320 (if (string= org-dir org-install-dir)
321 org-install-dir
322 (concat "mixed installation! " org-install-dir " and " org-dir))
323 "org-loaddefs.el can not be found!")))
324 (version1 (if full version org-version)))
325 (when here (insert version1))
326 (when message (message "%s" version1))
327 version1))
329 (defconst org-version (org-version))
332 ;;; Syntax Constants
334 ;;;; Block
336 (defconst org-block-regexp
337 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
338 "Regular expression for hiding blocks.")
340 (defconst org-dblock-start-re
341 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
342 "Matches the start line of a dynamic block, with parameters.")
344 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
345 "Matches the end of a dynamic block.")
347 ;;;; Clock and Planning
349 (defconst org-clock-string "CLOCK:"
350 "String used as prefix for timestamps clocking work hours on an item.")
352 (defconst org-closed-string "CLOSED:"
353 "String used as the prefix for timestamps logging closing a TODO entry.")
355 (defconst org-deadline-string "DEADLINE:"
356 "String to mark deadline entries.
357 A deadline is this string, followed by a time stamp. Should be a word,
358 terminated by a colon. You can insert a schedule keyword and
359 a timestamp with \\[org-deadline].")
361 (defconst org-scheduled-string "SCHEDULED:"
362 "String to mark scheduled TODO entries.
363 A schedule is this string, followed by a time stamp. Should be a word,
364 terminated by a colon. You can insert a schedule keyword and
365 a timestamp with \\[org-schedule].")
367 (defconst org-planning-or-clock-line-re
368 (concat "^[ \t]*"
369 (regexp-opt
370 (list org-clock-string org-closed-string org-deadline-string
371 org-scheduled-string)
373 "Matches a line with planning or clock info.
374 Matched keyword is in group 1.")
376 ;;;; Drawer
378 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
379 "Matches first or last line of a hidden block.
380 Group 1 contains drawer's name or \"END\".")
382 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
383 "Regular expression matching the first line of a property drawer.")
385 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
386 "Regular expression matching the last line of a property drawer.")
388 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
389 "Regular expression matching the first line of a clock drawer.")
391 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
392 "Regular expression matching the last line of a clock drawer.")
394 (defconst org-property-drawer-re
395 (concat "\\(" org-property-start-re "\\)[^\000]*?\\("
396 org-property-end-re "\\)\n?")
397 "Matches an entire property drawer.")
399 (defconst org-clock-drawer-re
400 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
401 org-clock-drawer-end-re "\\)\n?")
402 "Matches an entire clock drawer.")
404 ;;;; Headline
406 (defconst org-heading-keyword-regexp-format
407 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
408 "Printf format for a regexp matching a headline with some keyword.
409 This regexp will match the headline of any node which has the
410 exact keyword that is put into the format. The keyword isn't in
411 any group by default, but the stars and the body are.")
413 (defconst org-heading-keyword-maybe-regexp-format
414 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
415 "Printf format for a regexp matching a headline, possibly with some keyword.
416 This regexp can match any headline with the specified keyword, or
417 without a keyword. The keyword isn't in any group by default,
418 but the stars and the body are.")
420 (defconst org-archive-tag "ARCHIVE"
421 "The tag that marks a subtree as archived.
422 An archived subtree does not open during visibility cycling, and does
423 not contribute to the agenda listings.")
425 (defconst org-comment-string "COMMENT"
426 "Entries starting with this keyword will never be exported.
427 An entry can be toggled between COMMENT and normal with
428 \\[org-toggle-comment].")
431 ;;;; LaTeX Environments and Fragments
433 (defconst org-latex-regexps
434 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
435 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
436 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
437 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
438 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
439 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
440 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
441 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
442 "Regular expressions for matching embedded LaTeX.")
444 ;;;; Node Property
446 (defconst org-effort-property "Effort"
447 "The property that is being used to keep track of effort estimates.
448 Effort estimates given in this property need to have the format H:MM.")
450 ;;;; Table
452 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
453 "Detect an org-type or table-type table.")
455 (defconst org-table-line-regexp "^[ \t]*|"
456 "Detect an org-type table line.")
458 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
459 "Detect an org-type table line.")
461 (defconst org-table-hline-regexp "^[ \t]*|-"
462 "Detect an org-type table hline.")
464 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
465 "Detect a table-type table hline.")
467 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
468 "Detect the first line outside a table when searching from within it.
469 This works for both table types.")
471 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
472 "Detect a #+TBLFM line.")
474 ;;;; Timestamp
476 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
477 "Regular expression for fast time stamp matching.")
479 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
480 "Regular expression for fast time stamp matching.")
482 (defconst org-ts-regexp0
483 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
484 "Regular expression matching time strings for analysis.
485 This one does not require the space after the date, so it can be used
486 on a string that terminates immediately after the date.")
488 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
489 "Regular expression matching time strings for analysis.")
491 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
492 "Regular expression matching time stamps, with groups.")
494 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
495 "Regular expression matching time stamps (also [..]), with groups.")
497 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
498 "Regular expression matching a time stamp range.")
500 (defconst org-tr-regexp-both
501 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
502 "Regular expression matching a time stamp range.")
504 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
505 org-ts-regexp "\\)?")
506 "Regular expression matching a time stamp or time stamp range.")
508 (defconst org-tsr-regexp-both
509 (concat org-ts-regexp-both "\\(--?-?"
510 org-ts-regexp-both "\\)?")
511 "Regular expression matching a time stamp or time stamp range.
512 The time stamps may be either active or inactive.")
514 (defconst org-repeat-re
515 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
516 "Regular expression for specifying repeated events.
517 After a match, group 1 contains the repeat expression.")
519 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
520 "Formats for `format-time-string' which are used for time stamps.")
523 ;;; The custom variables
525 (defgroup org nil
526 "Outline-based notes management and organizer."
527 :tag "Org"
528 :group 'outlines
529 :group 'calendar)
531 (defcustom org-mode-hook nil
532 "Mode hook for Org-mode, run after the mode was turned on."
533 :group 'org
534 :type 'hook)
536 (defcustom org-load-hook nil
537 "Hook that is run after org.el has been loaded."
538 :group 'org
539 :type 'hook)
541 (defcustom org-log-buffer-setup-hook nil
542 "Hook that is run after an Org log buffer is created."
543 :group 'org
544 :version "24.1"
545 :type 'hook)
547 (defvar org-modules) ; defined below
548 (defvar org-modules-loaded nil
549 "Have the modules been loaded already?")
551 (defun org-load-modules-maybe (&optional force)
552 "Load all extensions listed in `org-modules'."
553 (when (or force (not org-modules-loaded))
554 (mapc (lambda (ext)
555 (condition-case nil (require ext)
556 (error (message "Problems while trying to load feature `%s'" ext))))
557 org-modules)
558 (setq org-modules-loaded t)))
560 (defun org-set-modules (var value)
561 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
562 (set var value)
563 (when (featurep 'org)
564 (org-load-modules-maybe 'force)
565 (org-element-cache-reset 'all)))
567 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
568 "Modules that should always be loaded together with org.el.
570 If a description starts with <C>, the file is not part of Emacs
571 and loading it will require that you have downloaded and properly
572 installed the Org mode distribution.
574 You can also use this system to load external packages (i.e. neither Org
575 core modules, nor modules from the CONTRIB directory). Just add symbols
576 to the end of the list. If the package is called org-xyz.el, then you need
577 to add the symbol `xyz', and the package must have a call to:
579 \(provide 'org-xyz)
581 For export specific modules, see also `org-export-backends'."
582 :group 'org
583 :set 'org-set-modules
584 :version "24.4"
585 :package-version '(Org . "8.0")
586 :type
587 '(set :greedy t
588 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
589 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
590 (const :tag " crypt: Encryption of subtrees" org-crypt)
591 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
592 (const :tag " docview: Links to doc-view buffers" org-docview)
593 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
594 (const :tag " habit: Track your consistency with habits" org-habit)
595 (const :tag " id: Global IDs for identifying entries" org-id)
596 (const :tag " info: Links to Info nodes" org-info)
597 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
598 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
599 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
600 (const :tag " mouse: Additional mouse support" org-mouse)
601 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
602 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
603 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
605 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
606 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
607 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
608 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
609 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
610 (const :tag "C collector: Collect properties into tables" org-collector)
611 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
612 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
613 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
614 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
615 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
616 (const :tag "C eval: Include command output as text" org-eval)
617 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
618 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
619 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
620 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
621 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
622 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
623 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
624 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
625 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
626 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
627 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
628 (const :tag "C mew: Links to Mew folders/messages" org-mew)
629 (const :tag "C mtags: Support for muse-like tags" org-mtags)
630 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
631 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
632 (const :tag "C registry: A registry for Org-mode links" org-registry)
633 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
634 (const :tag "C secretary: Team management with org-mode" org-secretary)
635 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
636 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
637 (const :tag "C track: Keep up with Org-mode development" org-track)
638 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
639 (const :tag "C vm: Links to VM folders/messages" org-vm)
640 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
641 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
642 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
644 (defvar org-export--registered-backends) ; From ox.el.
645 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
646 (declare-function org-export-backend-name "ox" (backend))
647 (defcustom org-export-backends '(ascii html icalendar latex)
648 "List of export back-ends that should be always available.
650 If a description starts with <C>, the file is not part of Emacs
651 and loading it will require that you have downloaded and properly
652 installed the Org mode distribution.
654 Unlike to `org-modules', libraries in this list will not be
655 loaded along with Org, but only once the export framework is
656 needed.
658 This variable needs to be set before org.el is loaded. If you
659 need to make a change while Emacs is running, use the customize
660 interface or run the following code, where VAL stands for the new
661 value of the variable, after updating it:
663 \(progn
664 \(setq org-export--registered-backends
665 \(org-remove-if-not
666 \(lambda (backend)
667 \(let ((name (org-export-backend-name backend)))
668 \(or (memq name val)
669 \(catch 'parentp
670 \(dolist (b val)
671 \(and (org-export-derived-backend-p b name)
672 \(throw 'parentp t)))))))
673 org-export--registered-backends))
674 \(let ((new-list (mapcar 'org-export-backend-name
675 org-export--registered-backends)))
676 \(dolist (backend val)
677 \(cond
678 \((not (load (format \"ox-%s\" backend) t t))
679 \(message \"Problems while trying to load export back-end `%s'\"
680 backend))
681 \((not (memq backend new-list)) (push backend new-list))))
682 \(set-default 'org-export-backends new-list)))
684 Adding a back-end to this list will also pull the back-end it
685 depends on, if any."
686 :group 'org
687 :group 'org-export
688 :version "24.4"
689 :package-version '(Org . "8.0")
690 :initialize 'custom-initialize-set
691 :set (lambda (var val)
692 (if (not (featurep 'ox)) (set-default var val)
693 ;; Any back-end not required anymore (not present in VAL and not
694 ;; a parent of any back-end in the new value) is removed from the
695 ;; list of registered back-ends.
696 (setq org-export--registered-backends
697 (org-remove-if-not
698 (lambda (backend)
699 (let ((name (org-export-backend-name backend)))
700 (or (memq name val)
701 (catch 'parentp
702 (dolist (b val)
703 (and (org-export-derived-backend-p b name)
704 (throw 'parentp t)))))))
705 org-export--registered-backends))
706 ;; Now build NEW-LIST of both new back-ends and required
707 ;; parents.
708 (let ((new-list (mapcar 'org-export-backend-name
709 org-export--registered-backends)))
710 (dolist (backend val)
711 (cond
712 ((not (load (format "ox-%s" backend) t t))
713 (message "Problems while trying to load export back-end `%s'"
714 backend))
715 ((not (memq backend new-list)) (push backend new-list))))
716 ;; Set VAR to that list with fixed dependencies.
717 (set-default var new-list))))
718 :type '(set :greedy t
719 (const :tag " ascii Export buffer to ASCII format" ascii)
720 (const :tag " beamer Export buffer to Beamer presentation" beamer)
721 (const :tag " html Export buffer to HTML format" html)
722 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
723 (const :tag " latex Export buffer to LaTeX format" latex)
724 (const :tag " man Export buffer to MAN format" man)
725 (const :tag " md Export buffer to Markdown format" md)
726 (const :tag " odt Export buffer to ODT format" odt)
727 (const :tag " org Export buffer to Org format" org)
728 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
729 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
730 (const :tag "C deck Export buffer to deck.js presentations" deck)
731 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
732 (const :tag "C groff Export buffer to Groff format" groff)
733 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
734 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
735 (const :tag "C s5 Export buffer to s5 presentations" s5)
736 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
738 (eval-after-load 'ox
739 '(mapc
740 (lambda (backend)
741 (condition-case nil (require (intern (format "ox-%s" backend)))
742 (error (message "Problems while trying to load export back-end `%s'"
743 backend))))
744 org-export-backends))
746 (defcustom org-support-shift-select nil
747 "Non-nil means make shift-cursor commands select text when possible.
749 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
750 start selecting a region, or enlarge regions started in this way.
751 In Org-mode, in special contexts, these same keys are used for
752 other purposes, important enough to compete with shift selection.
753 Org tries to balance these needs by supporting `shift-select-mode'
754 outside these special contexts, under control of this variable.
756 The default of this variable is nil, to avoid confusing behavior. Shifted
757 cursor keys will then execute Org commands in the following contexts:
758 - on a headline, changing TODO state (left/right) and priority (up/down)
759 - on a time stamp, changing the time
760 - in a plain list item, changing the bullet type
761 - in a property definition line, switching between allowed values
762 - in the BEGIN line of a clock table (changing the time block).
763 Outside these contexts, the commands will throw an error.
765 When this variable is t and the cursor is not in a special
766 context, Org-mode will support shift-selection for making and
767 enlarging regions. To make this more effective, the bullet
768 cycling will no longer happen anywhere in an item line, but only
769 if the cursor is exactly on the bullet.
771 If you set this variable to the symbol `always', then the keys
772 will not be special in headlines, property lines, and item lines,
773 to make shift selection work there as well. If this is what you
774 want, you can use the following alternative commands: `C-c C-t'
775 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
776 can be used to switch TODO sets, `C-c -' to cycle item bullet
777 types, and properties can be edited by hand or in column view.
779 However, when the cursor is on a timestamp, shift-cursor commands
780 will still edit the time stamp - this is just too good to give up.
782 XEmacs user should have this variable set to nil, because
783 `shift-select-mode' is in Emacs 23 or later only."
784 :group 'org
785 :type '(choice
786 (const :tag "Never" nil)
787 (const :tag "When outside special context" t)
788 (const :tag "Everywhere except timestamps" always)))
790 (defcustom org-loop-over-headlines-in-active-region nil
791 "Shall some commands act upon headlines in the active region?
793 When set to `t', some commands will be performed in all headlines
794 within the active region.
796 When set to `start-level', some commands will be performed in all
797 headlines within the active region, provided that these headlines
798 are of the same level than the first one.
800 When set to a string, those commands will be performed on the
801 matching headlines within the active region. Such string must be
802 a tags/property/todo match as it is used in the agenda tags view.
804 The list of commands is: `org-schedule', `org-deadline',
805 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
806 `org-archive-to-archive-sibling'. The archiving commands skip
807 already archived entries."
808 :type '(choice (const :tag "Don't loop" nil)
809 (const :tag "All headlines in active region" t)
810 (const :tag "In active region, headlines at the same level than the first one" start-level)
811 (string :tag "Tags/Property/Todo matcher"))
812 :version "24.1"
813 :group 'org-todo
814 :group 'org-archive)
816 (defgroup org-startup nil
817 "Options concerning startup of Org-mode."
818 :tag "Org Startup"
819 :group 'org)
821 (defcustom org-startup-folded t
822 "Non-nil means entering Org-mode will switch to OVERVIEW.
823 This can also be configured on a per-file basis by adding one of
824 the following lines anywhere in the buffer:
826 #+STARTUP: fold (or `overview', this is equivalent)
827 #+STARTUP: nofold (or `showall', this is equivalent)
828 #+STARTUP: content
829 #+STARTUP: showeverything
831 By default, this option is ignored when Org opens agenda files
832 for the first time. If you want the agenda to honor the startup
833 option, set `org-agenda-inhibit-startup' to nil."
834 :group 'org-startup
835 :type '(choice
836 (const :tag "nofold: show all" nil)
837 (const :tag "fold: overview" t)
838 (const :tag "content: all headlines" content)
839 (const :tag "show everything, even drawers" showeverything)))
841 (defcustom org-startup-truncated t
842 "Non-nil means entering Org-mode will set `truncate-lines'.
843 This is useful since some lines containing links can be very long and
844 uninteresting. Also tables look terrible when wrapped."
845 :group 'org-startup
846 :type 'boolean)
848 (defcustom org-startup-indented nil
849 "Non-nil means turn on `org-indent-mode' on startup.
850 This can also be configured on a per-file basis by adding one of
851 the following lines anywhere in the buffer:
853 #+STARTUP: indent
854 #+STARTUP: noindent"
855 :group 'org-structure
856 :type '(choice
857 (const :tag "Not" nil)
858 (const :tag "Globally (slow on startup in large files)" t)))
860 (defcustom org-use-sub-superscripts t
861 "Non-nil means interpret \"_\" and \"^\" for display.
863 If you want to control how Org exports those characters, see
864 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
865 used to be an alias for `org-export-with-sub-superscripts' in
866 Org <8.0, it is not anymore.
868 When this option is turned on, you can use TeX-like syntax for
869 sub- and superscripts within the buffer. Several characters after
870 \"_\" or \"^\" will be considered as a single item - so grouping
871 with {} is normally not needed. For example, the following things
872 will be parsed as single sub- or superscripts:
874 10^24 or 10^tau several digits will be considered 1 item.
875 10^-12 or 10^-tau a leading sign with digits or a word
876 x^2-y^3 will be read as x^2 - y^3, because items are
877 terminated by almost any nonword/nondigit char.
878 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
880 Still, ambiguity is possible. So when in doubt, use {} to enclose
881 the sub/superscript. If you set this variable to the symbol `{}',
882 the braces are *required* in order to trigger interpretations as
883 sub/superscript. This can be helpful in documents that need \"_\"
884 frequently in plain text."
885 :group 'org-startup
886 :version "24.4"
887 :package-version '(Org . "8.0")
888 :type '(choice
889 (const :tag "Always interpret" t)
890 (const :tag "Only with braces" {})
891 (const :tag "Never interpret" nil)))
893 (defcustom org-startup-with-beamer-mode nil
894 "Non-nil means turn on `org-beamer-mode' on startup.
895 This can also be configured on a per-file basis by adding one of
896 the following lines anywhere in the buffer:
898 #+STARTUP: beamer"
899 :group 'org-startup
900 :version "24.1"
901 :type 'boolean)
903 (defcustom org-startup-align-all-tables nil
904 "Non-nil means align all tables when visiting a file.
905 This is useful when the column width in tables is forced with <N> cookies
906 in table fields. Such tables will look correct only after the first re-align.
907 This can also be configured on a per-file basis by adding one of
908 the following lines anywhere in the buffer:
909 #+STARTUP: align
910 #+STARTUP: noalign"
911 :group 'org-startup
912 :type 'boolean)
914 (defcustom org-startup-with-inline-images nil
915 "Non-nil means show inline images when loading a new Org file.
916 This can also be configured on a per-file basis by adding one of
917 the following lines anywhere in the buffer:
918 #+STARTUP: inlineimages
919 #+STARTUP: noinlineimages"
920 :group 'org-startup
921 :version "24.1"
922 :type 'boolean)
924 (defcustom org-startup-with-latex-preview nil
925 "Non-nil means preview LaTeX fragments when loading a new Org file.
927 This can also be configured on a per-file basis by adding one of
928 the following lines anywhere in the buffer:
929 #+STARTUP: latexpreview
930 #+STARTUP: nolatexpreview"
931 :group 'org-startup
932 :version "24.4"
933 :package-version '(Org . "8.0")
934 :type 'boolean)
936 (defcustom org-insert-mode-line-in-empty-file nil
937 "Non-nil means insert the first line setting Org-mode in empty files.
938 When the function `org-mode' is called interactively in an empty file, this
939 normally means that the file name does not automatically trigger Org-mode.
940 To ensure that the file will always be in Org-mode in the future, a
941 line enforcing Org-mode will be inserted into the buffer, if this option
942 has been set."
943 :group 'org-startup
944 :type 'boolean)
946 (defcustom org-replace-disputed-keys nil
947 "Non-nil means use alternative key bindings for some keys.
948 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
949 These keys are also used by other packages like shift-selection-mode'
950 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
951 If you want to use Org-mode together with one of these other modes,
952 or more generally if you would like to move some Org-mode commands to
953 other keys, set this variable and configure the keys with the variable
954 `org-disputed-keys'.
956 This option is only relevant at load-time of Org-mode, and must be set
957 *before* org.el is loaded. Changing it requires a restart of Emacs to
958 become effective."
959 :group 'org-startup
960 :type 'boolean)
962 (defcustom org-use-extra-keys nil
963 "Non-nil means use extra key sequence definitions for certain commands.
964 This happens automatically if you run XEmacs or if `window-system'
965 is nil. This variable lets you do the same manually. You must
966 set it before loading org.
968 Example: on Carbon Emacs 22 running graphically, with an external
969 keyboard on a Powerbook, the default way of setting M-left might
970 not work for either Alt or ESC. Setting this variable will make
971 it work for ESC."
972 :group 'org-startup
973 :type 'boolean)
975 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
977 (defcustom org-disputed-keys
978 '(([(shift up)] . [(meta p)])
979 ([(shift down)] . [(meta n)])
980 ([(shift left)] . [(meta -)])
981 ([(shift right)] . [(meta +)])
982 ([(control shift right)] . [(meta shift +)])
983 ([(control shift left)] . [(meta shift -)]))
984 "Keys for which Org-mode and other modes compete.
985 This is an alist, cars are the default keys, second element specifies
986 the alternative to use when `org-replace-disputed-keys' is t.
988 Keys can be specified in any syntax supported by `define-key'.
989 The value of this option takes effect only at Org-mode's startup,
990 therefore you'll have to restart Emacs to apply it after changing."
991 :group 'org-startup
992 :type 'alist)
994 (defun org-key (key)
995 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
996 Or return the original if not disputed.
997 Also apply the translations defined in `org-xemacs-key-equivalents'."
998 (when org-replace-disputed-keys
999 (let* ((nkey (key-description key))
1000 (x (org-find-if (lambda (x)
1001 (equal (key-description (car x)) nkey))
1002 org-disputed-keys)))
1003 (setq key (if x (cdr x) key))))
1004 (when (featurep 'xemacs)
1005 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
1006 key)
1008 (defun org-find-if (predicate seq)
1009 (catch 'exit
1010 (while seq
1011 (if (funcall predicate (car seq))
1012 (throw 'exit (car seq))
1013 (pop seq)))))
1015 (defun org-defkey (keymap key def)
1016 "Define a key, possibly translated, as returned by `org-key'."
1017 (define-key keymap (org-key key) def))
1019 (defcustom org-ellipsis nil
1020 "The ellipsis to use in the Org-mode outline.
1021 When nil, just use the standard three dots.
1022 When a string, use that string instead.
1023 When a face, use the standard 3 dots, but with the specified face.
1024 The change affects only Org-mode (which will then use its own display table).
1025 Changing this requires executing `M-x org-mode RET' in a buffer to become
1026 effective."
1027 :group 'org-startup
1028 :type '(choice (const :tag "Default" nil)
1029 (face :tag "Face" :value org-warning)
1030 (string :tag "String" :value "...#")))
1032 (defvar org-display-table nil
1033 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
1035 (defgroup org-keywords nil
1036 "Keywords in Org-mode."
1037 :tag "Org Keywords"
1038 :group 'org)
1040 (defcustom org-closed-keep-when-no-todo nil
1041 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1042 :group 'org-todo
1043 :group 'org-keywords
1044 :version "24.4"
1045 :package-version '(Org . "8.0")
1046 :type 'boolean)
1048 (defgroup org-structure nil
1049 "Options concerning the general structure of Org-mode files."
1050 :tag "Org Structure"
1051 :group 'org)
1053 (defgroup org-reveal-location nil
1054 "Options about how to make context of a location visible."
1055 :tag "Org Reveal Location"
1056 :group 'org-structure)
1058 (defconst org-context-choice
1059 '(choice
1060 (const :tag "Always" t)
1061 (const :tag "Never" nil)
1062 (repeat :greedy t :tag "Individual contexts"
1063 (cons
1064 (choice :tag "Context"
1065 (const agenda)
1066 (const org-goto)
1067 (const occur-tree)
1068 (const tags-tree)
1069 (const link-search)
1070 (const mark-goto)
1071 (const bookmark-jump)
1072 (const isearch)
1073 (const default))
1074 (boolean))))
1075 "Contexts for the reveal options.")
1077 (defcustom org-show-hierarchy-above '((default . t))
1078 "Non-nil means show full hierarchy when revealing a location.
1079 Org-mode often shows locations in an org-mode file which might have
1080 been invisible before. When this is set, the hierarchy of headings
1081 above the exposed location is shown.
1082 Turning this off for example for sparse trees makes them very compact.
1083 Instead of t, this can also be an alist specifying this option for different
1084 contexts. Valid contexts are
1085 agenda when exposing an entry from the agenda
1086 org-goto when using the command `org-goto' on key C-c C-j
1087 occur-tree when using the command `org-occur' on key C-c /
1088 tags-tree when constructing a sparse tree based on tags matches
1089 link-search when exposing search matches associated with a link
1090 mark-goto when exposing the jump goal of a mark
1091 bookmark-jump when exposing a bookmark location
1092 isearch when exiting from an incremental search
1093 default default for all contexts not set explicitly"
1094 :group 'org-reveal-location
1095 :type org-context-choice)
1097 (defcustom org-show-following-heading '((default . nil))
1098 "Non-nil means show following heading when revealing a location.
1099 Org-mode often shows locations in an org-mode file which might have
1100 been invisible before. When this is set, the heading following the
1101 match is shown.
1102 Turning this off for example for sparse trees makes them very compact,
1103 but makes it harder to edit the location of the match. In such a case,
1104 use the command \\[org-reveal] to show more context.
1105 Instead of t, this can also be an alist specifying this option for different
1106 contexts. See `org-show-hierarchy-above' for valid contexts."
1107 :group 'org-reveal-location
1108 :type org-context-choice)
1110 (defcustom org-show-siblings '((default . nil) (isearch t) (bookmark-jump t))
1111 "Non-nil means show all sibling heading when revealing a location.
1112 Org-mode often shows locations in an org-mode file which might have
1113 been invisible before. When this is set, the sibling of the current entry
1114 heading are all made visible. If `org-show-hierarchy-above' is t,
1115 the same happens on each level of the hierarchy above the current entry.
1117 By default this is on for the isearch context, off for all other contexts.
1118 Turning this off for example for sparse trees makes them very compact,
1119 but makes it harder to edit the location of the match. In such a case,
1120 use the command \\[org-reveal] to show more context.
1121 Instead of t, this can also be an alist specifying this option for different
1122 contexts. See `org-show-hierarchy-above' for valid contexts."
1123 :group 'org-reveal-location
1124 :type org-context-choice
1125 :version "24.4"
1126 :package-version '(Org . "8.0"))
1128 (defcustom org-show-entry-below '((default . nil))
1129 "Non-nil means show the entry below a headline when revealing a location.
1130 Org-mode often shows locations in an org-mode file which might have
1131 been invisible before. When this is set, the text below the headline that is
1132 exposed is also shown.
1134 By default this is off for all contexts.
1135 Instead of t, this can also be an alist specifying this option for different
1136 contexts. See `org-show-hierarchy-above' for valid contexts."
1137 :group 'org-reveal-location
1138 :type org-context-choice)
1140 (defcustom org-indirect-buffer-display 'other-window
1141 "How should indirect tree buffers be displayed?
1142 This applies to indirect buffers created with the commands
1143 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
1144 Valid values are:
1145 current-window Display in the current window
1146 other-window Just display in another window.
1147 dedicated-frame Create one new frame, and re-use it each time.
1148 new-frame Make a new frame each time. Note that in this case
1149 previously-made indirect buffers are kept, and you need to
1150 kill these buffers yourself."
1151 :group 'org-structure
1152 :group 'org-agenda-windows
1153 :type '(choice
1154 (const :tag "In current window" current-window)
1155 (const :tag "In current frame, other window" other-window)
1156 (const :tag "Each time a new frame" new-frame)
1157 (const :tag "One dedicated frame" dedicated-frame)))
1159 (defcustom org-use-speed-commands nil
1160 "Non-nil means activate single letter commands at beginning of a headline.
1161 This may also be a function to test for appropriate locations where speed
1162 commands should be active.
1164 For example, to activate speed commands when the point is on any
1165 star at the beginning of the headline, you can do this:
1167 (setq org-use-speed-commands
1168 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1169 :group 'org-structure
1170 :type '(choice
1171 (const :tag "Never" nil)
1172 (const :tag "At beginning of headline stars" t)
1173 (function)))
1175 (defcustom org-speed-commands-user nil
1176 "Alist of additional speed commands.
1177 This list will be checked before `org-speed-commands-default'
1178 when the variable `org-use-speed-commands' is non-nil
1179 and when the cursor is at the beginning of a headline.
1180 The car if each entry is a string with a single letter, which must
1181 be assigned to `self-insert-command' in the global map.
1182 The cdr is either a command to be called interactively, a function
1183 to be called, or a form to be evaluated.
1184 An entry that is just a list with a single string will be interpreted
1185 as a descriptive headline that will be added when listing the speed
1186 commands in the Help buffer using the `?' speed command."
1187 :group 'org-structure
1188 :type '(repeat :value ("k" . ignore)
1189 (choice :value ("k" . ignore)
1190 (list :tag "Descriptive Headline" (string :tag "Headline"))
1191 (cons :tag "Letter and Command"
1192 (string :tag "Command letter")
1193 (choice
1194 (function)
1195 (sexp))))))
1197 (defcustom org-bookmark-names-plist
1198 '(:last-capture "org-capture-last-stored"
1199 :last-refile "org-refile-last-stored"
1200 :last-capture-marker "org-capture-last-stored-marker")
1201 "Names for bookmarks automatically set by some Org commands.
1202 This can provide strings as names for a number of bookmarks Org sets
1203 automatically. The following keys are currently implemented:
1204 :last-capture
1205 :last-capture-marker
1206 :last-refile
1207 When a key does not show up in the property list, the corresponding bookmark
1208 is not set."
1209 :group 'org-structure
1210 :type 'plist)
1212 (defgroup org-cycle nil
1213 "Options concerning visibility cycling in Org-mode."
1214 :tag "Org Cycle"
1215 :group 'org-structure)
1217 (defcustom org-cycle-skip-children-state-if-no-children t
1218 "Non-nil means skip CHILDREN state in entries that don't have any."
1219 :group 'org-cycle
1220 :type 'boolean)
1222 (defcustom org-cycle-max-level nil
1223 "Maximum level which should still be subject to visibility cycling.
1224 Levels higher than this will, for cycling, be treated as text, not a headline.
1225 When `org-odd-levels-only' is set, a value of N in this variable actually
1226 means 2N-1 stars as the limiting headline.
1227 When nil, cycle all levels.
1228 Note that the limiting level of cycling is also influenced by
1229 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1230 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1231 than its value."
1232 :group 'org-cycle
1233 :type '(choice
1234 (const :tag "No limit" nil)
1235 (integer :tag "Maximum level")))
1237 (defcustom org-hide-block-startup nil
1238 "Non-nil means entering Org-mode will fold all blocks.
1239 This can also be set in on a per-file basis with
1241 #+STARTUP: hideblocks
1242 #+STARTUP: showblocks"
1243 :group 'org-startup
1244 :group 'org-cycle
1245 :type 'boolean)
1247 (defcustom org-cycle-global-at-bob nil
1248 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1249 This makes it possible to do global cycling without having to use S-TAB or
1250 \\[universal-argument] TAB. For this special case to work, the first line
1251 of the buffer must not be a headline -- it may be empty or some other text.
1252 When used in this way, `org-cycle-hook' is disabled temporarily to make
1253 sure the cursor stays at the beginning of the buffer. When this option is
1254 nil, don't do anything special at the beginning of the buffer."
1255 :group 'org-cycle
1256 :type 'boolean)
1258 (defcustom org-cycle-level-after-item/entry-creation t
1259 "Non-nil means cycle entry level or item indentation in new empty entries.
1261 When the cursor is at the end of an empty headline, i.e., with only stars
1262 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1263 and then all possible ancestor states, before returning to the original state.
1264 This makes data entry extremely fast: M-RET to create a new headline,
1265 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1267 When the cursor is at the end of an empty plain list item, one TAB will
1268 make it a subitem, two or more tabs will back up to make this an item
1269 higher up in the item hierarchy."
1270 :group 'org-cycle
1271 :type 'boolean)
1273 (defcustom org-cycle-emulate-tab t
1274 "Where should `org-cycle' emulate TAB.
1275 nil Never
1276 white Only in completely white lines
1277 whitestart Only at the beginning of lines, before the first non-white char
1278 t Everywhere except in headlines
1279 exc-hl-bol Everywhere except at the start of a headline
1280 If TAB is used in a place where it does not emulate TAB, the current subtree
1281 visibility is cycled."
1282 :group 'org-cycle
1283 :type '(choice (const :tag "Never" nil)
1284 (const :tag "Only in completely white lines" white)
1285 (const :tag "Before first char in a line" whitestart)
1286 (const :tag "Everywhere except in headlines" t)
1287 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1289 (defcustom org-cycle-separator-lines 2
1290 "Number of empty lines needed to keep an empty line between collapsed trees.
1291 If you leave an empty line between the end of a subtree and the following
1292 headline, this empty line is hidden when the subtree is folded.
1293 Org-mode will leave (exactly) one empty line visible if the number of
1294 empty lines is equal or larger to the number given in this variable.
1295 So the default 2 means at least 2 empty lines after the end of a subtree
1296 are needed to produce free space between a collapsed subtree and the
1297 following headline.
1299 If the number is negative, and the number of empty lines is at least -N,
1300 all empty lines are shown.
1302 Special case: when 0, never leave empty lines in collapsed view."
1303 :group 'org-cycle
1304 :type 'integer)
1305 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1307 (defcustom org-pre-cycle-hook nil
1308 "Hook that is run before visibility cycling is happening.
1309 The function(s) in this hook must accept a single argument which indicates
1310 the new state that will be set right after running this hook. The
1311 argument is a symbol. Before a global state change, it can have the values
1312 `overview', `content', or `all'. Before a local state change, it can have
1313 the values `folded', `children', or `subtree'."
1314 :group 'org-cycle
1315 :type 'hook)
1317 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1318 org-cycle-hide-drawers
1319 org-cycle-hide-inline-tasks
1320 org-cycle-show-empty-lines
1321 org-optimize-window-after-visibility-change)
1322 "Hook that is run after `org-cycle' has changed the buffer visibility.
1323 The function(s) in this hook must accept a single argument which indicates
1324 the new state that was set by the most recent `org-cycle' command. The
1325 argument is a symbol. After a global state change, it can have the values
1326 `overview', `contents', or `all'. After a local state change, it can have
1327 the values `folded', `children', or `subtree'."
1328 :group 'org-cycle
1329 :type 'hook)
1331 (defgroup org-edit-structure nil
1332 "Options concerning structure editing in Org-mode."
1333 :tag "Org Edit Structure"
1334 :group 'org-structure)
1336 (defcustom org-odd-levels-only nil
1337 "Non-nil means skip even levels and only use odd levels for the outline.
1338 This has the effect that two stars are being added/taken away in
1339 promotion/demotion commands. It also influences how levels are
1340 handled by the exporters.
1341 Changing it requires restart of `font-lock-mode' to become effective
1342 for fontification also in regions already fontified.
1343 You may also set this on a per-file basis by adding one of the following
1344 lines to the buffer:
1346 #+STARTUP: odd
1347 #+STARTUP: oddeven"
1348 :group 'org-edit-structure
1349 :group 'org-appearance
1350 :type 'boolean)
1352 (defcustom org-adapt-indentation t
1353 "Non-nil means adapt indentation to outline node level.
1355 When this variable is set, Org assumes that you write outlines by
1356 indenting text in each node to align with the headline (after the stars).
1357 The following issues are influenced by this variable:
1359 - When this is set and the *entire* text in an entry is indented, the
1360 indentation is increased by one space in a demotion command, and
1361 decreased by one in a promotion command. If any line in the entry
1362 body starts with text at column 0, indentation is not changed at all.
1364 - Property drawers and planning information is inserted indented when
1365 this variable s set. When nil, they will not be indented.
1367 - TAB indents a line relative to context. The lines below a headline
1368 will be indented when this variable is set.
1370 Note that this is all about true indentation, by adding and removing
1371 space characters. See also `org-indent.el' which does level-dependent
1372 indentation in a virtual way, i.e. at display time in Emacs."
1373 :group 'org-edit-structure
1374 :type 'boolean)
1376 (defcustom org-special-ctrl-a/e nil
1377 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1379 When t, `C-a' will bring back the cursor to the beginning of the
1380 headline text, i.e. after the stars and after a possible TODO
1381 keyword. In an item, this will be the position after bullet and
1382 check-box, if any. When the cursor is already at that position,
1383 another `C-a' will bring it to the beginning of the line.
1385 `C-e' will jump to the end of the headline, ignoring the presence
1386 of tags in the headline. A second `C-e' will then jump to the
1387 true end of the line, after any tags. This also means that, when
1388 this variable is non-nil, `C-e' also will never jump beyond the
1389 end of the heading of a folded section, i.e. not after the
1390 ellipses.
1392 When set to the symbol `reversed', the first `C-a' or `C-e' works
1393 normally, going to the true line boundary first. Only a directly
1394 following, identical keypress will bring the cursor to the
1395 special positions.
1397 This may also be a cons cell where the behavior for `C-a' and
1398 `C-e' is set separately."
1399 :group 'org-edit-structure
1400 :type '(choice
1401 (const :tag "off" nil)
1402 (const :tag "on: after stars/bullet and before tags first" t)
1403 (const :tag "reversed: true line boundary first" reversed)
1404 (cons :tag "Set C-a and C-e separately"
1405 (choice :tag "Special C-a"
1406 (const :tag "off" nil)
1407 (const :tag "on: after stars/bullet first" t)
1408 (const :tag "reversed: before stars/bullet first" reversed))
1409 (choice :tag "Special C-e"
1410 (const :tag "off" nil)
1411 (const :tag "on: before tags first" t)
1412 (const :tag "reversed: after tags first" reversed)))))
1413 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1415 (defcustom org-special-ctrl-k nil
1416 "Non-nil means `C-k' will behave specially in headlines.
1417 When nil, `C-k' will call the default `kill-line' command.
1418 When t, the following will happen while the cursor is in the headline:
1420 - When the cursor is at the beginning of a headline, kill the entire
1421 line and possible the folded subtree below the line.
1422 - When in the middle of the headline text, kill the headline up to the tags.
1423 - When after the headline text, kill the tags."
1424 :group 'org-edit-structure
1425 :type 'boolean)
1427 (defcustom org-ctrl-k-protect-subtree nil
1428 "Non-nil means, do not delete a hidden subtree with C-k.
1429 When set to the symbol `error', simply throw an error when C-k is
1430 used to kill (part-of) a headline that has hidden text behind it.
1431 Any other non-nil value will result in a query to the user, if it is
1432 OK to kill that hidden subtree. When nil, kill without remorse."
1433 :group 'org-edit-structure
1434 :version "24.1"
1435 :type '(choice
1436 (const :tag "Do not protect hidden subtrees" nil)
1437 (const :tag "Protect hidden subtrees with a security query" t)
1438 (const :tag "Never kill a hidden subtree with C-k" error)))
1440 (defcustom org-special-ctrl-o t
1441 "Non-nil means, make `C-o' insert a row in tables."
1442 :group 'org-edit-structure
1443 :type 'boolean)
1445 (defcustom org-catch-invisible-edits nil
1446 "Check if in invisible region before inserting or deleting a character.
1447 Valid values are:
1449 nil Do not check, so just do invisible edits.
1450 error Throw an error and do nothing.
1451 show Make point visible, and do the requested edit.
1452 show-and-error Make point visible, then throw an error and abort the edit.
1453 smart Make point visible, and do insertion/deletion if it is
1454 adjacent to visible text and the change feels predictable.
1455 Never delete a previously invisible character or add in the
1456 middle or right after an invisible region. Basically, this
1457 allows insertion and backward-delete right before ellipses.
1458 FIXME: maybe in this case we should not even show?"
1459 :group 'org-edit-structure
1460 :version "24.1"
1461 :type '(choice
1462 (const :tag "Do not check" nil)
1463 (const :tag "Throw error when trying to edit" error)
1464 (const :tag "Unhide, but do not do the edit" show-and-error)
1465 (const :tag "Show invisible part and do the edit" show)
1466 (const :tag "Be smart and do the right thing" smart)))
1468 (defcustom org-yank-folded-subtrees t
1469 "Non-nil means when yanking subtrees, fold them.
1470 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1471 it starts with a heading and all other headings in it are either children
1472 or siblings, then fold all the subtrees. However, do this only if no
1473 text after the yank would be swallowed into a folded tree by this action."
1474 :group 'org-edit-structure
1475 :type 'boolean)
1477 (defcustom org-yank-adjusted-subtrees nil
1478 "Non-nil means when yanking subtrees, adjust the level.
1479 With this setting, `org-paste-subtree' is used to insert the subtree, see
1480 this function for details."
1481 :group 'org-edit-structure
1482 :type 'boolean)
1484 (defcustom org-M-RET-may-split-line '((default . t))
1485 "Non-nil means M-RET will split the line at the cursor position.
1486 When nil, it will go to the end of the line before making a
1487 new line.
1488 You may also set this option in a different way for different
1489 contexts. Valid contexts are:
1491 headline when creating a new headline
1492 item when creating a new item
1493 table in a table field
1494 default the value to be used for all contexts not explicitly
1495 customized"
1496 :group 'org-structure
1497 :group 'org-table
1498 :type '(choice
1499 (const :tag "Always" t)
1500 (const :tag "Never" nil)
1501 (repeat :greedy t :tag "Individual contexts"
1502 (cons
1503 (choice :tag "Context"
1504 (const headline)
1505 (const item)
1506 (const table)
1507 (const default))
1508 (boolean)))))
1511 (defcustom org-insert-heading-respect-content nil
1512 "Non-nil means insert new headings after the current subtree.
1513 When nil, the new heading is created directly after the current line.
1514 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1515 this variable on for the duration of the command."
1516 :group 'org-structure
1517 :type 'boolean)
1519 (defcustom org-blank-before-new-entry '((heading . auto)
1520 (plain-list-item . auto))
1521 "Should `org-insert-heading' leave a blank line before new heading/item?
1522 The value is an alist, with `heading' and `plain-list-item' as CAR,
1523 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1524 which case Org will look at the surrounding headings/items and try to
1525 make an intelligent decision whether to insert a blank line or not.
1527 For plain lists, if `org-list-empty-line-terminates-plain-lists' is set,
1528 the setting here is ignored and no empty line is inserted to avoid breaking
1529 the list structure."
1530 :group 'org-edit-structure
1531 :type '(list
1532 (cons (const heading)
1533 (choice (const :tag "Never" nil)
1534 (const :tag "Always" t)
1535 (const :tag "Auto" auto)))
1536 (cons (const plain-list-item)
1537 (choice (const :tag "Never" nil)
1538 (const :tag "Always" t)
1539 (const :tag "Auto" auto)))))
1541 (defcustom org-insert-heading-hook nil
1542 "Hook being run after inserting a new heading."
1543 :group 'org-edit-structure
1544 :type 'hook)
1546 (defcustom org-enable-fixed-width-editor t
1547 "Non-nil means lines starting with \":\" are treated as fixed-width.
1548 This currently only means they are never auto-wrapped.
1549 When nil, such lines will be treated like ordinary lines."
1550 :group 'org-edit-structure
1551 :type 'boolean)
1553 (defcustom org-goto-auto-isearch t
1554 "Non-nil means typing characters in `org-goto' starts incremental search.
1555 When nil, you can use these keybindings to navigate the buffer:
1557 q Quit the org-goto interface
1558 n Go to the next visible heading
1559 p Go to the previous visible heading
1560 f Go one heading forward on same level
1561 b Go one heading backward on same level
1562 u Go one heading up"
1563 :group 'org-edit-structure
1564 :type 'boolean)
1566 (defgroup org-sparse-trees nil
1567 "Options concerning sparse trees in Org-mode."
1568 :tag "Org Sparse Trees"
1569 :group 'org-structure)
1571 (defcustom org-highlight-sparse-tree-matches t
1572 "Non-nil means highlight all matches that define a sparse tree.
1573 The highlights will automatically disappear the next time the buffer is
1574 changed by an edit command."
1575 :group 'org-sparse-trees
1576 :type 'boolean)
1578 (defcustom org-remove-highlights-with-change t
1579 "Non-nil means any change to the buffer will remove temporary highlights.
1580 Such highlights are created by `org-occur' and `org-clock-display'.
1581 When nil, `C-c C-c needs to be used to get rid of the highlights.
1582 The highlights created by `org-preview-latex-fragment' always need
1583 `C-c C-c' to be removed."
1584 :group 'org-sparse-trees
1585 :group 'org-time
1586 :type 'boolean)
1589 (defcustom org-occur-hook '(org-first-headline-recenter)
1590 "Hook that is run after `org-occur' has constructed a sparse tree.
1591 This can be used to recenter the window to show as much of the structure
1592 as possible."
1593 :group 'org-sparse-trees
1594 :type 'hook)
1596 (defgroup org-imenu-and-speedbar nil
1597 "Options concerning imenu and speedbar in Org-mode."
1598 :tag "Org Imenu and Speedbar"
1599 :group 'org-structure)
1601 (defcustom org-imenu-depth 2
1602 "The maximum level for Imenu access to Org-mode headlines.
1603 This also applied for speedbar access."
1604 :group 'org-imenu-and-speedbar
1605 :type 'integer)
1607 (defgroup org-table nil
1608 "Options concerning tables in Org-mode."
1609 :tag "Org Table"
1610 :group 'org)
1612 (defcustom org-enable-table-editor 'optimized
1613 "Non-nil means lines starting with \"|\" are handled by the table editor.
1614 When nil, such lines will be treated like ordinary lines.
1616 When equal to the symbol `optimized', the table editor will be optimized to
1617 do the following:
1618 - Automatic overwrite mode in front of whitespace in table fields.
1619 This makes the structure of the table stay in tact as long as the edited
1620 field does not exceed the column width.
1621 - Minimize the number of realigns. Normally, the table is aligned each time
1622 TAB or RET are pressed to move to another field. With optimization this
1623 happens only if changes to a field might have changed the column width.
1624 Optimization requires replacing the functions `self-insert-command',
1625 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1626 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1627 very good at guessing when a re-align will be necessary, but you can always
1628 force one with \\[org-ctrl-c-ctrl-c].
1630 If you would like to use the optimized version in Org-mode, but the
1631 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1633 This variable can be used to turn on and off the table editor during a session,
1634 but in order to toggle optimization, a restart is required.
1636 See also the variable `org-table-auto-blank-field'."
1637 :group 'org-table
1638 :type '(choice
1639 (const :tag "off" nil)
1640 (const :tag "on" t)
1641 (const :tag "on, optimized" optimized)))
1643 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1644 (version<= emacs-version "24.1"))
1645 "Non-nil means cluster self-insert commands for undo when possible.
1646 If this is set, then, like in the Emacs command loop, 20 consecutive
1647 characters will be undone together.
1648 This is configurable, because there is some impact on typing performance."
1649 :group 'org-table
1650 :type 'boolean)
1652 (defcustom org-table-tab-recognizes-table.el t
1653 "Non-nil means TAB will automatically notice a table.el table.
1654 When it sees such a table, it moves point into it and - if necessary -
1655 calls `table-recognize-table'."
1656 :group 'org-table-editing
1657 :type 'boolean)
1659 (defgroup org-link nil
1660 "Options concerning links in Org-mode."
1661 :tag "Org Link"
1662 :group 'org)
1664 (defvar org-link-abbrev-alist-local nil
1665 "Buffer-local version of `org-link-abbrev-alist', which see.
1666 The value of this is taken from the #+LINK lines.")
1667 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1669 (defcustom org-link-abbrev-alist nil
1670 "Alist of link abbreviations.
1671 The car of each element is a string, to be replaced at the start of a link.
1672 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1673 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1675 [[linkkey:tag][description]]
1677 The 'linkkey' must be a word word, starting with a letter, followed
1678 by letters, numbers, '-' or '_'.
1680 If REPLACE is a string, the tag will simply be appended to create the link.
1681 If the string contains \"%s\", the tag will be inserted there. If the string
1682 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1683 at that point (see the function `url-hexify-string'). If the string contains
1684 the specifier \"%(my-function)\", then the custom function `my-function' will
1685 be invoked: this function takes the tag as its only argument and must return
1686 a string.
1688 REPLACE may also be a function that will be called with the tag as the
1689 only argument to create the link, which should be returned as a string.
1691 See the manual for examples."
1692 :group 'org-link
1693 :type '(repeat
1694 (cons
1695 (string :tag "Protocol")
1696 (choice
1697 (string :tag "Format")
1698 (function)))))
1700 (defcustom org-descriptive-links t
1701 "Non-nil means Org will display descriptive links.
1702 E.g. [[http://orgmode.org][Org website]] will be displayed as
1703 \"Org Website\", hiding the link itself and just displaying its
1704 description. When set to `nil', Org will display the full links
1705 literally.
1707 You can interactively set the value of this variable by calling
1708 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1709 :group 'org-link
1710 :type 'boolean)
1712 (defcustom org-link-file-path-type 'adaptive
1713 "How the path name in file links should be stored.
1714 Valid values are:
1716 relative Relative to the current directory, i.e. the directory of the file
1717 into which the link is being inserted.
1718 absolute Absolute path, if possible with ~ for home directory.
1719 noabbrev Absolute path, no abbreviation of home directory.
1720 adaptive Use relative path for files in the current directory and sub-
1721 directories of it. For other files, use an absolute path."
1722 :group 'org-link
1723 :type '(choice
1724 (const relative)
1725 (const absolute)
1726 (const noabbrev)
1727 (const adaptive)))
1729 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1730 "Types of links that should be activated in Org-mode files.
1731 This is a list of symbols, each leading to the activation of a certain link
1732 type. In principle, it does not hurt to turn on most link types - there may
1733 be a small gain when turning off unused link types. The types are:
1735 bracket The recommended [[link][description]] or [[link]] links with hiding.
1736 angle Links in angular brackets that may contain whitespace like
1737 <bbdb:Carsten Dominik>.
1738 plain Plain links in normal text, no whitespace, like http://google.com.
1739 radio Text that is matched by a radio target, see manual for details.
1740 tag Tag settings in a headline (link to tag search).
1741 date Time stamps (link to calendar).
1742 footnote Footnote labels.
1744 Changing this variable requires a restart of Emacs to become effective."
1745 :group 'org-link
1746 :type '(set :greedy t
1747 (const :tag "Double bracket links" bracket)
1748 (const :tag "Angular bracket links" angle)
1749 (const :tag "Plain text links" plain)
1750 (const :tag "Radio target matches" radio)
1751 (const :tag "Tags" tag)
1752 (const :tag "Timestamps" date)
1753 (const :tag "Footnotes" footnote)))
1755 (defcustom org-make-link-description-function nil
1756 "Function to use for generating link descriptions from links.
1757 When nil, the link location will be used. This function must take
1758 two parameters: the first one is the link, the second one is the
1759 description generated by `org-insert-link'. The function should
1760 return the description to use."
1761 :group 'org-link
1762 :type '(choice (const nil) (function)))
1764 (defgroup org-link-store nil
1765 "Options concerning storing links in Org-mode."
1766 :tag "Org Store Link"
1767 :group 'org-link)
1769 (defcustom org-url-hexify-p t
1770 "When non-nil, hexify URL when creating a link."
1771 :type 'boolean
1772 :version "24.3"
1773 :group 'org-link-store)
1775 (defcustom org-email-link-description-format "Email %c: %.30s"
1776 "Format of the description part of a link to an email or usenet message.
1777 The following %-escapes will be replaced by corresponding information:
1779 %F full \"From\" field
1780 %f name, taken from \"From\" field, address if no name
1781 %T full \"To\" field
1782 %t first name in \"To\" field, address if no name
1783 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1784 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1785 %s subject
1786 %d date
1787 %m message-id.
1789 You may use normal field width specification between the % and the letter.
1790 This is for example useful to limit the length of the subject.
1792 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1793 :group 'org-link-store
1794 :type 'string)
1796 (defcustom org-from-is-user-regexp
1797 (let (r1 r2)
1798 (when (and user-mail-address (not (string= user-mail-address "")))
1799 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1800 (when (and user-full-name (not (string= user-full-name "")))
1801 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1802 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1803 "Regexp matched against the \"From:\" header of an email or usenet message.
1804 It should match if the message is from the user him/herself."
1805 :group 'org-link-store
1806 :type 'regexp)
1808 (defcustom org-context-in-file-links t
1809 "Non-nil means file links from `org-store-link' contain context.
1810 A search string will be added to the file name with :: as separator and
1811 used to find the context when the link is activated by the command
1812 `org-open-at-point'. When this option is t, the entire active region
1813 will be placed in the search string of the file link. If set to a
1814 positive integer, only the first n lines of context will be stored.
1816 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1817 negates this setting for the duration of the command."
1818 :group 'org-link-store
1819 :type '(choice boolean integer))
1821 (defcustom org-keep-stored-link-after-insertion nil
1822 "Non-nil means keep link in list for entire session.
1824 The command `org-store-link' adds a link pointing to the current
1825 location to an internal list. These links accumulate during a session.
1826 The command `org-insert-link' can be used to insert links into any
1827 Org-mode file (offering completion for all stored links). When this
1828 option is nil, every link which has been inserted once using \\[org-insert-link]
1829 will be removed from the list, to make completing the unused links
1830 more efficient."
1831 :group 'org-link-store
1832 :type 'boolean)
1834 (defgroup org-link-follow nil
1835 "Options concerning following links in Org-mode."
1836 :tag "Org Follow Link"
1837 :group 'org-link)
1839 (defcustom org-link-translation-function nil
1840 "Function to translate links with different syntax to Org syntax.
1841 This can be used to translate links created for example by the Planner
1842 or emacs-wiki packages to Org syntax.
1843 The function must accept two parameters, a TYPE containing the link
1844 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1845 which is everything after the link protocol. It should return a cons
1846 with possibly modified values of type and path.
1847 Org contains a function for this, so if you set this variable to
1848 `org-translate-link-from-planner', you should be able follow many
1849 links created by planner."
1850 :group 'org-link-follow
1851 :type '(choice (const nil) (function)))
1853 (defcustom org-follow-link-hook nil
1854 "Hook that is run after a link has been followed."
1855 :group 'org-link-follow
1856 :type 'hook)
1858 (defcustom org-tab-follows-link nil
1859 "Non-nil means on links TAB will follow the link.
1860 Needs to be set before org.el is loaded.
1861 This really should not be used, it does not make sense, and the
1862 implementation is bad."
1863 :group 'org-link-follow
1864 :type 'boolean)
1866 (defcustom org-return-follows-link nil
1867 "Non-nil means on links RET will follow the link.
1868 In tables, the special behavior of RET has precedence."
1869 :group 'org-link-follow
1870 :type 'boolean)
1872 (defcustom org-mouse-1-follows-link
1873 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1874 "Non-nil means mouse-1 on a link will follow the link.
1875 A longer mouse click will still set point. Does not work on XEmacs.
1876 Needs to be set before org.el is loaded."
1877 :group 'org-link-follow
1878 :version "24.4"
1879 :package-version '(Org . "8.3")
1880 :type '(choice
1881 (const :tag "A double click follows the link" double)
1882 (const :tag "Unconditionally follow the link with mouse-1" t)
1883 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
1885 (defcustom org-mark-ring-length 4
1886 "Number of different positions to be recorded in the ring.
1887 Changing this requires a restart of Emacs to work correctly."
1888 :group 'org-link-follow
1889 :type 'integer)
1891 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1892 "Non-nil means internal links in Org files must exactly match a headline.
1893 When nil, the link search tries to match a phrase with all words
1894 in the search text."
1895 :group 'org-link-follow
1896 :version "24.1"
1897 :type '(choice
1898 (const :tag "Use fuzzy text search" nil)
1899 (const :tag "Match only exact headline" t)
1900 (const :tag "Match exact headline or query to create it"
1901 query-to-create)))
1903 (defcustom org-link-frame-setup
1904 '((vm . vm-visit-folder-other-frame)
1905 (vm-imap . vm-visit-imap-folder-other-frame)
1906 (gnus . org-gnus-no-new-news)
1907 (file . find-file-other-window)
1908 (wl . wl-other-frame))
1909 "Setup the frame configuration for following links.
1910 When following a link with Emacs, it may often be useful to display
1911 this link in another window or frame. This variable can be used to
1912 set this up for the different types of links.
1913 For VM, use any of
1914 `vm-visit-folder'
1915 `vm-visit-folder-other-window'
1916 `vm-visit-folder-other-frame'
1917 For Gnus, use any of
1918 `gnus'
1919 `gnus-other-frame'
1920 `org-gnus-no-new-news'
1921 For FILE, use any of
1922 `find-file'
1923 `find-file-other-window'
1924 `find-file-other-frame'
1925 For Wanderlust use any of
1926 `wl'
1927 `wl-other-frame'
1928 For the calendar, use the variable `calendar-setup'.
1929 For BBDB, it is currently only possible to display the matches in
1930 another window."
1931 :group 'org-link-follow
1932 :type '(list
1933 (cons (const vm)
1934 (choice
1935 (const vm-visit-folder)
1936 (const vm-visit-folder-other-window)
1937 (const vm-visit-folder-other-frame)))
1938 (cons (const vm-imap)
1939 (choice
1940 (const vm-visit-imap-folder)
1941 (const vm-visit-imap-folder-other-window)
1942 (const vm-visit-imap-folder-other-frame)))
1943 (cons (const gnus)
1944 (choice
1945 (const gnus)
1946 (const gnus-other-frame)
1947 (const org-gnus-no-new-news)))
1948 (cons (const file)
1949 (choice
1950 (const find-file)
1951 (const find-file-other-window)
1952 (const find-file-other-frame)))
1953 (cons (const wl)
1954 (choice
1955 (const wl)
1956 (const wl-other-frame)))))
1958 (defcustom org-display-internal-link-with-indirect-buffer nil
1959 "Non-nil means use indirect buffer to display infile links.
1960 Activating internal links (from one location in a file to another location
1961 in the same file) normally just jumps to the location. When the link is
1962 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1963 is displayed in
1964 another window. When this option is set, the other window actually displays
1965 an indirect buffer clone of the current buffer, to avoid any visibility
1966 changes to the current buffer."
1967 :group 'org-link-follow
1968 :type 'boolean)
1970 (defcustom org-open-non-existing-files nil
1971 "Non-nil means `org-open-file' will open non-existing files.
1972 When nil, an error will be generated.
1973 This variable applies only to external applications because they
1974 might choke on non-existing files. If the link is to a file that
1975 will be opened in Emacs, the variable is ignored."
1976 :group 'org-link-follow
1977 :type 'boolean)
1979 (defcustom org-open-directory-means-index-dot-org nil
1980 "Non-nil means a link to a directory really means to index.org.
1981 When nil, following a directory link will run dired or open a finder/explorer
1982 window on that directory."
1983 :group 'org-link-follow
1984 :type 'boolean)
1986 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1987 "Function and arguments to call for following mailto links.
1988 This is a list with the first element being a Lisp function, and the
1989 remaining elements being arguments to the function. In string arguments,
1990 %a will be replaced by the address, and %s will be replaced by the subject
1991 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1992 :group 'org-link-follow
1993 :type '(choice
1994 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1995 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1996 (const :tag "message-mail" (message-mail "%a" "%s"))
1997 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1999 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2000 "Non-nil means ask for confirmation before executing shell links.
2001 Shell links can be dangerous: just think about a link
2003 [[shell:rm -rf ~/*][Google Search]]
2005 This link would show up in your Org-mode document as \"Google Search\",
2006 but really it would remove your entire home directory.
2007 Therefore we advise against setting this variable to nil.
2008 Just change it to `y-or-n-p' if you want to confirm with a
2009 single keystroke rather than having to type \"yes\"."
2010 :group 'org-link-follow
2011 :type '(choice
2012 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2013 (const :tag "with y-or-n (faster)" y-or-n-p)
2014 (const :tag "no confirmation (dangerous)" nil)))
2015 (put 'org-confirm-shell-link-function
2016 'safe-local-variable
2017 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2019 (defcustom org-confirm-shell-link-not-regexp ""
2020 "A regexp to skip confirmation for shell links."
2021 :group 'org-link-follow
2022 :version "24.1"
2023 :type 'regexp)
2025 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2026 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2027 Elisp links can be dangerous: just think about a link
2029 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2031 This link would show up in your Org-mode document as \"Google Search\",
2032 but really it would remove your entire home directory.
2033 Therefore we advise against setting this variable to nil.
2034 Just change it to `y-or-n-p' if you want to confirm with a
2035 single keystroke rather than having to type \"yes\"."
2036 :group 'org-link-follow
2037 :type '(choice
2038 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2039 (const :tag "with y-or-n (faster)" y-or-n-p)
2040 (const :tag "no confirmation (dangerous)" nil)))
2041 (put 'org-confirm-shell-link-function
2042 'safe-local-variable
2043 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2045 (defcustom org-confirm-elisp-link-not-regexp ""
2046 "A regexp to skip confirmation for Elisp links."
2047 :group 'org-link-follow
2048 :version "24.1"
2049 :type 'regexp)
2051 (defconst org-file-apps-defaults-gnu
2052 '((remote . emacs)
2053 (system . mailcap)
2054 (t . mailcap))
2055 "Default file applications on a UNIX or GNU/Linux system.
2056 See `org-file-apps'.")
2058 (defconst org-file-apps-defaults-macosx
2059 '((remote . emacs)
2060 (t . "open %s")
2061 (system . "open %s")
2062 ("ps.gz" . "gv %s")
2063 ("eps.gz" . "gv %s")
2064 ("dvi" . "xdvi %s")
2065 ("fig" . "xfig %s"))
2066 "Default file applications on a MacOS X system.
2067 The system \"open\" is known as a default, but we use X11 applications
2068 for some files for which the OS does not have a good default.
2069 See `org-file-apps'.")
2071 (defconst org-file-apps-defaults-windowsnt
2072 (list
2073 '(remote . emacs)
2074 (cons t
2075 (list (if (featurep 'xemacs)
2076 'mswindows-shell-execute
2077 'w32-shell-execute)
2078 "open" 'file))
2079 (cons 'system
2080 (list (if (featurep 'xemacs)
2081 'mswindows-shell-execute
2082 'w32-shell-execute)
2083 "open" 'file)))
2084 "Default file applications on a Windows NT system.
2085 The system \"open\" is used for most files.
2086 See `org-file-apps'.")
2088 (defcustom org-file-apps
2089 '((auto-mode . emacs)
2090 ("\\.mm\\'" . default)
2091 ("\\.x?html?\\'" . default)
2092 ("\\.pdf\\'" . default))
2093 "External applications for opening `file:path' items in a document.
2094 Org-mode uses system defaults for different file types, but
2095 you can use this variable to set the application for a given file
2096 extension. The entries in this list are cons cells where the car identifies
2097 files and the cdr the corresponding command. Possible values for the
2098 file identifier are
2099 \"string\" A string as a file identifier can be interpreted in different
2100 ways, depending on its contents:
2102 - Alphanumeric characters only:
2103 Match links with this file extension.
2104 Example: (\"pdf\" . \"evince %s\")
2105 to open PDFs with evince.
2107 - Regular expression: Match links where the
2108 filename matches the regexp. If you want to
2109 use groups here, use shy groups.
2111 Example: (\"\\.x?html\\'\" . \"firefox %s\")
2112 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
2113 to open *.html and *.xhtml with firefox.
2115 - Regular expression which contains (non-shy) groups:
2116 Match links where the whole link, including \"::\", and
2117 anything after that, matches the regexp.
2118 In a custom command string, %1, %2, etc. are replaced with
2119 the parts of the link that were matched by the groups.
2120 For backwards compatibility, if a command string is given
2121 that does not use any of the group matches, this case is
2122 handled identically to the second one (i.e. match against
2123 file name only).
2124 In a custom lisp form, you can access the group matches with
2125 (match-string n link).
2127 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
2128 to open [[file:document.pdf::5]] with evince at page 5.
2130 `directory' Matches a directory
2131 `remote' Matches a remote file, accessible through tramp or efs.
2132 Remote files most likely should be visited through Emacs
2133 because external applications cannot handle such paths.
2134 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2135 so all files Emacs knows how to handle. Using this with
2136 command `emacs' will open most files in Emacs. Beware that this
2137 will also open html files inside Emacs, unless you add
2138 (\"html\" . default) to the list as well.
2139 t Default for files not matched by any of the other options.
2140 `system' The system command to open files, like `open' on Windows
2141 and Mac OS X, and mailcap under GNU/Linux. This is the command
2142 that will be selected if you call `C-c C-o' with a double
2143 \\[universal-argument] \\[universal-argument] prefix.
2145 Possible values for the command are:
2146 `emacs' The file will be visited by the current Emacs process.
2147 `default' Use the default application for this file type, which is the
2148 association for t in the list, most likely in the system-specific
2149 part.
2150 This can be used to overrule an unwanted setting in the
2151 system-specific variable.
2152 `system' Use the system command for opening files, like \"open\".
2153 This command is specified by the entry whose car is `system'.
2154 Most likely, the system-specific version of this variable
2155 does define this command, but you can overrule/replace it
2156 here.
2157 string A command to be executed by a shell; %s will be replaced
2158 by the path to the file.
2159 sexp A Lisp form which will be evaluated. The file path will
2160 be available in the Lisp variable `file'.
2161 For more examples, see the system specific constants
2162 `org-file-apps-defaults-macosx'
2163 `org-file-apps-defaults-windowsnt'
2164 `org-file-apps-defaults-gnu'."
2165 :group 'org-link-follow
2166 :type '(repeat
2167 (cons (choice :value ""
2168 (string :tag "Extension")
2169 (const :tag "System command to open files" system)
2170 (const :tag "Default for unrecognized files" t)
2171 (const :tag "Remote file" remote)
2172 (const :tag "Links to a directory" directory)
2173 (const :tag "Any files that have Emacs modes"
2174 auto-mode))
2175 (choice :value ""
2176 (const :tag "Visit with Emacs" emacs)
2177 (const :tag "Use default" default)
2178 (const :tag "Use the system command" system)
2179 (string :tag "Command")
2180 (sexp :tag "Lisp form")))))
2182 (defcustom org-doi-server-url "http://dx.doi.org/"
2183 "The URL of the DOI server."
2184 :type 'string
2185 :version "24.3"
2186 :group 'org-link-follow)
2188 (defgroup org-refile nil
2189 "Options concerning refiling entries in Org-mode."
2190 :tag "Org Refile"
2191 :group 'org)
2193 (defcustom org-directory "~/org"
2194 "Directory with org files.
2195 This is just a default location to look for Org files. There is no need
2196 at all to put your files into this directory. It is only used in the
2197 following situations:
2199 1. When a capture template specifies a target file that is not an
2200 absolute path. The path will then be interpreted relative to
2201 `org-directory'
2202 2. When a capture note is filed away in an interactive way (when exiting the
2203 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2204 with `org-directory' as the default path."
2205 :group 'org-refile
2206 :group 'org-capture
2207 :type 'directory)
2209 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2210 "Default target for storing notes.
2211 Used as a fall back file for org-capture.el, for templates that
2212 do not specify a target file."
2213 :group 'org-refile
2214 :group 'org-capture
2215 :type '(choice
2216 (const :tag "Default from remember-data-file" nil)
2217 file))
2219 (defcustom org-goto-interface 'outline
2220 "The default interface to be used for `org-goto'.
2221 Allowed values are:
2222 outline The interface shows an outline of the relevant file
2223 and the correct heading is found by moving through
2224 the outline or by searching with incremental search.
2225 outline-path-completion Headlines in the current buffer are offered via
2226 completion. This is the interface also used by
2227 the refile command."
2228 :group 'org-refile
2229 :type '(choice
2230 (const :tag "Outline" outline)
2231 (const :tag "Outline-path-completion" outline-path-completion)))
2233 (defcustom org-goto-max-level 5
2234 "Maximum target level when running `org-goto' with refile interface."
2235 :group 'org-refile
2236 :type 'integer)
2238 (defcustom org-reverse-note-order nil
2239 "Non-nil means store new notes at the beginning of a file or entry.
2240 When nil, new notes will be filed to the end of a file or entry.
2241 This can also be a list with cons cells of regular expressions that
2242 are matched against file names, and values."
2243 :group 'org-capture
2244 :group 'org-refile
2245 :type '(choice
2246 (const :tag "Reverse always" t)
2247 (const :tag "Reverse never" nil)
2248 (repeat :tag "By file name regexp"
2249 (cons regexp boolean))))
2251 (defcustom org-log-refile nil
2252 "Information to record when a task is refiled.
2254 Possible values are:
2256 nil Don't add anything
2257 time Add a time stamp to the task
2258 note Prompt for a note and add it with template `org-log-note-headings'
2260 This option can also be set with on a per-file-basis with
2262 #+STARTUP: nologrefile
2263 #+STARTUP: logrefile
2264 #+STARTUP: lognoterefile
2266 You can have local logging settings for a subtree by setting the LOGGING
2267 property to one or more of these keywords.
2269 When bulk-refiling from the agenda, the value `note' is forbidden and
2270 will temporarily be changed to `time'."
2271 :group 'org-refile
2272 :group 'org-progress
2273 :version "24.1"
2274 :type '(choice
2275 (const :tag "No logging" nil)
2276 (const :tag "Record timestamp" time)
2277 (const :tag "Record timestamp with note." note)))
2279 (defcustom org-refile-targets nil
2280 "Targets for refiling entries with \\[org-refile].
2281 This is a list of cons cells. Each cell contains:
2282 - a specification of the files to be considered, either a list of files,
2283 or a symbol whose function or variable value will be used to retrieve
2284 a file name or a list of file names. If you use `org-agenda-files' for
2285 that, all agenda files will be scanned for targets. Nil means consider
2286 headings in the current buffer.
2287 - A specification of how to find candidate refile targets. This may be
2288 any of:
2289 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2290 This tag has to be present in all target headlines, inheritance will
2291 not be considered.
2292 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2293 todo keyword.
2294 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2295 headlines that are refiling targets.
2296 - a cons cell (:level . N). Any headline of level N is considered a target.
2297 Note that, when `org-odd-levels-only' is set, level corresponds to
2298 order in hierarchy, not to the number of stars.
2299 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2300 Note that, when `org-odd-levels-only' is set, level corresponds to
2301 order in hierarchy, not to the number of stars.
2303 Each element of this list generates a set of possible targets.
2304 The union of these sets is presented (with completion) to
2305 the user by `org-refile'.
2307 You can set the variable `org-refile-target-verify-function' to a function
2308 to verify each headline found by the simple criteria above.
2310 When this variable is nil, all top-level headlines in the current buffer
2311 are used, equivalent to the value `((nil . (:level . 1))'."
2312 :group 'org-refile
2313 :type '(repeat
2314 (cons
2315 (choice :value org-agenda-files
2316 (const :tag "All agenda files" org-agenda-files)
2317 (const :tag "Current buffer" nil)
2318 (function) (variable) (file))
2319 (choice :tag "Identify target headline by"
2320 (cons :tag "Specific tag" (const :value :tag) (string))
2321 (cons :tag "TODO keyword" (const :value :todo) (string))
2322 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2323 (cons :tag "Level number" (const :value :level) (integer))
2324 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2326 (defcustom org-refile-target-verify-function nil
2327 "Function to verify if the headline at point should be a refile target.
2328 The function will be called without arguments, with point at the
2329 beginning of the headline. It should return t and leave point
2330 where it is if the headline is a valid target for refiling.
2332 If the target should not be selected, the function must return nil.
2333 In addition to this, it may move point to a place from where the search
2334 should be continued. For example, the function may decide that the entire
2335 subtree of the current entry should be excluded and move point to the end
2336 of the subtree."
2337 :group 'org-refile
2338 :type '(choice
2339 (const nil)
2340 (function)))
2342 (defcustom org-refile-use-cache nil
2343 "Non-nil means cache refile targets to speed up the process.
2344 The cache for a particular file will be updated automatically when
2345 the buffer has been killed, or when any of the marker used for flagging
2346 refile targets no longer points at a live buffer.
2347 If you have added new entries to a buffer that might themselves be targets,
2348 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2349 find that easier, `C-u C-u C-u C-c C-w'."
2350 :group 'org-refile
2351 :version "24.1"
2352 :type 'boolean)
2354 (defcustom org-refile-use-outline-path nil
2355 "Non-nil means provide refile targets as paths.
2356 So a level 3 headline will be available as level1/level2/level3.
2358 When the value is `file', also include the file name (without directory)
2359 into the path. In this case, you can also stop the completion after
2360 the file name, to get entries inserted as top level in the file.
2362 When `full-file-path', include the full file path."
2363 :group 'org-refile
2364 :type '(choice
2365 (const :tag "Not" nil)
2366 (const :tag "Yes" t)
2367 (const :tag "Start with file name" file)
2368 (const :tag "Start with full file path" full-file-path)))
2370 (defcustom org-outline-path-complete-in-steps t
2371 "Non-nil means complete the outline path in hierarchical steps.
2372 When Org-mode uses the refile interface to select an outline path
2373 \(see variable `org-refile-use-outline-path'), the completion of
2374 the path can be done is a single go, or if can be done in steps down
2375 the headline hierarchy. Going in steps is probably the best if you
2376 do not use a special completion package like `ido' or `icicles'.
2377 However, when using these packages, going in one step can be very
2378 fast, while still showing the whole path to the entry."
2379 :group 'org-refile
2380 :type 'boolean)
2382 (defcustom org-refile-allow-creating-parent-nodes nil
2383 "Non-nil means allow to create new nodes as refile targets.
2384 New nodes are then created by adding \"/new node name\" to the completion
2385 of an existing node. When the value of this variable is `confirm',
2386 new node creation must be confirmed by the user (recommended).
2387 When nil, the completion must match an existing entry.
2389 Note that, if the new heading is not seen by the criteria
2390 listed in `org-refile-targets', multiple instances of the same
2391 heading would be created by trying again to file under the new
2392 heading."
2393 :group 'org-refile
2394 :type '(choice
2395 (const :tag "Never" nil)
2396 (const :tag "Always" t)
2397 (const :tag "Prompt for confirmation" confirm)))
2399 (defcustom org-refile-active-region-within-subtree nil
2400 "Non-nil means also refile active region within a subtree.
2402 By default `org-refile' doesn't allow refiling regions if they
2403 don't contain a set of subtrees, but it might be convenient to
2404 do so sometimes: in that case, the first line of the region is
2405 converted to a headline before refiling."
2406 :group 'org-refile
2407 :version "24.1"
2408 :type 'boolean)
2410 (defgroup org-todo nil
2411 "Options concerning TODO items in Org-mode."
2412 :tag "Org TODO"
2413 :group 'org)
2415 (defgroup org-progress nil
2416 "Options concerning Progress logging in Org-mode."
2417 :tag "Org Progress"
2418 :group 'org-time)
2420 (defvar org-todo-interpretation-widgets
2421 '((:tag "Sequence (cycling hits every state)" sequence)
2422 (:tag "Type (cycling directly to DONE)" type))
2423 "The available interpretation symbols for customizing `org-todo-keywords'.
2424 Interested libraries should add to this list.")
2426 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2427 "List of TODO entry keyword sequences and their interpretation.
2428 \\<org-mode-map>This is a list of sequences.
2430 Each sequence starts with a symbol, either `sequence' or `type',
2431 indicating if the keywords should be interpreted as a sequence of
2432 action steps, or as different types of TODO items. The first
2433 keywords are states requiring action - these states will select a headline
2434 for inclusion into the global TODO list Org-mode produces. If one of
2435 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2436 signify that no further action is necessary. If \"|\" is not found,
2437 the last keyword is treated as the only DONE state of the sequence.
2439 The command \\[org-todo] cycles an entry through these states, and one
2440 additional state where no keyword is present. For details about this
2441 cycling, see the manual.
2443 TODO keywords and interpretation can also be set on a per-file basis with
2444 the special #+SEQ_TODO and #+TYP_TODO lines.
2446 Each keyword can optionally specify a character for fast state selection
2447 \(in combination with the variable `org-use-fast-todo-selection')
2448 and specifiers for state change logging, using the same syntax that
2449 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2450 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2451 indicates to record a time stamp each time this state is selected.
2453 Each keyword may also specify if a timestamp or a note should be
2454 recorded when entering or leaving the state, by adding additional
2455 characters in the parenthesis after the keyword. This looks like this:
2456 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2457 record only the time of the state change. With X and Y being either
2458 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2459 Y when leaving the state if and only if the *target* state does not
2460 define X. You may omit any of the fast-selection key or X or /Y,
2461 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2463 For backward compatibility, this variable may also be just a list
2464 of keywords. In this case the interpretation (sequence or type) will be
2465 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2466 :group 'org-todo
2467 :group 'org-keywords
2468 :type '(choice
2469 (repeat :tag "Old syntax, just keywords"
2470 (string :tag "Keyword"))
2471 (repeat :tag "New syntax"
2472 (cons
2473 (choice
2474 :tag "Interpretation"
2475 ;;Quick and dirty way to see
2476 ;;`org-todo-interpretations'. This takes the
2477 ;;place of item arguments
2478 :convert-widget
2479 (lambda (widget)
2480 (widget-put widget
2481 :args (mapcar
2482 #'(lambda (x)
2483 (widget-convert
2484 (cons 'const x)))
2485 org-todo-interpretation-widgets))
2486 widget))
2487 (repeat
2488 (string :tag "Keyword"))))))
2490 (defvar org-todo-keywords-1 nil
2491 "All TODO and DONE keywords active in a buffer.")
2492 (make-variable-buffer-local 'org-todo-keywords-1)
2493 (defvar org-todo-keywords-for-agenda nil)
2494 (defvar org-done-keywords-for-agenda nil)
2495 (defvar org-todo-keyword-alist-for-agenda nil)
2496 (defvar org-tag-alist-for-agenda nil
2497 "Alist of all tags from all agenda files.")
2498 (defvar org-tag-groups-alist-for-agenda nil
2499 "Alist of all groups tags from all current agenda files.")
2500 (defvar org-tag-groups-alist nil)
2501 (make-variable-buffer-local 'org-tag-groups-alist)
2502 (defvar org-agenda-contributing-files nil)
2503 (defvar org-not-done-keywords nil)
2504 (make-variable-buffer-local 'org-not-done-keywords)
2505 (defvar org-done-keywords nil)
2506 (make-variable-buffer-local 'org-done-keywords)
2507 (defvar org-todo-heads nil)
2508 (make-variable-buffer-local 'org-todo-heads)
2509 (defvar org-todo-sets nil)
2510 (make-variable-buffer-local 'org-todo-sets)
2511 (defvar org-todo-log-states nil)
2512 (make-variable-buffer-local 'org-todo-log-states)
2513 (defvar org-todo-kwd-alist nil)
2514 (make-variable-buffer-local 'org-todo-kwd-alist)
2515 (defvar org-todo-key-alist nil)
2516 (make-variable-buffer-local 'org-todo-key-alist)
2517 (defvar org-todo-key-trigger nil)
2518 (make-variable-buffer-local 'org-todo-key-trigger)
2520 (defcustom org-todo-interpretation 'sequence
2521 "Controls how TODO keywords are interpreted.
2522 This variable is in principle obsolete and is only used for
2523 backward compatibility, if the interpretation of todo keywords is
2524 not given already in `org-todo-keywords'. See that variable for
2525 more information."
2526 :group 'org-todo
2527 :group 'org-keywords
2528 :type '(choice (const sequence)
2529 (const type)))
2531 (defcustom org-use-fast-todo-selection t
2532 "Non-nil means use the fast todo selection scheme with C-c C-t.
2533 This variable describes if and under what circumstances the cycling
2534 mechanism for TODO keywords will be replaced by a single-key, direct
2535 selection scheme.
2537 When nil, fast selection is never used.
2539 When the symbol `prefix', it will be used when `org-todo' is called
2540 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2541 `C-u t' in an agenda buffer.
2543 When t, fast selection is used by default. In this case, the prefix
2544 argument forces cycling instead.
2546 In all cases, the special interface is only used if access keys have
2547 actually been assigned by the user, i.e. if keywords in the configuration
2548 are followed by a letter in parenthesis, like TODO(t)."
2549 :group 'org-todo
2550 :type '(choice
2551 (const :tag "Never" nil)
2552 (const :tag "By default" t)
2553 (const :tag "Only with C-u C-c C-t" prefix)))
2555 (defcustom org-provide-todo-statistics t
2556 "Non-nil means update todo statistics after insert and toggle.
2557 ALL-HEADLINES means update todo statistics by including headlines
2558 with no TODO keyword as well, counting them as not done.
2559 A list of TODO keywords means the same, but skip keywords that are
2560 not in this list.
2561 When set to a list of two lists, the first list contains keywords
2562 to consider as TODO keywords, the second list contains keywords
2563 to consider as DONE keywords.
2565 When this is set, todo statistics is updated in the parent of the
2566 current entry each time a todo state is changed."
2567 :group 'org-todo
2568 :type '(choice
2569 (const :tag "Yes, only for TODO entries" t)
2570 (const :tag "Yes, including all entries" all-headlines)
2571 (repeat :tag "Yes, for TODOs in this list"
2572 (string :tag "TODO keyword"))
2573 (list :tag "Yes, for TODOs and DONEs in these lists"
2574 (repeat (string :tag "TODO keyword"))
2575 (repeat (string :tag "DONE keyword")))
2576 (other :tag "No TODO statistics" nil)))
2578 (defcustom org-hierarchical-todo-statistics t
2579 "Non-nil means TODO statistics covers just direct children.
2580 When nil, all entries in the subtree are considered.
2581 This has only an effect if `org-provide-todo-statistics' is set.
2582 To set this to nil for only a single subtree, use a COOKIE_DATA
2583 property and include the word \"recursive\" into the value."
2584 :group 'org-todo
2585 :type 'boolean)
2587 (defcustom org-after-todo-state-change-hook nil
2588 "Hook which is run after the state of a TODO item was changed.
2589 The new state (a string with a TODO keyword, or nil) is available in the
2590 Lisp variable `org-state'."
2591 :group 'org-todo
2592 :type 'hook)
2594 (defvar org-blocker-hook nil
2595 "Hook for functions that are allowed to block a state change.
2597 Functions in this hook should not modify the buffer.
2598 Each function gets as its single argument a property list,
2599 see `org-trigger-hook' for more information about this list.
2601 If any of the functions in this hook returns nil, the state change
2602 is blocked.")
2604 (defvar org-trigger-hook nil
2605 "Hook for functions that are triggered by a state change.
2607 Each function gets as its single argument a property list with at
2608 least the following elements:
2610 (:type type-of-change :position pos-at-entry-start
2611 :from old-state :to new-state)
2613 Depending on the type, more properties may be present.
2615 This mechanism is currently implemented for:
2617 TODO state changes
2618 ------------------
2619 :type todo-state-change
2620 :from previous state (keyword as a string), or nil, or a symbol
2621 'todo' or 'done', to indicate the general type of state.
2622 :to new state, like in :from")
2624 (defcustom org-enforce-todo-dependencies nil
2625 "Non-nil means undone TODO entries will block switching the parent to DONE.
2626 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2627 be blocked if any prior sibling is not yet done.
2628 Finally, if the parent is blocked because of ordered siblings of its own,
2629 the child will also be blocked."
2630 :set (lambda (var val)
2631 (set var val)
2632 (if val
2633 (add-hook 'org-blocker-hook
2634 'org-block-todo-from-children-or-siblings-or-parent)
2635 (remove-hook 'org-blocker-hook
2636 'org-block-todo-from-children-or-siblings-or-parent)))
2637 :group 'org-todo
2638 :type 'boolean)
2640 (defcustom org-enforce-todo-checkbox-dependencies nil
2641 "Non-nil means unchecked boxes will block switching the parent to DONE.
2642 When this is nil, checkboxes have no influence on switching TODO states.
2643 When non-nil, you first need to check off all check boxes before the TODO
2644 entry can be switched to DONE.
2645 This variable needs to be set before org.el is loaded, and you need to
2646 restart Emacs after a change to make the change effective. The only way
2647 to change is while Emacs is running is through the customize interface."
2648 :set (lambda (var val)
2649 (set var val)
2650 (if val
2651 (add-hook 'org-blocker-hook
2652 'org-block-todo-from-checkboxes)
2653 (remove-hook 'org-blocker-hook
2654 'org-block-todo-from-checkboxes)))
2655 :group 'org-todo
2656 :type 'boolean)
2658 (defcustom org-treat-insert-todo-heading-as-state-change nil
2659 "Non-nil means inserting a TODO heading is treated as state change.
2660 So when the command \\[org-insert-todo-heading] is used, state change
2661 logging will apply if appropriate. When nil, the new TODO item will
2662 be inserted directly, and no logging will take place."
2663 :group 'org-todo
2664 :type 'boolean)
2666 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2667 "Non-nil means switching TODO states with S-cursor counts as state change.
2668 This is the default behavior. However, setting this to nil allows a
2669 convenient way to select a TODO state and bypass any logging associated
2670 with that."
2671 :group 'org-todo
2672 :type 'boolean)
2674 (defcustom org-todo-state-tags-triggers nil
2675 "Tag changes that should be triggered by TODO state changes.
2676 This is a list. Each entry is
2678 (state-change (tag . flag) .......)
2680 State-change can be a string with a state, and empty string to indicate the
2681 state that has no TODO keyword, or it can be one of the symbols `todo'
2682 or `done', meaning any not-done or done state, respectively."
2683 :group 'org-todo
2684 :group 'org-tags
2685 :type '(repeat
2686 (cons (choice :tag "When changing to"
2687 (const :tag "Not-done state" todo)
2688 (const :tag "Done state" done)
2689 (string :tag "State"))
2690 (repeat
2691 (cons :tag "Tag action"
2692 (string :tag "Tag")
2693 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2695 (defcustom org-log-done nil
2696 "Information to record when a task moves to the DONE state.
2698 Possible values are:
2700 nil Don't add anything, just change the keyword
2701 time Add a time stamp to the task
2702 note Prompt for a note and add it with template `org-log-note-headings'
2704 This option can also be set with on a per-file-basis with
2706 #+STARTUP: nologdone
2707 #+STARTUP: logdone
2708 #+STARTUP: lognotedone
2710 You can have local logging settings for a subtree by setting the LOGGING
2711 property to one or more of these keywords."
2712 :group 'org-todo
2713 :group 'org-progress
2714 :type '(choice
2715 (const :tag "No logging" nil)
2716 (const :tag "Record CLOSED timestamp" time)
2717 (const :tag "Record CLOSED timestamp with note." note)))
2719 ;; Normalize old uses of org-log-done.
2720 (cond
2721 ((eq org-log-done t) (setq org-log-done 'time))
2722 ((and (listp org-log-done) (memq 'done org-log-done))
2723 (setq org-log-done 'note)))
2725 (defcustom org-log-reschedule nil
2726 "Information to record when the scheduling date of a tasks is modified.
2728 Possible values are:
2730 nil Don't add anything, just change the date
2731 time Add a time stamp to the task
2732 note Prompt for a note and add it with template `org-log-note-headings'
2734 This option can also be set with on a per-file-basis with
2736 #+STARTUP: nologreschedule
2737 #+STARTUP: logreschedule
2738 #+STARTUP: lognotereschedule"
2739 :group 'org-todo
2740 :group 'org-progress
2741 :type '(choice
2742 (const :tag "No logging" nil)
2743 (const :tag "Record timestamp" time)
2744 (const :tag "Record timestamp with note." note)))
2746 (defcustom org-log-redeadline nil
2747 "Information to record when the deadline date of a tasks is modified.
2749 Possible values are:
2751 nil Don't add anything, just change the date
2752 time Add a time stamp to the task
2753 note Prompt for a note and add it with template `org-log-note-headings'
2755 This option can also be set with on a per-file-basis with
2757 #+STARTUP: nologredeadline
2758 #+STARTUP: logredeadline
2759 #+STARTUP: lognoteredeadline
2761 You can have local logging settings for a subtree by setting the LOGGING
2762 property to one or more of these keywords."
2763 :group 'org-todo
2764 :group 'org-progress
2765 :type '(choice
2766 (const :tag "No logging" nil)
2767 (const :tag "Record timestamp" time)
2768 (const :tag "Record timestamp with note." note)))
2770 (defcustom org-log-note-clock-out nil
2771 "Non-nil means record a note when clocking out of an item.
2772 This can also be configured on a per-file basis by adding one of
2773 the following lines anywhere in the buffer:
2775 #+STARTUP: lognoteclock-out
2776 #+STARTUP: nolognoteclock-out"
2777 :group 'org-todo
2778 :group 'org-progress
2779 :type 'boolean)
2781 (defcustom org-log-done-with-time t
2782 "Non-nil means the CLOSED time stamp will contain date and time.
2783 When nil, only the date will be recorded."
2784 :group 'org-progress
2785 :type 'boolean)
2787 (defcustom org-log-note-headings
2788 '((done . "CLOSING NOTE %t")
2789 (state . "State %-12s from %-12S %t")
2790 (note . "Note taken on %t")
2791 (reschedule . "Rescheduled from %S on %t")
2792 (delschedule . "Not scheduled, was %S on %t")
2793 (redeadline . "New deadline from %S on %t")
2794 (deldeadline . "Removed deadline, was %S on %t")
2795 (refile . "Refiled on %t")
2796 (clock-out . ""))
2797 "Headings for notes added to entries.
2798 The value is an alist, with the car being a symbol indicating the note
2799 context, and the cdr is the heading to be used. The heading may also be the
2800 empty string.
2801 %t in the heading will be replaced by a time stamp.
2802 %T will be an active time stamp instead the default inactive one
2803 %d will be replaced by a short-format time stamp.
2804 %D will be replaced by an active short-format time stamp.
2805 %s will be replaced by the new TODO state, in double quotes.
2806 %S will be replaced by the old TODO state, in double quotes.
2807 %u will be replaced by the user name.
2808 %U will be replaced by the full user name.
2810 In fact, it is not a good idea to change the `state' entry, because
2811 agenda log mode depends on the format of these entries."
2812 :group 'org-todo
2813 :group 'org-progress
2814 :type '(list :greedy t
2815 (cons (const :tag "Heading when closing an item" done) string)
2816 (cons (const :tag
2817 "Heading when changing todo state (todo sequence only)"
2818 state) string)
2819 (cons (const :tag "Heading when just taking a note" note) string)
2820 (cons (const :tag "Heading when rescheduling" reschedule) string)
2821 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2822 (cons (const :tag "Heading when changing deadline" redeadline) string)
2823 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2824 (cons (const :tag "Heading when refiling" refile) string)
2825 (cons (const :tag "Heading when clocking out" clock-out) string)))
2827 (unless (assq 'note org-log-note-headings)
2828 (push '(note . "%t") org-log-note-headings))
2830 (defcustom org-log-into-drawer nil
2831 "Non-nil means insert state change notes and time stamps into a drawer.
2832 When nil, state changes notes will be inserted after the headline and
2833 any scheduling and clock lines, but not inside a drawer.
2835 The value of this variable should be the name of the drawer to use.
2836 LOGBOOK is proposed as the default drawer for this purpose, you can
2837 also set this to a string to define the drawer of your choice.
2839 A value of t is also allowed, representing \"LOGBOOK\".
2841 A value of t or nil can also be set with on a per-file-basis with
2843 #+STARTUP: logdrawer
2844 #+STARTUP: nologdrawer
2846 If this variable is set, `org-log-state-notes-insert-after-drawers'
2847 will be ignored.
2849 You can set the property LOG_INTO_DRAWER to overrule this setting for
2850 a subtree."
2851 :group 'org-todo
2852 :group 'org-progress
2853 :type '(choice
2854 (const :tag "Not into a drawer" nil)
2855 (const :tag "LOGBOOK" t)
2856 (string :tag "Other")))
2858 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2860 (defun org-log-into-drawer ()
2861 "Return the value of `org-log-into-drawer', but let properties overrule.
2862 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2863 used instead of the default value."
2864 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2865 (cond
2866 ((not p) org-log-into-drawer)
2867 ((equal p "nil") nil)
2868 ((equal p "t") "LOGBOOK")
2869 (t p))))
2871 (defcustom org-log-state-notes-insert-after-drawers nil
2872 "Non-nil means insert state change notes after any drawers in entry.
2873 Only the drawers that *immediately* follow the headline and the
2874 deadline/scheduled line are skipped.
2875 When nil, insert notes right after the heading and perhaps the line
2876 with deadline/scheduling if present.
2878 This variable will have no effect if `org-log-into-drawer' is
2879 set."
2880 :group 'org-todo
2881 :group 'org-progress
2882 :type 'boolean)
2884 (defcustom org-log-states-order-reversed t
2885 "Non-nil means the latest state note will be directly after heading.
2886 When nil, the state change notes will be ordered according to time.
2888 This option can also be set with on a per-file-basis with
2890 #+STARTUP: logstatesreversed
2891 #+STARTUP: nologstatesreversed"
2892 :group 'org-todo
2893 :group 'org-progress
2894 :type 'boolean)
2896 (defcustom org-todo-repeat-to-state nil
2897 "The TODO state to which a repeater should return the repeating task.
2898 By default this is the first task in a TODO sequence, or the previous state
2899 in a TODO_TYP set. But you can specify another task here.
2900 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2901 :group 'org-todo
2902 :version "24.1"
2903 :type '(choice (const :tag "Head of sequence" nil)
2904 (string :tag "Specific state")))
2906 (defcustom org-log-repeat 'time
2907 "Non-nil means record moving through the DONE state when triggering repeat.
2908 An auto-repeating task is immediately switched back to TODO when
2909 marked DONE. If you are not logging state changes (by adding \"@\"
2910 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2911 record a closing note, there will be no record of the task moving
2912 through DONE. This variable forces taking a note anyway.
2914 nil Don't force a record
2915 time Record a time stamp
2916 note Prompt for a note and add it with template `org-log-note-headings'
2918 This option can also be set with on a per-file-basis with
2920 #+STARTUP: nologrepeat
2921 #+STARTUP: logrepeat
2922 #+STARTUP: lognoterepeat
2924 You can have local logging settings for a subtree by setting the LOGGING
2925 property to one or more of these keywords."
2926 :group 'org-todo
2927 :group 'org-progress
2928 :type '(choice
2929 (const :tag "Don't force a record" nil)
2930 (const :tag "Force recording the DONE state" time)
2931 (const :tag "Force recording a note with the DONE state" note)))
2934 (defgroup org-priorities nil
2935 "Priorities in Org-mode."
2936 :tag "Org Priorities"
2937 :group 'org-todo)
2939 (defcustom org-enable-priority-commands t
2940 "Non-nil means priority commands are active.
2941 When nil, these commands will be disabled, so that you never accidentally
2942 set a priority."
2943 :group 'org-priorities
2944 :type 'boolean)
2946 (defcustom org-highest-priority ?A
2947 "The highest priority of TODO items. A character like ?A, ?B etc.
2948 Must have a smaller ASCII number than `org-lowest-priority'."
2949 :group 'org-priorities
2950 :type 'character)
2952 (defcustom org-lowest-priority ?C
2953 "The lowest priority of TODO items. A character like ?A, ?B etc.
2954 Must have a larger ASCII number than `org-highest-priority'."
2955 :group 'org-priorities
2956 :type 'character)
2958 (defcustom org-default-priority ?B
2959 "The default priority of TODO items.
2960 This is the priority an item gets if no explicit priority is given.
2961 When starting to cycle on an empty priority the first step in the cycle
2962 depends on `org-priority-start-cycle-with-default'. The resulting first
2963 step priority must not exceed the range from `org-highest-priority' to
2964 `org-lowest-priority' which means that `org-default-priority' has to be
2965 in this range exclusive or inclusive the range boundaries. Else the
2966 first step refuses to set the default and the second will fall back
2967 to (depending on the command used) the highest or lowest priority."
2968 :group 'org-priorities
2969 :type 'character)
2971 (defcustom org-priority-start-cycle-with-default t
2972 "Non-nil means start with default priority when starting to cycle.
2973 When this is nil, the first step in the cycle will be (depending on the
2974 command used) one higher or lower than the default priority.
2975 See also `org-default-priority'."
2976 :group 'org-priorities
2977 :type 'boolean)
2979 (defcustom org-get-priority-function nil
2980 "Function to extract the priority from a string.
2981 The string is normally the headline. If this is nil Org computes the
2982 priority from the priority cookie like [#A] in the headline. It returns
2983 an integer, increasing by 1000 for each priority level.
2984 The user can set a different function here, which should take a string
2985 as an argument and return the numeric priority."
2986 :group 'org-priorities
2987 :version "24.1"
2988 :type '(choice
2989 (const nil)
2990 (function)))
2992 (defgroup org-time nil
2993 "Options concerning time stamps and deadlines in Org-mode."
2994 :tag "Org Time"
2995 :group 'org)
2997 (defcustom org-insert-labeled-timestamps-at-point nil
2998 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2999 When nil, these labeled time stamps are forces into the second line of an
3000 entry, just after the headline. When scheduling from the global TODO list,
3001 the time stamp will always be forced into the second line."
3002 :group 'org-time
3003 :type 'boolean)
3005 (defcustom org-time-stamp-rounding-minutes '(0 5)
3006 "Number of minutes to round time stamps to.
3007 These are two values, the first applies when first creating a time stamp.
3008 The second applies when changing it with the commands `S-up' and `S-down'.
3009 When changing the time stamp, this means that it will change in steps
3010 of N minutes, as given by the second value.
3012 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3013 numbers should be factors of 60, so for example 5, 10, 15.
3015 When this is larger than 1, you can still force an exact time stamp by using
3016 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
3017 and by using a prefix arg to `S-up/down' to specify the exact number
3018 of minutes to shift."
3019 :group 'org-time
3020 :get #'(lambda (var) ; Make sure both elements are there
3021 (if (integerp (default-value var))
3022 (list (default-value var) 5)
3023 (default-value var)))
3024 :type '(list
3025 (integer :tag "when inserting times")
3026 (integer :tag "when modifying times")))
3028 ;; Normalize old customizations of this variable.
3029 (when (integerp org-time-stamp-rounding-minutes)
3030 (setq org-time-stamp-rounding-minutes
3031 (list org-time-stamp-rounding-minutes
3032 org-time-stamp-rounding-minutes)))
3034 (defcustom org-display-custom-times nil
3035 "Non-nil means overlay custom formats over all time stamps.
3036 The formats are defined through the variable `org-time-stamp-custom-formats'.
3037 To turn this on on a per-file basis, insert anywhere in the file:
3038 #+STARTUP: customtime"
3039 :group 'org-time
3040 :set 'set-default
3041 :type 'sexp)
3042 (make-variable-buffer-local 'org-display-custom-times)
3044 (defcustom org-time-stamp-custom-formats
3045 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3046 "Custom formats for time stamps. See `format-time-string' for the syntax.
3047 These are overlaid over the default ISO format if the variable
3048 `org-display-custom-times' is set. Time like %H:%M should be at the
3049 end of the second format. The custom formats are also honored by export
3050 commands, if custom time display is turned on at the time of export."
3051 :group 'org-time
3052 :type 'sexp)
3054 (defun org-time-stamp-format (&optional long inactive)
3055 "Get the right format for a time string."
3056 (let ((f (if long (cdr org-time-stamp-formats)
3057 (car org-time-stamp-formats))))
3058 (if inactive
3059 (concat "[" (substring f 1 -1) "]")
3060 f)))
3062 (defcustom org-time-clocksum-format
3063 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
3064 "The format string used when creating CLOCKSUM lines.
3065 This is also used when Org mode generates a time duration.
3067 The value can be a single format string containing two
3068 %-sequences, which will be filled with the number of hours and
3069 minutes in that order.
3071 Alternatively, the value can be a plist associating any of the
3072 keys :years, :months, :weeks, :days, :hours or :minutes with
3073 format strings. The time duration is formatted using only the
3074 time components that are needed and concatenating the results.
3075 If a time unit in absent, it falls back to the next smallest
3076 unit.
3078 The keys :require-years, :require-months, :require-days,
3079 :require-weeks, :require-hours, :require-minutes are also
3080 meaningful. A non-nil value for these keys indicates that the
3081 corresponding time component should always be included, even if
3082 its value is 0.
3085 For example,
3087 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
3088 :require-minutes t)
3090 means durations longer than a day will be expressed in days,
3091 hours and minutes, and durations less than a day will always be
3092 expressed in hours and minutes (even for durations less than an
3093 hour).
3095 The value
3097 \(:days \"%dd\" :minutes \"%dm\")
3099 means durations longer than a day will be expressed in days and
3100 minutes, and durations less than a day will be expressed entirely
3101 in minutes (even for durations longer than an hour)."
3102 :group 'org-time
3103 :group 'org-clock
3104 :version "24.4"
3105 :package-version '(Org . "8.0")
3106 :type '(choice (string :tag "Format string")
3107 (set :tag "Plist"
3108 (group :inline t (const :tag "Years" :years)
3109 (string :tag "Format string"))
3110 (group :inline t
3111 (const :tag "Always show years" :require-years)
3112 (const t))
3113 (group :inline t (const :tag "Months" :months)
3114 (string :tag "Format string"))
3115 (group :inline t
3116 (const :tag "Always show months" :require-months)
3117 (const t))
3118 (group :inline t (const :tag "Weeks" :weeks)
3119 (string :tag "Format string"))
3120 (group :inline t
3121 (const :tag "Always show weeks" :require-weeks)
3122 (const t))
3123 (group :inline t (const :tag "Days" :days)
3124 (string :tag "Format string"))
3125 (group :inline t
3126 (const :tag "Always show days" :require-days)
3127 (const t))
3128 (group :inline t (const :tag "Hours" :hours)
3129 (string :tag "Format string"))
3130 (group :inline t
3131 (const :tag "Always show hours" :require-hours)
3132 (const t))
3133 (group :inline t (const :tag "Minutes" :minutes)
3134 (string :tag "Format string"))
3135 (group :inline t
3136 (const :tag "Always show minutes" :require-minutes)
3137 (const t)))))
3139 (defcustom org-time-clocksum-use-fractional nil
3140 "When non-nil, \\[org-clock-display] uses fractional times.
3141 See `org-time-clocksum-format' for more on time clock formats."
3142 :group 'org-time
3143 :group 'org-clock
3144 :version "24.3"
3145 :type 'boolean)
3147 (defcustom org-time-clocksum-use-effort-durations nil
3148 "When non-nil, \\[org-clock-display] uses effort durations.
3149 E.g. by default, one day is considered to be a 8 hours effort,
3150 so a task that has been clocked for 16 hours will be displayed
3151 as during 2 days in the clock display or in the clocktable.
3153 See `org-effort-durations' on how to set effort durations
3154 and `org-time-clocksum-format' for more on time clock formats."
3155 :group 'org-time
3156 :group 'org-clock
3157 :version "24.4"
3158 :package-version '(Org . "8.0")
3159 :type 'boolean)
3161 (defcustom org-time-clocksum-fractional-format "%.2f"
3162 "The format string used when creating CLOCKSUM lines,
3163 or when Org mode generates a time duration, if
3164 `org-time-clocksum-use-fractional' is enabled.
3166 The value can be a single format string containing one
3167 %-sequence, which will be filled with the number of hours as
3168 a float.
3170 Alternatively, the value can be a plist associating any of the
3171 keys :years, :months, :weeks, :days, :hours or :minutes with
3172 a format string. The time duration is formatted using the
3173 largest time unit which gives a non-zero integer part. If all
3174 specified formats have zero integer part, the smallest time unit
3175 is used."
3176 :group 'org-time
3177 :type '(choice (string :tag "Format string")
3178 (set (group :inline t (const :tag "Years" :years)
3179 (string :tag "Format string"))
3180 (group :inline t (const :tag "Months" :months)
3181 (string :tag "Format string"))
3182 (group :inline t (const :tag "Weeks" :weeks)
3183 (string :tag "Format string"))
3184 (group :inline t (const :tag "Days" :days)
3185 (string :tag "Format string"))
3186 (group :inline t (const :tag "Hours" :hours)
3187 (string :tag "Format string"))
3188 (group :inline t (const :tag "Minutes" :minutes)
3189 (string :tag "Format string")))))
3191 (defcustom org-deadline-warning-days 14
3192 "Number of days before expiration during which a deadline becomes active.
3193 This variable governs the display in sparse trees and in the agenda.
3194 When 0 or negative, it means use this number (the absolute value of it)
3195 even if a deadline has a different individual lead time specified.
3197 Custom commands can set this variable in the options section."
3198 :group 'org-time
3199 :group 'org-agenda-daily/weekly
3200 :type 'integer)
3202 (defcustom org-scheduled-delay-days 0
3203 "Number of days before a scheduled item becomes active.
3204 This variable governs the display in sparse trees and in the agenda.
3205 The default value (i.e. 0) means: don't delay scheduled item.
3206 When negative, it means use this number (the absolute value of it)
3207 even if a scheduled item has a different individual delay time
3208 specified.
3210 Custom commands can set this variable in the options section."
3211 :group 'org-time
3212 :group 'org-agenda-daily/weekly
3213 :version "24.4"
3214 :package-version '(Org . "8.0")
3215 :type 'integer)
3217 (defcustom org-read-date-prefer-future t
3218 "Non-nil means assume future for incomplete date input from user.
3219 This affects the following situations:
3220 1. The user gives a month but not a year.
3221 For example, if it is April and you enter \"feb 2\", this will be read
3222 as Feb 2, *next* year. \"May 5\", however, will be this year.
3223 2. The user gives a day, but no month.
3224 For example, if today is the 15th, and you enter \"3\", Org-mode will
3225 read this as the third of *next* month. However, if you enter \"17\",
3226 it will be considered as *this* month.
3228 If you set this variable to the symbol `time', then also the following
3229 will work:
3231 3. If the user gives a time.
3232 If the time is before now, it will be interpreted as tomorrow.
3234 Currently none of this works for ISO week specifications.
3236 When this option is nil, the current day, month and year will always be
3237 used as defaults.
3239 See also `org-agenda-jump-prefer-future'."
3240 :group 'org-time
3241 :type '(choice
3242 (const :tag "Never" nil)
3243 (const :tag "Check month and day" t)
3244 (const :tag "Check month, day, and time" time)))
3246 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3247 "Should the agenda jump command prefer the future for incomplete dates?
3248 The default is to do the same as configured in `org-read-date-prefer-future'.
3249 But you can also set a deviating value here.
3250 This may t or nil, or the symbol `org-read-date-prefer-future'."
3251 :group 'org-agenda
3252 :group 'org-time
3253 :version "24.1"
3254 :type '(choice
3255 (const :tag "Use org-read-date-prefer-future"
3256 org-read-date-prefer-future)
3257 (const :tag "Never" nil)
3258 (const :tag "Always" t)))
3260 (defcustom org-read-date-force-compatible-dates t
3261 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3263 Depending on the system Emacs is running on, certain dates cannot
3264 be represented with the type used internally to represent time.
3265 Dates between 1970-1-1 and 2038-1-1 can always be represented
3266 correctly. Some systems allow for earlier dates, some for later,
3267 some for both. One way to find out it to insert any date into an
3268 Org buffer, putting the cursor on the year and hitting S-up and
3269 S-down to test the range.
3271 When this variable is set to t, the date/time prompt will not let
3272 you specify dates outside the 1970-2037 range, so it is certain that
3273 these dates will work in whatever version of Emacs you are
3274 running, and also that you can move a file from one Emacs implementation
3275 to another. WHenever Org is forcing the year for you, it will display
3276 a message and beep.
3278 When this variable is nil, Org will check if the date is
3279 representable in the specific Emacs implementation you are using.
3280 If not, it will force a year, usually the current year, and beep
3281 to remind you. Currently this setting is not recommended because
3282 the likelihood that you will open your Org files in an Emacs that
3283 has limited date range is not negligible.
3285 A workaround for this problem is to use diary sexp dates for time
3286 stamps outside of this range."
3287 :group 'org-time
3288 :version "24.1"
3289 :type 'boolean)
3291 (defcustom org-read-date-display-live t
3292 "Non-nil means display current interpretation of date prompt live.
3293 This display will be in an overlay, in the minibuffer."
3294 :group 'org-time
3295 :type 'boolean)
3297 (defcustom org-read-date-popup-calendar t
3298 "Non-nil means pop up a calendar when prompting for a date.
3299 In the calendar, the date can be selected with mouse-1. However, the
3300 minibuffer will also be active, and you can simply enter the date as well.
3301 When nil, only the minibuffer will be available."
3302 :group 'org-time
3303 :type 'boolean)
3304 (org-defvaralias 'org-popup-calendar-for-date-prompt
3305 'org-read-date-popup-calendar)
3307 (make-obsolete-variable
3308 'org-read-date-minibuffer-setup-hook
3309 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3310 (defcustom org-read-date-minibuffer-setup-hook nil
3311 "Hook to be used to set up keys for the date/time interface.
3312 Add key definitions to `minibuffer-local-map', which will be a
3313 temporary copy.
3315 WARNING: This option is obsolete, you should use
3316 `org-read-date-minibuffer-local-map' to set up keys."
3317 :group 'org-time
3318 :type 'hook)
3320 (defcustom org-extend-today-until 0
3321 "The hour when your day really ends. Must be an integer.
3322 This has influence for the following applications:
3323 - When switching the agenda to \"today\". It it is still earlier than
3324 the time given here, the day recognized as TODAY is actually yesterday.
3325 - When a date is read from the user and it is still before the time given
3326 here, the current date and time will be assumed to be yesterday, 23:59.
3327 Also, timestamps inserted in capture templates follow this rule.
3329 IMPORTANT: This is a feature whose implementation is and likely will
3330 remain incomplete. Really, it is only here because past midnight seems to
3331 be the favorite working time of John Wiegley :-)"
3332 :group 'org-time
3333 :type 'integer)
3335 (defcustom org-use-effective-time nil
3336 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3337 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3338 \"effective time\" of any timestamps between midnight and 8am will be
3339 23:59 of the previous day."
3340 :group 'org-time
3341 :version "24.1"
3342 :type 'boolean)
3344 (defcustom org-use-last-clock-out-time-as-effective-time nil
3345 "When non-nil, use the last clock out time for `org-todo'.
3346 Note that this option has precedence over the combined use of
3347 `org-use-effective-time' and `org-extend-today-until'."
3348 :group 'org-time
3349 :version "24.4"
3350 :package-version '(Org . "8.0")
3351 :type 'boolean)
3353 (defcustom org-edit-timestamp-down-means-later nil
3354 "Non-nil means S-down will increase the time in a time stamp.
3355 When nil, S-up will increase."
3356 :group 'org-time
3357 :type 'boolean)
3359 (defcustom org-calendar-follow-timestamp-change t
3360 "Non-nil means make the calendar window follow timestamp changes.
3361 When a timestamp is modified and the calendar window is visible, it will be
3362 moved to the new date."
3363 :group 'org-time
3364 :type 'boolean)
3366 (defgroup org-tags nil
3367 "Options concerning tags in Org-mode."
3368 :tag "Org Tags"
3369 :group 'org)
3371 (defcustom org-tag-alist nil
3372 "List of tags allowed in Org-mode files.
3373 When this list is nil, Org-mode will base TAG input on what is already in the
3374 buffer.
3375 The value of this variable is an alist, the car of each entry must be a
3376 keyword as a string, the cdr may be a character that is used to select
3377 that tag through the fast-tag-selection interface.
3378 See the manual for details."
3379 :group 'org-tags
3380 :type '(repeat
3381 (choice
3382 (cons (string :tag "Tag name")
3383 (character :tag "Access char"))
3384 (list :tag "Start radio group"
3385 (const :startgroup)
3386 (option (string :tag "Group description")))
3387 (list :tag "Group tags delimiter"
3388 (const :grouptags))
3389 (list :tag "End radio group"
3390 (const :endgroup)
3391 (option (string :tag "Group description")))
3392 (const :tag "New line" (:newline)))))
3394 (defcustom org-tag-persistent-alist nil
3395 "List of tags that will always appear in all Org-mode files.
3396 This is in addition to any in buffer settings or customizations
3397 of `org-tag-alist'.
3398 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3399 The value of this variable is an alist, the car of each entry must be a
3400 keyword as a string, the cdr may be a character that is used to select
3401 that tag through the fast-tag-selection interface.
3402 See the manual for details.
3403 To disable these tags on a per-file basis, insert anywhere in the file:
3404 #+STARTUP: noptag"
3405 :group 'org-tags
3406 :type '(repeat
3407 (choice
3408 (cons (string :tag "Tag name")
3409 (character :tag "Access char"))
3410 (const :tag "Start radio group" (:startgroup))
3411 (const :tag "Group tags delimiter" (:grouptags))
3412 (const :tag "End radio group" (:endgroup))
3413 (const :tag "New line" (:newline)))))
3415 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3416 "If non-nil, always offer completion for all tags of all agenda files.
3417 Instead of customizing this variable directly, you might want to
3418 set it locally for capture buffers, because there no list of
3419 tags in that file can be created dynamically (there are none).
3421 (add-hook 'org-capture-mode-hook
3422 (lambda ()
3423 (set (make-local-variable
3424 'org-complete-tags-always-offer-all-agenda-tags)
3425 t)))"
3426 :group 'org-tags
3427 :version "24.1"
3428 :type 'boolean)
3430 (defvar org-file-tags nil
3431 "List of tags that can be inherited by all entries in the file.
3432 The tags will be inherited if the variable `org-use-tag-inheritance'
3433 says they should be.
3434 This variable is populated from #+FILETAGS lines.")
3436 (defcustom org-use-fast-tag-selection 'auto
3437 "Non-nil means use fast tag selection scheme.
3438 This is a special interface to select and deselect tags with single keys.
3439 When nil, fast selection is never used.
3440 When the symbol `auto', fast selection is used if and only if selection
3441 characters for tags have been configured, either through the variable
3442 `org-tag-alist' or through a #+TAGS line in the buffer.
3443 When t, fast selection is always used and selection keys are assigned
3444 automatically if necessary."
3445 :group 'org-tags
3446 :type '(choice
3447 (const :tag "Always" t)
3448 (const :tag "Never" nil)
3449 (const :tag "When selection characters are configured" auto)))
3451 (defcustom org-fast-tag-selection-single-key nil
3452 "Non-nil means fast tag selection exits after first change.
3453 When nil, you have to press RET to exit it.
3454 During fast tag selection, you can toggle this flag with `C-c'.
3455 This variable can also have the value `expert'. In this case, the window
3456 displaying the tags menu is not even shown, until you press C-c again."
3457 :group 'org-tags
3458 :type '(choice
3459 (const :tag "No" nil)
3460 (const :tag "Yes" t)
3461 (const :tag "Expert" expert)))
3463 (defvar org-fast-tag-selection-include-todo nil
3464 "Non-nil means fast tags selection interface will also offer TODO states.
3465 This is an undocumented feature, you should not rely on it.")
3467 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3468 "The column to which tags should be indented in a headline.
3469 If this number is positive, it specifies the column. If it is negative,
3470 it means that the tags should be flushright to that column. For example,
3471 -80 works well for a normal 80 character screen.
3472 When 0, place tags directly after headline text, with only one space in
3473 between."
3474 :group 'org-tags
3475 :type 'integer)
3477 (defcustom org-auto-align-tags t
3478 "Non-nil keeps tags aligned when modifying headlines.
3479 Some operations (i.e. demoting) change the length of a headline and
3480 therefore shift the tags around. With this option turned on, after
3481 each such operation the tags are again aligned to `org-tags-column'."
3482 :group 'org-tags
3483 :type 'boolean)
3485 (defcustom org-use-tag-inheritance t
3486 "Non-nil means tags in levels apply also for sublevels.
3487 When nil, only the tags directly given in a specific line apply there.
3488 This may also be a list of tags that should be inherited, or a regexp that
3489 matches tags that should be inherited. Additional control is possible
3490 with the variable `org-tags-exclude-from-inheritance' which gives an
3491 explicit list of tags to be excluded from inheritance, even if the value of
3492 `org-use-tag-inheritance' would select it for inheritance.
3494 If this option is t, a match early-on in a tree can lead to a large
3495 number of matches in the subtree when constructing the agenda or creating
3496 a sparse tree. If you only want to see the first match in a tree during
3497 a search, check out the variable `org-tags-match-list-sublevels'."
3498 :group 'org-tags
3499 :type '(choice
3500 (const :tag "Not" nil)
3501 (const :tag "Always" t)
3502 (repeat :tag "Specific tags" (string :tag "Tag"))
3503 (regexp :tag "Tags matched by regexp")))
3505 (defcustom org-tags-exclude-from-inheritance nil
3506 "List of tags that should never be inherited.
3507 This is a way to exclude a few tags from inheritance. For way to do
3508 the opposite, to actively allow inheritance for selected tags,
3509 see the variable `org-use-tag-inheritance'."
3510 :group 'org-tags
3511 :type '(repeat (string :tag "Tag")))
3513 (defun org-tag-inherit-p (tag)
3514 "Check if TAG is one that should be inherited."
3515 (cond
3516 ((member tag org-tags-exclude-from-inheritance) nil)
3517 ((eq org-use-tag-inheritance t) t)
3518 ((not org-use-tag-inheritance) nil)
3519 ((stringp org-use-tag-inheritance)
3520 (string-match org-use-tag-inheritance tag))
3521 ((listp org-use-tag-inheritance)
3522 (member tag org-use-tag-inheritance))
3523 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3525 (defcustom org-tags-match-list-sublevels t
3526 "Non-nil means list also sublevels of headlines matching a search.
3527 This variable applies to tags/property searches, and also to stuck
3528 projects because this search is based on a tags match as well.
3530 When set to the symbol `indented', sublevels are indented with
3531 leading dots.
3533 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3534 the sublevels of a headline matching a tag search often also match
3535 the same search. Listing all of them can create very long lists.
3536 Setting this variable to nil causes subtrees of a match to be skipped.
3538 This variable is semi-obsolete and probably should always be true. It
3539 is better to limit inheritance to certain tags using the variables
3540 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3541 :group 'org-tags
3542 :type '(choice
3543 (const :tag "No, don't list them" nil)
3544 (const :tag "Yes, do list them" t)
3545 (const :tag "List them, indented with leading dots" indented)))
3547 (defcustom org-tags-sort-function nil
3548 "When set, tags are sorted using this function as a comparator."
3549 :group 'org-tags
3550 :type '(choice
3551 (const :tag "No sorting" nil)
3552 (const :tag "Alphabetical" string<)
3553 (const :tag "Reverse alphabetical" string>)
3554 (function :tag "Custom function" nil)))
3556 (defvar org-tags-history nil
3557 "History of minibuffer reads for tags.")
3558 (defvar org-last-tags-completion-table nil
3559 "The last used completion table for tags.")
3560 (defvar org-after-tags-change-hook nil
3561 "Hook that is run after the tags in a line have changed.")
3563 (defgroup org-properties nil
3564 "Options concerning properties in Org-mode."
3565 :tag "Org Properties"
3566 :group 'org)
3568 (defcustom org-property-format "%-10s %s"
3569 "How property key/value pairs should be formatted by `indent-line'.
3570 When `indent-line' hits a property definition, it will format the line
3571 according to this format, mainly to make sure that the values are
3572 lined-up with respect to each other."
3573 :group 'org-properties
3574 :type 'string)
3576 (defcustom org-properties-postprocess-alist nil
3577 "Alist of properties and functions to adjust inserted values.
3578 Elements of this alist must be of the form
3580 ([string] [function])
3582 where [string] must be a property name and [function] must be a
3583 lambda expression: this lambda expression must take one argument,
3584 the value to adjust, and return the new value as a string.
3586 For example, this element will allow the property \"Remaining\"
3587 to be updated wrt the relation between the \"Effort\" property
3588 and the clock summary:
3590 ((\"Remaining\" (lambda(value)
3591 (let ((clocksum (org-clock-sum-current-item))
3592 (effort (org-duration-string-to-minutes
3593 (org-entry-get (point) \"Effort\"))))
3594 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3595 :group 'org-properties
3596 :version "24.1"
3597 :type '(alist :key-type (string :tag "Property")
3598 :value-type (function :tag "Function")))
3600 (defcustom org-use-property-inheritance nil
3601 "Non-nil means properties apply also for sublevels.
3603 This setting is chiefly used during property searches. Turning it on can
3604 cause significant overhead when doing a search, which is why it is not
3605 on by default.
3607 When nil, only the properties directly given in the current entry count.
3608 When t, every property is inherited. The value may also be a list of
3609 properties that should have inheritance, or a regular expression matching
3610 properties that should be inherited.
3612 However, note that some special properties use inheritance under special
3613 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3614 and the properties ending in \"_ALL\" when they are used as descriptor
3615 for valid values of a property.
3617 Note for programmers:
3618 When querying an entry with `org-entry-get', you can control if inheritance
3619 should be used. By default, `org-entry-get' looks only at the local
3620 properties. You can request inheritance by setting the inherit argument
3621 to t (to force inheritance) or to `selective' (to respect the setting
3622 in this variable)."
3623 :group 'org-properties
3624 :type '(choice
3625 (const :tag "Not" nil)
3626 (const :tag "Always" t)
3627 (repeat :tag "Specific properties" (string :tag "Property"))
3628 (regexp :tag "Properties matched by regexp")))
3630 (defun org-property-inherit-p (property)
3631 "Check if PROPERTY is one that should be inherited."
3632 (cond
3633 ((eq org-use-property-inheritance t) t)
3634 ((not org-use-property-inheritance) nil)
3635 ((stringp org-use-property-inheritance)
3636 (string-match org-use-property-inheritance property))
3637 ((listp org-use-property-inheritance)
3638 (member property org-use-property-inheritance))
3639 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3641 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3642 "The default column format, if no other format has been defined.
3643 This variable can be set on the per-file basis by inserting a line
3645 #+COLUMNS: %25ITEM ....."
3646 :group 'org-properties
3647 :type 'string)
3649 (defcustom org-columns-ellipses ".."
3650 "The ellipses to be used when a field in column view is truncated.
3651 When this is the empty string, as many characters as possible are shown,
3652 but then there will be no visual indication that the field has been truncated.
3653 When this is a string of length N, the last N characters of a truncated
3654 field are replaced by this string. If the column is narrower than the
3655 ellipses string, only part of the ellipses string will be shown."
3656 :group 'org-properties
3657 :type 'string)
3659 (defcustom org-columns-modify-value-for-display-function nil
3660 "Function that modifies values for display in column view.
3661 For example, it can be used to cut out a certain part from a time stamp.
3662 The function must take 2 arguments:
3664 column-title The title of the column (*not* the property name)
3665 value The value that should be modified.
3667 The function should return the value that should be displayed,
3668 or nil if the normal value should be used."
3669 :group 'org-properties
3670 :type '(choice (const nil) (function)))
3672 (defconst org-global-properties-fixed
3673 '(("VISIBILITY_ALL" . "folded children content all")
3674 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3675 "List of property/value pairs that can be inherited by any entry.
3677 These are fixed values, for the preset properties. The user variable
3678 that can be used to add to this list is `org-global-properties'.
3680 The entries in this list are cons cells where the car is a property
3681 name and cdr is a string with the value. If the value represents
3682 multiple items like an \"_ALL\" property, separate the items by
3683 spaces.")
3685 (defcustom org-global-properties nil
3686 "List of property/value pairs that can be inherited by any entry.
3688 This list will be combined with the constant `org-global-properties-fixed'.
3690 The entries in this list are cons cells where the car is a property
3691 name and cdr is a string with the value.
3693 You can set buffer-local values for the same purpose in the variable
3694 `org-file-properties' this by adding lines like
3696 #+PROPERTY: NAME VALUE"
3697 :group 'org-properties
3698 :type '(repeat
3699 (cons (string :tag "Property")
3700 (string :tag "Value"))))
3702 (defvar org-file-properties nil
3703 "List of property/value pairs that can be inherited by any entry.
3704 Valid for the current buffer.
3705 This variable is populated from #+PROPERTY lines.")
3706 (make-variable-buffer-local 'org-file-properties)
3708 (defgroup org-agenda nil
3709 "Options concerning agenda views in Org-mode."
3710 :tag "Org Agenda"
3711 :group 'org)
3713 (defvar org-category nil
3714 "Variable used by org files to set a category for agenda display.
3715 Such files should use a file variable to set it, for example
3717 # -*- mode: org; org-category: \"ELisp\"
3719 or contain a special line
3721 #+CATEGORY: ELisp
3723 If the file does not specify a category, then file's base name
3724 is used instead.")
3725 (make-variable-buffer-local 'org-category)
3726 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3728 (defcustom org-agenda-files nil
3729 "The files to be used for agenda display.
3730 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3731 \\[org-remove-file]. You can also use customize to edit the list.
3733 If an entry is a directory, all files in that directory that are matched by
3734 `org-agenda-file-regexp' will be part of the file list.
3736 If the value of the variable is not a list but a single file name, then
3737 the list of agenda files is actually stored and maintained in that file, one
3738 agenda file per line. In this file paths can be given relative to
3739 `org-directory'. Tilde expansion and environment variable substitution
3740 are also made."
3741 :group 'org-agenda
3742 :type '(choice
3743 (repeat :tag "List of files and directories" file)
3744 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3746 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3747 "Regular expression to match files for `org-agenda-files'.
3748 If any element in the list in that variable contains a directory instead
3749 of a normal file, all files in that directory that are matched by this
3750 regular expression will be included."
3751 :group 'org-agenda
3752 :type 'regexp)
3754 (defcustom org-agenda-text-search-extra-files nil
3755 "List of extra files to be searched by text search commands.
3756 These files will be searched in addition to the agenda files by the
3757 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3758 Note that these files will only be searched for text search commands,
3759 not for the other agenda views like todo lists, tag searches or the weekly
3760 agenda. This variable is intended to list notes and possibly archive files
3761 that should also be searched by these two commands.
3762 In fact, if the first element in the list is the symbol `agenda-archives',
3763 then all archive files of all agenda files will be added to the search
3764 scope."
3765 :group 'org-agenda
3766 :type '(set :greedy t
3767 (const :tag "Agenda Archives" agenda-archives)
3768 (repeat :inline t (file))))
3770 (org-defvaralias 'org-agenda-multi-occur-extra-files
3771 'org-agenda-text-search-extra-files)
3773 (defcustom org-agenda-skip-unavailable-files nil
3774 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3775 A nil value means to remove them, after a query, from the list."
3776 :group 'org-agenda
3777 :type 'boolean)
3779 (defcustom org-calendar-to-agenda-key [?c]
3780 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3781 The command `org-calendar-goto-agenda' will be bound to this key. The
3782 default is the character `c' because then `c' can be used to switch back and
3783 forth between agenda and calendar."
3784 :group 'org-agenda
3785 :type 'sexp)
3787 (defcustom org-calendar-insert-diary-entry-key [?i]
3788 "The key to be installed in `calendar-mode-map' for adding diary entries.
3789 This option is irrelevant until `org-agenda-diary-file' has been configured
3790 to point to an Org-mode file. When that is the case, the command
3791 `org-agenda-diary-entry' will be bound to the key given here, by default
3792 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3793 if you want to continue doing this, you need to change this to a different
3794 key."
3795 :group 'org-agenda
3796 :type 'sexp)
3798 (defcustom org-agenda-diary-file 'diary-file
3799 "File to which to add new entries with the `i' key in agenda and calendar.
3800 When this is the symbol `diary-file', the functionality in the Emacs
3801 calendar will be used to add entries to the `diary-file'. But when this
3802 points to a file, `org-agenda-diary-entry' will be used instead."
3803 :group 'org-agenda
3804 :type '(choice
3805 (const :tag "The standard Emacs diary file" diary-file)
3806 (file :tag "Special Org file diary entries")))
3808 (eval-after-load "calendar"
3809 '(progn
3810 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3811 'org-calendar-goto-agenda)
3812 (add-hook 'calendar-mode-hook
3813 (lambda ()
3814 (unless (eq org-agenda-diary-file 'diary-file)
3815 (define-key calendar-mode-map
3816 org-calendar-insert-diary-entry-key
3817 'org-agenda-diary-entry))))))
3819 (defgroup org-latex nil
3820 "Options for embedding LaTeX code into Org-mode."
3821 :tag "Org LaTeX"
3822 :group 'org)
3824 (defcustom org-format-latex-options
3825 '(:foreground default :background default :scale 1.0
3826 :html-foreground "Black" :html-background "Transparent"
3827 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3828 "Options for creating images from LaTeX fragments.
3829 This is a property list with the following properties:
3830 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3831 `default' means use the foreground of the default face.
3832 `auto' means use the foreground from the text face.
3833 :background the background color, or \"Transparent\".
3834 `default' means use the background of the default face.
3835 `auto' means use the background from the text face.
3836 :scale a scaling factor for the size of the images, to get more pixels
3837 :html-foreground, :html-background, :html-scale
3838 the same numbers for HTML export.
3839 :matchers a list indicating which matchers should be used to
3840 find LaTeX fragments. Valid members of this list are:
3841 \"begin\" find environments
3842 \"$1\" find single characters surrounded by $.$
3843 \"$\" find math expressions surrounded by $...$
3844 \"$$\" find math expressions surrounded by $$....$$
3845 \"\\(\" find math expressions surrounded by \\(...\\)
3846 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3847 :group 'org-latex
3848 :type 'plist)
3850 (defcustom org-format-latex-signal-error t
3851 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3852 When nil, just push out a message."
3853 :group 'org-latex
3854 :version "24.1"
3855 :type 'boolean)
3857 (defcustom org-latex-to-mathml-jar-file nil
3858 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3859 Use this to specify additional executable file say a jar file.
3861 When using MathToWeb as the converter, specify the full-path to
3862 your mathtoweb.jar file."
3863 :group 'org-latex
3864 :version "24.1"
3865 :type '(choice
3866 (const :tag "None" nil)
3867 (file :tag "JAR file" :must-match t)))
3869 (defcustom org-latex-to-mathml-convert-command nil
3870 "Command to convert LaTeX fragments to MathML.
3871 Replace format-specifiers in the command as noted below and use
3872 `shell-command' to convert LaTeX to MathML.
3873 %j: Executable file in fully expanded form as specified by
3874 `org-latex-to-mathml-jar-file'.
3875 %I: Input LaTeX file in fully expanded form
3876 %o: Output MathML file
3877 This command is used by `org-create-math-formula'.
3879 When using MathToWeb as the converter, set this to
3880 \"java -jar %j -unicode -force -df %o %I\"."
3881 :group 'org-latex
3882 :version "24.1"
3883 :type '(choice
3884 (const :tag "None" nil)
3885 (string :tag "\nShell command")))
3887 (defcustom org-latex-create-formula-image-program 'dvipng
3888 "Program to convert LaTeX fragments with.
3890 dvipng Process the LaTeX fragments to dvi file, then convert
3891 dvi files to png files using dvipng.
3892 This will also include processing of non-math environments.
3893 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3894 to convert pdf files to png files"
3895 :group 'org-latex
3896 :version "24.1"
3897 :type '(choice
3898 (const :tag "dvipng" dvipng)
3899 (const :tag "imagemagick" imagemagick)))
3901 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3902 "Path to store latex preview images.
3903 A relative path here creates many directories relative to the
3904 processed org files paths. An absolute path puts all preview
3905 images at the same place."
3906 :group 'org-latex
3907 :version "24.3"
3908 :type 'string)
3910 (defun org-format-latex-mathml-available-p ()
3911 "Return t if `org-latex-to-mathml-convert-command' is usable."
3912 (save-match-data
3913 (when (and (boundp 'org-latex-to-mathml-convert-command)
3914 org-latex-to-mathml-convert-command)
3915 (let ((executable (car (split-string
3916 org-latex-to-mathml-convert-command))))
3917 (when (executable-find executable)
3918 (if (string-match
3919 "%j" org-latex-to-mathml-convert-command)
3920 (file-readable-p org-latex-to-mathml-jar-file)
3921 t))))))
3923 (defcustom org-format-latex-header "\\documentclass{article}
3924 \\usepackage[usenames]{color}
3925 \[PACKAGES]
3926 \[DEFAULT-PACKAGES]
3927 \\pagestyle{empty} % do not remove
3928 % The settings below are copied from fullpage.sty
3929 \\setlength{\\textwidth}{\\paperwidth}
3930 \\addtolength{\\textwidth}{-3cm}
3931 \\setlength{\\oddsidemargin}{1.5cm}
3932 \\addtolength{\\oddsidemargin}{-2.54cm}
3933 \\setlength{\\evensidemargin}{\\oddsidemargin}
3934 \\setlength{\\textheight}{\\paperheight}
3935 \\addtolength{\\textheight}{-\\headheight}
3936 \\addtolength{\\textheight}{-\\headsep}
3937 \\addtolength{\\textheight}{-\\footskip}
3938 \\addtolength{\\textheight}{-3cm}
3939 \\setlength{\\topmargin}{1.5cm}
3940 \\addtolength{\\topmargin}{-2.54cm}"
3941 "The document header used for processing LaTeX fragments.
3942 It is imperative that this header make sure that no page number
3943 appears on the page. The package defined in the variables
3944 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3945 will either replace the placeholder \"[PACKAGES]\" in this
3946 header, or they will be appended."
3947 :group 'org-latex
3948 :type 'string)
3950 (defun org-set-packages-alist (var val)
3951 "Set the packages alist and make sure it has 3 elements per entry."
3952 (set var (mapcar (lambda (x)
3953 (if (and (consp x) (= (length x) 2))
3954 (list (car x) (nth 1 x) t)
3956 val)))
3958 (defun org-get-packages-alist (var)
3959 "Get the packages alist and make sure it has 3 elements per entry."
3960 (mapcar (lambda (x)
3961 (if (and (consp x) (= (length x) 2))
3962 (list (car x) (nth 1 x) t)
3964 (default-value var)))
3966 (defcustom org-latex-default-packages-alist
3967 '(("AUTO" "inputenc" t)
3968 ("T1" "fontenc" t)
3969 ("" "fixltx2e" nil)
3970 ("" "graphicx" t)
3971 ("" "longtable" nil)
3972 ("" "float" nil)
3973 ("" "wrapfig" nil)
3974 ("" "rotating" nil)
3975 ("normalem" "ulem" t)
3976 ("" "amsmath" t)
3977 ("" "textcomp" t)
3978 ("" "marvosym" t)
3979 ("" "wasysym" t)
3980 ("" "amssymb" t)
3981 ("" "hyperref" nil)
3982 "\\tolerance=1000")
3983 "Alist of default packages to be inserted in the header.
3985 Change this only if one of the packages here causes an
3986 incompatibility with another package you are using.
3988 The packages in this list are needed by one part or another of
3989 Org mode to function properly:
3991 - inputenc, fontenc: for basic font and character selection
3992 - fixltx2e: Important patches of LaTeX itself
3993 - graphicx: for including images
3994 - longtable: For multipage tables
3995 - float, wrapfig: for figure placement
3996 - rotating: for sideways figures and tables
3997 - ulem: for underline and strike-through
3998 - amsmath: for subscript and superscript and math environments
3999 - textcomp, marvosymb, wasysym, amssymb: for various symbols used
4000 for interpreting the entities in `org-entities'. You can skip
4001 some of these packages if you don't use any of their symbols.
4002 - hyperref: for cross references
4004 Therefore you should not modify this variable unless you know
4005 what you are doing. The one reason to change it anyway is that
4006 you might be loading some other package that conflicts with one
4007 of the default packages. Each cell is of the format
4008 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
4009 the package also needs to be included when compiling LaTeX
4010 snippets into images for inclusion into non-LaTeX output."
4011 :group 'org-latex
4012 :group 'org-export-latex
4013 :set 'org-set-packages-alist
4014 :get 'org-get-packages-alist
4015 :version "24.1"
4016 :type '(repeat
4017 (choice
4018 (list :tag "options/package pair"
4019 (string :tag "options")
4020 (string :tag "package")
4021 (boolean :tag "Snippet"))
4022 (string :tag "A line of LaTeX"))))
4024 (defcustom org-latex-packages-alist nil
4025 "Alist of packages to be inserted in every LaTeX header.
4027 These will be inserted after `org-latex-default-packages-alist'.
4028 Each cell is of the format:
4030 \(\"options\" \"package\" snippet-flag)
4032 SNIPPET-FLAG, when t, indicates that this package is also needed
4033 when turning LaTeX snippets into images for inclusion into
4034 non-LaTeX output.
4036 Make sure that you only list packages here which:
4038 - you want in every file
4039 - do not conflict with the setup in `org-format-latex-header'.
4040 - do not conflict with the default packages in
4041 `org-latex-default-packages-alist'."
4042 :group 'org-latex
4043 :group 'org-export-latex
4044 :set 'org-set-packages-alist
4045 :get 'org-get-packages-alist
4046 :type '(repeat
4047 (choice
4048 (list :tag "options/package pair"
4049 (string :tag "options")
4050 (string :tag "package")
4051 (boolean :tag "Snippet"))
4052 (string :tag "A line of LaTeX"))))
4054 (defgroup org-appearance nil
4055 "Settings for Org-mode appearance."
4056 :tag "Org Appearance"
4057 :group 'org)
4059 (defcustom org-level-color-stars-only nil
4060 "Non-nil means fontify only the stars in each headline.
4061 When nil, the entire headline is fontified.
4062 Changing it requires restart of `font-lock-mode' to become effective
4063 also in regions already fontified."
4064 :group 'org-appearance
4065 :type 'boolean)
4067 (defcustom org-hide-leading-stars nil
4068 "Non-nil means hide the first N-1 stars in a headline.
4069 This works by using the face `org-hide' for these stars. This
4070 face is white for a light background, and black for a dark
4071 background. You may have to customize the face `org-hide' to
4072 make this work.
4073 Changing it requires restart of `font-lock-mode' to become effective
4074 also in regions already fontified.
4075 You may also set this on a per-file basis by adding one of the following
4076 lines to the buffer:
4078 #+STARTUP: hidestars
4079 #+STARTUP: showstars"
4080 :group 'org-appearance
4081 :type 'boolean)
4083 (defcustom org-hidden-keywords nil
4084 "List of symbols corresponding to keywords to be hidden the org buffer.
4085 For example, a value '(title) for this list will make the document's title
4086 appear in the buffer without the initial #+TITLE: keyword."
4087 :group 'org-appearance
4088 :version "24.1"
4089 :type '(set (const :tag "#+AUTHOR" author)
4090 (const :tag "#+DATE" date)
4091 (const :tag "#+EMAIL" email)
4092 (const :tag "#+TITLE" title)))
4094 (defcustom org-custom-properties nil
4095 "List of properties (as strings) with a special meaning.
4096 The default use of these custom properties is to let the user
4097 hide them with `org-toggle-custom-properties-visibility'."
4098 :group 'org-properties
4099 :group 'org-appearance
4100 :version "24.3"
4101 :type '(repeat (string :tag "Property Name")))
4103 (defcustom org-fontify-done-headline nil
4104 "Non-nil means change the face of a headline if it is marked DONE.
4105 Normally, only the TODO/DONE keyword indicates the state of a headline.
4106 When this is non-nil, the headline after the keyword is set to the
4107 `org-headline-done' as an additional indication."
4108 :group 'org-appearance
4109 :type 'boolean)
4111 (defcustom org-fontify-emphasized-text t
4112 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4113 Changing this variable requires a restart of Emacs to take effect."
4114 :group 'org-appearance
4115 :type 'boolean)
4117 (defcustom org-fontify-whole-heading-line nil
4118 "Non-nil means fontify the whole line for headings.
4119 This is useful when setting a background color for the
4120 org-level-* faces."
4121 :group 'org-appearance
4122 :type 'boolean)
4124 (defcustom org-highlight-latex-and-related nil
4125 "Non-nil means highlight LaTeX related syntax in the buffer.
4126 When non nil, the value should be a list containing any of the
4127 following symbols:
4128 `latex' Highlight LaTeX snippets and environments.
4129 `script' Highlight subscript and superscript.
4130 `entities' Highlight entities."
4131 :group 'org-appearance
4132 :version "24.4"
4133 :package-version '(Org . "8.0")
4134 :type '(choice
4135 (const :tag "No highlighting" nil)
4136 (set :greedy t :tag "Highlight"
4137 (const :tag "LaTeX snippets and environments" latex)
4138 (const :tag "Subscript and superscript" script)
4139 (const :tag "Entities" entities))))
4141 (defcustom org-hide-emphasis-markers nil
4142 "Non-nil mean font-lock should hide the emphasis marker characters."
4143 :group 'org-appearance
4144 :type 'boolean)
4146 (defcustom org-hide-macro-markers nil
4147 "Non-nil mean font-lock should hide the brackets marking macro calls."
4148 :group 'org-appearance
4149 :type 'boolean)
4151 (defcustom org-pretty-entities nil
4152 "Non-nil means show entities as UTF8 characters.
4153 When nil, the \\name form remains in the buffer."
4154 :group 'org-appearance
4155 :version "24.1"
4156 :type 'boolean)
4158 (defcustom org-pretty-entities-include-sub-superscripts t
4159 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4160 :group 'org-appearance
4161 :version "24.1"
4162 :type 'boolean)
4164 (defvar org-emph-re nil
4165 "Regular expression for matching emphasis.
4166 After a match, the match groups contain these elements:
4167 0 The match of the full regular expression, including the characters
4168 before and after the proper match
4169 1 The character before the proper match, or empty at beginning of line
4170 2 The proper match, including the leading and trailing markers
4171 3 The leading marker like * or /, indicating the type of highlighting
4172 4 The text between the emphasis markers, not including the markers
4173 5 The character after the match, empty at the end of a line")
4174 (defvar org-verbatim-re nil
4175 "Regular expression for matching verbatim text.")
4176 (defvar org-emphasis-regexp-components) ; defined just below
4177 (defvar org-emphasis-alist) ; defined just below
4178 (defun org-set-emph-re (var val)
4179 "Set variable and compute the emphasis regular expression."
4180 (set var val)
4181 (when (and (boundp 'org-emphasis-alist)
4182 (boundp 'org-emphasis-regexp-components)
4183 org-emphasis-alist org-emphasis-regexp-components)
4184 (let* ((e org-emphasis-regexp-components)
4185 (pre (car e))
4186 (post (nth 1 e))
4187 (border (nth 2 e))
4188 (body (nth 3 e))
4189 (nl (nth 4 e))
4190 (body1 (concat body "*?"))
4191 (markers (mapconcat 'car org-emphasis-alist ""))
4192 (vmarkers (mapconcat
4193 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4194 org-emphasis-alist "")))
4195 ;; make sure special characters appear at the right position in the class
4196 (if (string-match "\\^" markers)
4197 (setq markers (concat (replace-match "" t t markers) "^")))
4198 (if (string-match "-" markers)
4199 (setq markers (concat (replace-match "" t t markers) "-")))
4200 (if (string-match "\\^" vmarkers)
4201 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4202 (if (string-match "-" vmarkers)
4203 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4204 (if (> nl 0)
4205 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4206 (int-to-string nl) "\\}")))
4207 ;; Make the regexp
4208 (setq org-emph-re
4209 (concat "\\([" pre "]\\|^\\)"
4210 "\\("
4211 "\\([" markers "]\\)"
4212 "\\("
4213 "[^" border "]\\|"
4214 "[^" border "]"
4215 body1
4216 "[^" border "]"
4217 "\\)"
4218 "\\3\\)"
4219 "\\([" post "]\\|$\\)"))
4220 (setq org-verbatim-re
4221 (concat "\\([" pre "]\\|^\\)"
4222 "\\("
4223 "\\([" vmarkers "]\\)"
4224 "\\("
4225 "[^" border "]\\|"
4226 "[^" border "]"
4227 body1
4228 "[^" border "]"
4229 "\\)"
4230 "\\3\\)"
4231 "\\([" post "]\\|$\\)")))))
4233 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4234 ;; set this option proved cumbersome. See this message/thread:
4235 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4236 (defvar org-emphasis-regexp-components
4237 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4238 "Components used to build the regular expression for emphasis.
4239 This is a list with five entries. Terminology: In an emphasis string
4240 like \" *strong word* \", we call the initial space PREMATCH, the final
4241 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4242 and \"trong wor\" is the body. The different components in this variable
4243 specify what is allowed/forbidden in each part:
4245 pre Chars allowed as prematch. Beginning of line will be allowed too.
4246 post Chars allowed as postmatch. End of line will be allowed too.
4247 border The chars *forbidden* as border characters.
4248 body-regexp A regexp like \".\" to match a body character. Don't use
4249 non-shy groups here, and don't allow newline here.
4250 newline The maximum number of newlines allowed in an emphasis exp.
4252 You need to reload Org or to restart Emacs after customizing this.")
4254 (defcustom org-emphasis-alist
4255 `(("*" bold)
4256 ("/" italic)
4257 ("_" underline)
4258 ("=" org-verbatim verbatim)
4259 ("~" org-code verbatim)
4260 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4261 "Alist of characters and faces to emphasize text.
4262 Text starting and ending with a special character will be emphasized,
4263 for example *bold*, _underlined_ and /italic/. This variable sets the
4264 marker characters and the face to be used by font-lock for highlighting
4265 in Org-mode Emacs buffers.
4267 You need to reload Org or to restart Emacs after customizing this."
4268 :group 'org-appearance
4269 :set 'org-set-emph-re
4270 :version "24.4"
4271 :package-version '(Org . "8.0")
4272 :type '(repeat
4273 (list
4274 (string :tag "Marker character")
4275 (choice
4276 (face :tag "Font-lock-face")
4277 (plist :tag "Face property list"))
4278 (option (const verbatim)))))
4280 (defvar org-protecting-blocks
4281 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4282 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4283 This is needed for font-lock setup.")
4285 ;;; Miscellaneous options
4287 (defgroup org-completion nil
4288 "Completion in Org-mode."
4289 :tag "Org Completion"
4290 :group 'org)
4292 (defcustom org-completion-use-ido nil
4293 "Non-nil means use ido completion wherever possible.
4294 Note that `ido-mode' must be active for this variable to be relevant.
4295 If you decide to turn this variable on, you might well want to turn off
4296 `org-outline-path-complete-in-steps'.
4297 See also `org-completion-use-iswitchb'."
4298 :group 'org-completion
4299 :type 'boolean)
4301 (defcustom org-completion-use-iswitchb nil
4302 "Non-nil means use iswitchb completion wherever possible.
4303 Note that `iswitchb-mode' must be active for this variable to be relevant.
4304 If you decide to turn this variable on, you might well want to turn off
4305 `org-outline-path-complete-in-steps'.
4306 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4307 :group 'org-completion
4308 :type 'boolean)
4310 (defcustom org-completion-fallback-command 'hippie-expand
4311 "The expansion command called by \\[pcomplete] in normal context.
4312 Normal means, no org-mode-specific context."
4313 :group 'org-completion
4314 :type 'function)
4316 ;;; Functions and variables from their packages
4317 ;; Declared here to avoid compiler warnings
4319 ;; XEmacs only
4320 (defvar outline-mode-menu-heading)
4321 (defvar outline-mode-menu-show)
4322 (defvar outline-mode-menu-hide)
4323 (defvar zmacs-regions) ; XEmacs regions
4325 ;; Emacs only
4326 (defvar mark-active)
4328 ;; Various packages
4329 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4330 (declare-function calendar-forward-day "cal-move" (arg))
4331 (declare-function calendar-goto-date "cal-move" (date))
4332 (declare-function calendar-goto-today "cal-move" ())
4333 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4334 (defvar calc-embedded-close-formula)
4335 (defvar calc-embedded-open-formula)
4336 (declare-function cdlatex-tab "ext:cdlatex" ())
4337 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4338 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4339 (defvar font-lock-unfontify-region-function)
4340 (declare-function iswitchb-read-buffer "iswitchb"
4341 (prompt &optional default require-match start matches-set))
4342 (defvar iswitchb-temp-buflist)
4343 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4344 (defvar org-agenda-tags-todo-honor-ignore-options)
4345 (declare-function org-agenda-skip "org-agenda" ())
4346 (declare-function
4347 org-agenda-format-item "org-agenda"
4348 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4349 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4350 (declare-function org-agenda-change-all-lines "org-agenda"
4351 (newhead hdmarker &optional fixface just-this))
4352 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4353 (declare-function org-agenda-maybe-redo "org-agenda" ())
4354 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4355 (beg end))
4356 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4357 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4358 "org-agenda" (&optional end))
4359 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4360 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4361 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4362 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4363 (declare-function org-indent-mode "org-indent" (&optional arg))
4364 (declare-function parse-time-string "parse-time" (string))
4365 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4366 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4367 (defvar remember-data-file)
4368 (defvar texmathp-why)
4369 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4370 (declare-function table--at-cell-p "table" (position &optional object at-column))
4372 ;;;###autoload
4373 (defun turn-on-orgtbl ()
4374 "Unconditionally turn on `orgtbl-mode'."
4375 (require 'org-table)
4376 (orgtbl-mode 1))
4378 (defun org-at-table-p (&optional table-type)
4379 "Return t if the cursor is inside an org-type table.
4380 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4381 (if org-enable-table-editor
4382 (save-excursion
4383 (beginning-of-line 1)
4384 (looking-at (if table-type org-table-any-line-regexp
4385 org-table-line-regexp)))
4386 nil))
4387 (defsubst org-table-p () (org-at-table-p))
4389 (defun org-at-table.el-p ()
4390 "Return t if and only if we are at a table.el table."
4391 (and (org-at-table-p 'any)
4392 (save-excursion
4393 (goto-char (org-table-begin 'any))
4394 (looking-at org-table1-hline-regexp))))
4396 (defun org-table-recognize-table.el ()
4397 "If there is a table.el table nearby, recognize it and move into it."
4398 (if org-table-tab-recognizes-table.el
4399 (if (org-at-table.el-p)
4400 (progn
4401 (beginning-of-line 1)
4402 (if (looking-at org-table-dataline-regexp)
4404 (if (looking-at org-table1-hline-regexp)
4405 (progn
4406 (beginning-of-line 2)
4407 (if (looking-at org-table-any-border-regexp)
4408 (beginning-of-line -1)))))
4409 (if (re-search-forward "|" (org-table-end t) t)
4410 (progn
4411 (require 'table)
4412 (if (table--at-cell-p (point))
4414 (message "recognizing table.el table...")
4415 (table-recognize-table)
4416 (message "recognizing table.el table...done")))
4417 (error "This should not happen"))
4419 nil)
4420 nil))
4422 (defun org-at-table-hline-p ()
4423 "Return t if the cursor is inside a hline in a table."
4424 (if org-enable-table-editor
4425 (save-excursion
4426 (beginning-of-line 1)
4427 (looking-at org-table-hline-regexp))
4428 nil))
4430 (defun org-table-map-tables (function &optional quietly)
4431 "Apply FUNCTION to the start of all tables in the buffer."
4432 (save-excursion
4433 (save-restriction
4434 (widen)
4435 (goto-char (point-min))
4436 (while (re-search-forward org-table-any-line-regexp nil t)
4437 (unless quietly
4438 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4439 (beginning-of-line 1)
4440 (when (and (looking-at org-table-line-regexp)
4441 ;; Exclude tables in src/example/verbatim/clocktable blocks
4442 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4443 (save-excursion (funcall function))
4444 (or (looking-at org-table-line-regexp)
4445 (forward-char 1)))
4446 (re-search-forward org-table-any-border-regexp nil 1))))
4447 (unless quietly (message "Mapping tables: done")))
4449 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4450 (declare-function org-clock-update-mode-line "org-clock" ())
4451 (declare-function org-resolve-clocks "org-clock"
4452 (&optional also-non-dangling-p prompt last-valid))
4454 (defun org-at-TBLFM-p (&optional pos)
4455 "Return t when point (or POS) is in #+TBLFM line."
4456 (save-excursion
4457 (let ((pos pos)))
4458 (goto-char (or pos (point)))
4459 (beginning-of-line 1)
4460 (looking-at org-TBLFM-regexp)))
4462 (defvar org-clock-start-time)
4463 (defvar org-clock-marker (make-marker)
4464 "Marker recording the last clock-in.")
4465 (defvar org-clock-hd-marker (make-marker)
4466 "Marker recording the last clock-in, but the headline position.")
4467 (defvar org-clock-heading ""
4468 "The heading of the current clock entry.")
4469 (defun org-clock-is-active ()
4470 "Return the buffer where the clock is currently running.
4471 Return nil if no clock is running."
4472 (marker-buffer org-clock-marker))
4474 (defun org-check-running-clock ()
4475 "Check if the current buffer contains the running clock.
4476 If yes, offer to stop it and to save the buffer with the changes."
4477 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4478 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4479 (buffer-name))))
4480 (org-clock-out)
4481 (when (y-or-n-p "Save changed buffer?")
4482 (save-buffer))))
4484 (defun org-clocktable-try-shift (dir n)
4485 "Check if this line starts a clock table, if yes, shift the time block."
4486 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4487 (org-clocktable-shift dir n)))
4489 ;;;###autoload
4490 (defun org-clock-persistence-insinuate ()
4491 "Set up hooks for clock persistence."
4492 (require 'org-clock)
4493 (add-hook 'org-mode-hook 'org-clock-load)
4494 (add-hook 'kill-emacs-hook 'org-clock-save))
4496 (defgroup org-archive nil
4497 "Options concerning archiving in Org-mode."
4498 :tag "Org Archive"
4499 :group 'org-structure)
4501 (defcustom org-archive-location "%s_archive::"
4502 "The location where subtrees should be archived.
4504 The value of this variable is a string, consisting of two parts,
4505 separated by a double-colon. The first part is a filename and
4506 the second part is a headline.
4508 When the filename is omitted, archiving happens in the same file.
4509 %s in the filename will be replaced by the current file
4510 name (without the directory part). Archiving to a different file
4511 is useful to keep archived entries from contributing to the
4512 Org-mode Agenda.
4514 The archived entries will be filed as subtrees of the specified
4515 headline. When the headline is omitted, the subtrees are simply
4516 filed away at the end of the file, as top-level entries. Also in
4517 the heading you can use %s to represent the file name, this can be
4518 useful when using the same archive for a number of different files.
4520 Here are a few examples:
4521 \"%s_archive::\"
4522 If the current file is Projects.org, archive in file
4523 Projects.org_archive, as top-level trees. This is the default.
4525 \"::* Archived Tasks\"
4526 Archive in the current file, under the top-level headline
4527 \"* Archived Tasks\".
4529 \"~/org/archive.org::\"
4530 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4532 \"~/org/archive.org::* From %s\"
4533 Archive in file ~/org/archive.org (absolute path), under headlines
4534 \"From FILENAME\" where file name is the current file name.
4536 \"~/org/datetree.org::datetree/* Finished Tasks\"
4537 The \"datetree/\" string is special, signifying to archive
4538 items to the datetree. Items are placed in either the CLOSED
4539 date of the item, or the current date if there is no CLOSED date.
4540 The heading will be a subentry to the current date. There doesn't
4541 need to be a heading, but there always needs to be a slash after
4542 datetree. For example, to store archived items directly in the
4543 datetree, use \"~/org/datetree.org::datetree/\".
4545 \"basement::** Finished Tasks\"
4546 Archive in file ./basement (relative path), as level 3 trees
4547 below the level 2 heading \"** Finished Tasks\".
4549 You may set this option on a per-file basis by adding to the buffer a
4550 line like
4552 #+ARCHIVE: basement::** Finished Tasks
4554 You may also define it locally for a subtree by setting an ARCHIVE property
4555 in the entry. If such a property is found in an entry, or anywhere up
4556 the hierarchy, it will be used."
4557 :group 'org-archive
4558 :type 'string)
4560 (defcustom org-agenda-skip-archived-trees t
4561 "Non-nil means the agenda will skip any items located in archived trees.
4562 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4563 variable is no longer recommended, you should leave it at the value t.
4564 Instead, use the key `v' to cycle the archives-mode in the agenda."
4565 :group 'org-archive
4566 :group 'org-agenda-skip
4567 :type 'boolean)
4569 (defcustom org-columns-skip-archived-trees t
4570 "Non-nil means ignore archived trees when creating column view."
4571 :group 'org-archive
4572 :group 'org-properties
4573 :type 'boolean)
4575 (defcustom org-cycle-open-archived-trees nil
4576 "Non-nil means `org-cycle' will open archived trees.
4577 An archived tree is a tree marked with the tag ARCHIVE.
4578 When nil, archived trees will stay folded. You can still open them with
4579 normal outline commands like `show-all', but not with the cycling commands."
4580 :group 'org-archive
4581 :group 'org-cycle
4582 :type 'boolean)
4584 (defcustom org-sparse-tree-open-archived-trees nil
4585 "Non-nil means sparse tree construction shows matches in archived trees.
4586 When nil, matches in these trees are highlighted, but the trees are kept in
4587 collapsed state."
4588 :group 'org-archive
4589 :group 'org-sparse-trees
4590 :type 'boolean)
4592 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4593 "The default date type when building a sparse tree.
4594 When this is nil, a date is a scheduled or a deadline timestamp.
4595 Otherwise, these types are allowed:
4597 all: all timestamps
4598 active: only active timestamps (<...>)
4599 inactive: only inactive timestamps (<...)
4600 scheduled: only scheduled timestamps
4601 deadline: only deadline timestamps"
4602 :type '(choice (const :tag "Scheduled or deadline" scheduled-or-deadline)
4603 (const :tag "All timestamps" all)
4604 (const :tag "Only active timestamps" active)
4605 (const :tag "Only inactive timestamps" inactive)
4606 (const :tag "Only scheduled timestamps" scheduled)
4607 (const :tag "Only deadline timestamps" deadline)
4608 (const :tag "Only closed timestamps" closed))
4609 :version "24.3"
4610 :group 'org-sparse-trees)
4612 (defun org-cycle-hide-archived-subtrees (state)
4613 "Re-hide all archived subtrees after a visibility state change."
4614 (when (and (not org-cycle-open-archived-trees)
4615 (not (memq state '(overview folded))))
4616 (save-excursion
4617 (let* ((globalp (memq state '(contents all)))
4618 (beg (if globalp (point-min) (point)))
4619 (end (if globalp (point-max) (org-end-of-subtree t))))
4620 (org-hide-archived-subtrees beg end)
4621 (goto-char beg)
4622 (if (looking-at (concat ".*:" org-archive-tag ":"))
4623 (message "%s" (substitute-command-keys
4624 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4626 (defun org-force-cycle-archived ()
4627 "Cycle subtree even if it is archived."
4628 (interactive)
4629 (setq this-command 'org-cycle)
4630 (let ((org-cycle-open-archived-trees t))
4631 (call-interactively 'org-cycle)))
4633 (defun org-hide-archived-subtrees (beg end)
4634 "Re-hide all archived subtrees after a visibility state change."
4635 (save-excursion
4636 (let* ((re (concat ":" org-archive-tag ":")))
4637 (goto-char beg)
4638 (while (re-search-forward re end t)
4639 (when (org-at-heading-p)
4640 (org-flag-subtree t)
4641 (org-end-of-subtree t))))))
4643 (declare-function outline-end-of-heading "outline" ())
4644 (declare-function outline-flag-region "outline" (from to flag))
4645 (defun org-flag-subtree (flag)
4646 (save-excursion
4647 (org-back-to-heading t)
4648 (outline-end-of-heading)
4649 (outline-flag-region (point)
4650 (progn (org-end-of-subtree t) (point))
4651 flag)))
4653 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4655 ;; Declare Column View Code
4657 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4658 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4659 (declare-function org-columns-compute "org-colview" (property))
4661 ;; Declare ID code
4663 (declare-function org-id-store-link "org-id")
4664 (declare-function org-id-locations-load "org-id")
4665 (declare-function org-id-locations-save "org-id")
4666 (defvar org-id-track-globally)
4668 ;;; Variables for pre-computed regular expressions, all buffer local
4670 (defvar org-todo-regexp nil
4671 "Matches any of the TODO state keywords.")
4672 (make-variable-buffer-local 'org-todo-regexp)
4673 (defvar org-not-done-regexp nil
4674 "Matches any of the TODO state keywords except the last one.")
4675 (make-variable-buffer-local 'org-not-done-regexp)
4676 (defvar org-not-done-heading-regexp nil
4677 "Matches a TODO headline that is not done.")
4678 (make-variable-buffer-local 'org-not-done-regexp)
4679 (defvar org-todo-line-regexp nil
4680 "Matches a headline and puts TODO state into group 2 if present.")
4681 (make-variable-buffer-local 'org-todo-line-regexp)
4682 (defvar org-complex-heading-regexp nil
4683 "Matches a headline and puts everything into groups:
4684 group 1: the stars
4685 group 2: The todo keyword, maybe
4686 group 3: Priority cookie
4687 group 4: True headline
4688 group 5: Tags")
4689 (make-variable-buffer-local 'org-complex-heading-regexp)
4690 (defvar org-complex-heading-regexp-format nil
4691 "Printf format to make regexp to match an exact headline.
4692 This regexp will match the headline of any node which has the
4693 exact headline text that is put into the format, but may have any
4694 TODO state, priority and tags.")
4695 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4696 (defvar org-todo-line-tags-regexp nil
4697 "Matches a headline and puts TODO state into group 2 if present.
4698 Also put tags into group 4 if tags are present.")
4699 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4700 (defvar org-ds-keyword-length 12
4701 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4702 (make-variable-buffer-local 'org-ds-keyword-length)
4703 (defvar org-deadline-regexp nil
4704 "Matches the DEADLINE keyword.")
4705 (make-variable-buffer-local 'org-deadline-regexp)
4706 (defvar org-deadline-time-regexp nil
4707 "Matches the DEADLINE keyword together with a time stamp.")
4708 (make-variable-buffer-local 'org-deadline-time-regexp)
4709 (defvar org-deadline-time-hour-regexp nil
4710 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4711 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4712 (defvar org-deadline-line-regexp nil
4713 "Matches the DEADLINE keyword and the rest of the line.")
4714 (make-variable-buffer-local 'org-deadline-line-regexp)
4715 (defvar org-scheduled-regexp nil
4716 "Matches the SCHEDULED keyword.")
4717 (make-variable-buffer-local 'org-scheduled-regexp)
4718 (defvar org-scheduled-time-regexp nil
4719 "Matches the SCHEDULED keyword together with a time stamp.")
4720 (make-variable-buffer-local 'org-scheduled-time-regexp)
4721 (defvar org-scheduled-time-hour-regexp nil
4722 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4723 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4724 (defvar org-closed-time-regexp nil
4725 "Matches the CLOSED keyword together with a time stamp.")
4726 (make-variable-buffer-local 'org-closed-time-regexp)
4728 (defvar org-keyword-time-regexp nil
4729 "Matches any of the 4 keywords, together with the time stamp.")
4730 (make-variable-buffer-local 'org-keyword-time-regexp)
4731 (defvar org-keyword-time-not-clock-regexp nil
4732 "Matches any of the 3 keywords, together with the time stamp.")
4733 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4734 (defvar org-maybe-keyword-time-regexp nil
4735 "Matches a timestamp, possibly preceded by a keyword.")
4736 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4737 (defvar org-all-time-keywords nil
4738 "List of time keywords.")
4739 (make-variable-buffer-local 'org-all-time-keywords)
4741 (defconst org-plain-time-of-day-regexp
4742 (concat
4743 "\\(\\<[012]?[0-9]"
4744 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4745 "\\(--?"
4746 "\\(\\<[012]?[0-9]"
4747 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4748 "\\)?")
4749 "Regular expression to match a plain time or time range.
4750 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4751 groups carry important information:
4752 0 the full match
4753 1 the first time, range or not
4754 8 the second time, if it is a range.")
4756 (defconst org-plain-time-extension-regexp
4757 (concat
4758 "\\(\\<[012]?[0-9]"
4759 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4760 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4761 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4762 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4763 groups carry important information:
4764 0 the full match
4765 7 hours of duration
4766 9 minutes of duration")
4768 (defconst org-stamp-time-of-day-regexp
4769 (concat
4770 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4771 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4772 "\\(--?"
4773 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4774 "Regular expression to match a timestamp time or time range.
4775 After a match, the following groups carry important information:
4776 0 the full match
4777 1 date plus weekday, for back referencing to make sure both times are on the same day
4778 2 the first time, range or not
4779 4 the second time, if it is a range.")
4781 (defconst org-startup-options
4782 '(("fold" org-startup-folded t)
4783 ("overview" org-startup-folded t)
4784 ("nofold" org-startup-folded nil)
4785 ("showall" org-startup-folded nil)
4786 ("showeverything" org-startup-folded showeverything)
4787 ("content" org-startup-folded content)
4788 ("indent" org-startup-indented t)
4789 ("noindent" org-startup-indented nil)
4790 ("hidestars" org-hide-leading-stars t)
4791 ("showstars" org-hide-leading-stars nil)
4792 ("odd" org-odd-levels-only t)
4793 ("oddeven" org-odd-levels-only nil)
4794 ("align" org-startup-align-all-tables t)
4795 ("noalign" org-startup-align-all-tables nil)
4796 ("inlineimages" org-startup-with-inline-images t)
4797 ("noinlineimages" org-startup-with-inline-images nil)
4798 ("latexpreview" org-startup-with-latex-preview t)
4799 ("nolatexpreview" org-startup-with-latex-preview nil)
4800 ("customtime" org-display-custom-times t)
4801 ("logdone" org-log-done time)
4802 ("lognotedone" org-log-done note)
4803 ("nologdone" org-log-done nil)
4804 ("lognoteclock-out" org-log-note-clock-out t)
4805 ("nolognoteclock-out" org-log-note-clock-out nil)
4806 ("logrepeat" org-log-repeat state)
4807 ("lognoterepeat" org-log-repeat note)
4808 ("logdrawer" org-log-into-drawer t)
4809 ("nologdrawer" org-log-into-drawer nil)
4810 ("logstatesreversed" org-log-states-order-reversed t)
4811 ("nologstatesreversed" org-log-states-order-reversed nil)
4812 ("nologrepeat" org-log-repeat nil)
4813 ("logreschedule" org-log-reschedule time)
4814 ("lognotereschedule" org-log-reschedule note)
4815 ("nologreschedule" org-log-reschedule nil)
4816 ("logredeadline" org-log-redeadline time)
4817 ("lognoteredeadline" org-log-redeadline note)
4818 ("nologredeadline" org-log-redeadline nil)
4819 ("logrefile" org-log-refile time)
4820 ("lognoterefile" org-log-refile note)
4821 ("nologrefile" org-log-refile nil)
4822 ("fninline" org-footnote-define-inline t)
4823 ("nofninline" org-footnote-define-inline nil)
4824 ("fnlocal" org-footnote-section nil)
4825 ("fnauto" org-footnote-auto-label t)
4826 ("fnprompt" org-footnote-auto-label nil)
4827 ("fnconfirm" org-footnote-auto-label confirm)
4828 ("fnplain" org-footnote-auto-label plain)
4829 ("fnadjust" org-footnote-auto-adjust t)
4830 ("nofnadjust" org-footnote-auto-adjust nil)
4831 ("constcgs" constants-unit-system cgs)
4832 ("constSI" constants-unit-system SI)
4833 ("noptag" org-tag-persistent-alist nil)
4834 ("hideblocks" org-hide-block-startup t)
4835 ("nohideblocks" org-hide-block-startup nil)
4836 ("beamer" org-startup-with-beamer-mode t)
4837 ("entitiespretty" org-pretty-entities t)
4838 ("entitiesplain" org-pretty-entities nil))
4839 "Variable associated with STARTUP options for org-mode.
4840 Each element is a list of three items: the startup options (as written
4841 in the #+STARTUP line), the corresponding variable, and the value to set
4842 this variable to if the option is found. An optional forth element PUSH
4843 means to push this value onto the list in the variable.")
4845 (defun org-update-property-plist (key val props)
4846 "Update PROPS with KEY and VAL."
4847 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4848 (key (if appending (substring key 0 (- (length key) 1)) key))
4849 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4850 (previous (cdr (assoc key props))))
4851 (if appending
4852 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4853 (cons (cons key val) remainder))))
4855 (defcustom org-group-tags t
4856 "When non-nil (the default), use group tags.
4857 This can be turned on/off through `org-toggle-tags-groups'."
4858 :group 'org-tags
4859 :group 'org-startup
4860 :type 'boolean)
4862 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4864 (defun org-toggle-tags-groups ()
4865 "Toggle support for group tags.
4866 Support for group tags is controlled by the option
4867 `org-group-tags', which is non-nil by default."
4868 (interactive)
4869 (setq org-group-tags (not org-group-tags))
4870 (cond ((and (derived-mode-p 'org-agenda-mode)
4871 org-group-tags)
4872 (org-agenda-redo))
4873 ((derived-mode-p 'org-mode)
4874 (let ((org-inhibit-startup t)) (org-mode))))
4875 (message "Groups tags support has been turned %s"
4876 (if org-group-tags "on" "off")))
4878 (defun org-set-regexps-and-options-for-tags ()
4879 "Precompute variables used for tags."
4880 (when (derived-mode-p 'org-mode)
4881 (org-set-local 'org-file-tags nil)
4882 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4883 (splitre "[ \t]+")
4884 (start 0)
4885 tags ftags key value)
4886 (save-excursion
4887 (save-restriction
4888 (widen)
4889 (goto-char (point-min))
4890 (while (re-search-forward re nil t)
4891 (setq key (upcase (org-match-string-no-properties 1))
4892 value (org-match-string-no-properties 2))
4893 (if (stringp value) (setq value (org-trim value)))
4894 (cond
4895 ((equal key "TAGS")
4896 (setq tags (append tags (if tags '("\\n") nil)
4897 (org-split-string value splitre))))
4898 ((equal key "FILETAGS")
4899 (when (string-match "\\S-" value)
4900 (setq ftags
4901 (append
4902 ftags
4903 (apply 'append
4904 (mapcar (lambda (x) (org-split-string x ":"))
4905 (org-split-string value)))))))))))
4906 ;; Process the file tags.
4907 (and ftags (org-set-local 'org-file-tags
4908 (mapcar 'org-add-prop-inherited ftags)))
4909 (org-set-local 'org-tag-groups-alist nil)
4910 ;; Process the tags.
4911 (when (and (not tags) org-tag-alist)
4912 (setq tags
4913 (mapcar
4914 (lambda (tg) (cond ((eq (car tg) :startgroup) "{")
4915 ((eq (car tg) :endgroup) "}")
4916 ((eq (car tg) :grouptags) ":")
4917 ((eq (car tg) :newline) "\n")
4918 (t (concat (car tg)
4919 (if (characterp (cdr tg))
4920 (format "(%s)" (char-to-string (cdr tg))) "")))))
4921 org-tag-alist)))
4922 (let (e tgs g)
4923 (while (setq e (pop tags))
4924 (cond
4925 ((equal e "{")
4926 (progn (push '(:startgroup) tgs)
4927 (when (equal (nth 1 tags) ":")
4928 (push (list (replace-regexp-in-string
4929 "(.+)$" "" (nth 0 tags)))
4930 org-tag-groups-alist)
4931 (setq g 0))))
4932 ((equal e ":") (push '(:grouptags) tgs))
4933 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4934 ((equal e "\\n") (push '(:newline) tgs))
4935 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4936 (push (cons (match-string 1 e)
4937 (string-to-char (match-string 2 e))) tgs)
4938 (if (and g (> g 0))
4939 (setcar org-tag-groups-alist
4940 (append (car org-tag-groups-alist)
4941 (list (match-string 1 e)))))
4942 (if g (setq g (1+ g))))
4943 (t (push (list e) tgs)
4944 (if (and g (> g 0))
4945 (setcar org-tag-groups-alist
4946 (append (car org-tag-groups-alist) (list e))))
4947 (if g (setq g (1+ g))))))
4948 (org-set-local 'org-tag-alist nil)
4949 (while (setq e (pop tgs))
4950 (or (and (stringp (car e))
4951 (assoc (car e) org-tag-alist))
4952 (push e org-tag-alist)))
4953 ;; Return a list with tag variables
4954 (list org-file-tags org-tag-alist org-tag-groups-alist)))))
4956 (defvar org-ota nil)
4957 (defun org-set-regexps-and-options ()
4958 "Precompute regular expressions used in the current buffer."
4959 (when (derived-mode-p 'org-mode)
4960 (org-set-local 'org-todo-kwd-alist nil)
4961 (org-set-local 'org-todo-key-alist nil)
4962 (org-set-local 'org-todo-key-trigger nil)
4963 (org-set-local 'org-todo-keywords-1 nil)
4964 (org-set-local 'org-done-keywords nil)
4965 (org-set-local 'org-todo-heads nil)
4966 (org-set-local 'org-todo-sets nil)
4967 (org-set-local 'org-todo-log-states nil)
4968 (org-set-local 'org-file-properties nil)
4969 (let ((re (org-make-options-regexp
4970 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
4971 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4972 "SETUPFILE" "OPTIONS")
4973 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4974 (splitre "[ \t]+")
4975 (scripts org-use-sub-superscripts)
4976 kwds kws0 kwsa key log value cat arch const links hw dws
4977 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
4978 (start 0))
4979 (save-excursion
4980 (save-restriction
4981 (widen)
4982 (goto-char (point-min))
4983 (while
4984 (or (and
4985 ext-setup-or-nil
4986 (not org-ota)
4987 (let (ret)
4988 (with-temp-buffer
4989 (insert ext-setup-or-nil)
4990 (let ((major-mode 'org-mode) org-ota)
4991 (setq ret (save-match-data
4992 (org-set-regexps-and-options-for-tags)))))
4993 ;; Append setupfile tags to existing tags
4994 (setq org-ota t)
4995 (setq org-file-tags
4996 (delq nil (append org-file-tags (nth 0 ret)))
4997 org-tag-alist
4998 (delq nil (append org-tag-alist (nth 1 ret)))
4999 org-tag-groups-alist
5000 (delq nil (append org-tag-groups-alist (nth 2 ret))))))
5001 (and ext-setup-or-nil
5002 (string-match re ext-setup-or-nil start)
5003 (setq start (match-end 0)))
5004 (and (setq ext-setup-or-nil nil start 0)
5005 (re-search-forward re nil t)))
5006 (setq key (upcase (match-string 1 ext-setup-or-nil))
5007 value (org-match-string-no-properties 2 ext-setup-or-nil))
5008 (if (stringp value) (setq value (org-trim value)))
5009 (cond
5010 ((equal key "CATEGORY")
5011 (setq cat value))
5012 ((member key '("SEQ_TODO" "TODO"))
5013 (push (cons 'sequence (org-split-string value splitre)) kwds))
5014 ((equal key "TYP_TODO")
5015 (push (cons 'type (org-split-string value splitre)) kwds))
5016 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
5017 ;; general TODO-like setup
5018 (push (cons (intern (downcase (match-string 1 key)))
5019 (org-split-string value splitre)) kwds))
5020 ((equal key "COLUMNS")
5021 (org-set-local 'org-columns-default-format value))
5022 ((equal key "LINK")
5023 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5024 (push (cons (match-string 1 value)
5025 (org-trim (match-string 2 value)))
5026 links)))
5027 ((equal key "PRIORITIES")
5028 (setq prio (org-split-string value " +")))
5029 ((equal key "PROPERTY")
5030 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
5031 (setq props (org-update-property-plist (match-string 1 value)
5032 (match-string 2 value)
5033 props))))
5034 ((equal key "CONSTANTS")
5035 (org-table-set-constants))
5036 ((equal key "STARTUP")
5037 (let ((opts (org-split-string value splitre))
5038 l var val)
5039 (while (setq l (pop opts))
5040 (when (setq l (assoc l org-startup-options))
5041 (setq var (nth 1 l) val (nth 2 l))
5042 (if (not (nth 3 l))
5043 (set (make-local-variable var) val)
5044 (if (not (listp (symbol-value var)))
5045 (set (make-local-variable var) nil))
5046 (set (make-local-variable var) (symbol-value var))
5047 (add-to-list var val))))))
5048 ((equal key "ARCHIVE")
5049 (setq arch value)
5050 (remove-text-properties 0 (length arch)
5051 '(face t fontified t) arch))
5052 ((equal key "OPTIONS")
5053 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
5054 (setq scripts (read (match-string 2 value)))))
5055 ((and (equal key "SETUPFILE")
5056 ;; Prevent checking in Gnus messages
5057 (not buffer-read-only))
5058 (setq setup-contents (org-file-contents
5059 (expand-file-name
5060 (org-remove-double-quotes value))
5061 'noerror))
5062 (if (not ext-setup-or-nil)
5063 (setq ext-setup-or-nil setup-contents start 0)
5064 (setq ext-setup-or-nil
5065 (concat (substring ext-setup-or-nil 0 start)
5066 "\n" setup-contents "\n"
5067 (substring ext-setup-or-nil start)))))))
5068 ;; search for property blocks
5069 (goto-char (point-min))
5070 (while (re-search-forward org-block-regexp nil t)
5071 (when (equal "PROPERTY" (upcase (match-string 1)))
5072 (setq value (replace-regexp-in-string
5073 "[\n\r]" " " (match-string 4)))
5074 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
5075 (setq props (org-update-property-plist (match-string 1 value)
5076 (match-string 2 value)
5077 props)))))))
5078 (org-set-local 'org-use-sub-superscripts scripts)
5079 (when cat
5080 (org-set-local 'org-category (intern cat))
5081 (push (cons "CATEGORY" cat) props))
5082 (when prio
5083 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
5084 (setq prio (mapcar 'string-to-char prio))
5085 (org-set-local 'org-highest-priority (nth 0 prio))
5086 (org-set-local 'org-lowest-priority (nth 1 prio))
5087 (org-set-local 'org-default-priority (nth 2 prio)))
5088 (and props (org-set-local 'org-file-properties (nreverse props)))
5089 (and arch (org-set-local 'org-archive-location arch))
5090 (and links (setq org-link-abbrev-alist-local (nreverse links)))
5091 ;; Process the TODO keywords
5092 (unless kwds
5093 ;; Use the global values as if they had been given locally.
5094 (setq kwds (default-value 'org-todo-keywords))
5095 (if (stringp (car kwds))
5096 (setq kwds (list (cons org-todo-interpretation
5097 (default-value 'org-todo-keywords)))))
5098 (setq kwds (reverse kwds)))
5099 (setq kwds (nreverse kwds))
5100 (let (inter kws kw)
5101 (while (setq kws (pop kwds))
5102 (let ((kws (or
5103 (run-hook-with-args-until-success
5104 'org-todo-setup-filter-hook kws)
5105 kws)))
5106 (setq inter (pop kws) sep (member "|" kws)
5107 kws0 (delete "|" (copy-sequence kws))
5108 kwsa nil
5109 kws1 (mapcar
5110 (lambda (x)
5111 ;; 1 2
5112 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
5113 (progn
5114 (setq kw (match-string 1 x)
5115 key (and (match-end 2) (match-string 2 x))
5116 log (org-extract-log-state-settings x))
5117 (push (cons kw (and key (string-to-char key))) kwsa)
5118 (and log (push log org-todo-log-states))
5120 (error "Invalid TODO keyword %s" x)))
5121 kws0)
5122 kwsa (if kwsa (append '((:startgroup))
5123 (nreverse kwsa)
5124 '((:endgroup))))
5125 hw (car kws1)
5126 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
5127 tail (list inter hw (car dws) (org-last dws))))
5128 (add-to-list 'org-todo-heads hw 'append)
5129 (push kws1 org-todo-sets)
5130 (setq org-done-keywords (append org-done-keywords dws nil))
5131 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
5132 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
5133 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
5134 (setq org-todo-sets (nreverse org-todo-sets)
5135 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5136 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
5137 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
5138 ;; Compute the regular expressions and other local variables.
5139 ;; Using `org-outline-regexp-bol' would complicate them much,
5140 ;; because of the fixed white space at the end of that string.
5141 (if (not org-done-keywords)
5142 (setq org-done-keywords (and org-todo-keywords-1
5143 (list (org-last org-todo-keywords-1)))))
5144 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5145 (length org-scheduled-string)
5146 (length org-clock-string)
5147 (length org-closed-string)))
5148 org-not-done-keywords
5149 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5150 org-todo-regexp
5151 (concat "\\("
5152 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5153 "\\)")
5154 org-not-done-regexp
5155 (concat "\\("
5156 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5157 "\\)")
5158 org-not-done-heading-regexp
5159 (format org-heading-keyword-regexp-format org-not-done-regexp)
5160 org-todo-line-regexp
5161 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5162 org-complex-heading-regexp
5163 (concat "^\\(\\*+\\)"
5164 "\\(?: +" org-todo-regexp "\\)?"
5165 "\\(?: +\\(\\[#.\\]\\)\\)?"
5166 "\\(?: +\\(.*?\\)\\)??"
5167 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5168 "[ \t]*$")
5169 org-complex-heading-regexp-format
5170 (concat "^\\(\\*+\\)"
5171 "\\(?: +" org-todo-regexp "\\)?"
5172 "\\(?: +\\(\\[#.\\]\\)\\)?"
5173 "\\(?: +"
5174 ;; Stats cookies can be stuck to body.
5175 "\\(?:\\[[0-9%%/]+\\] *\\)?"
5176 "\\(%s\\)"
5177 "\\(?: *\\[[0-9%%/]+\\]\\)?"
5178 "\\)"
5179 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5180 "[ \t]*$")
5181 org-todo-line-tags-regexp
5182 (concat "^\\(\\*+\\)"
5183 "\\(?: +" org-todo-regexp "\\)?"
5184 "\\(?: +\\(.*?\\)\\)??"
5185 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5186 "[ \t]*$")
5187 org-deadline-regexp (concat "\\<" org-deadline-string)
5188 org-deadline-time-regexp
5189 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5190 org-deadline-time-hour-regexp
5191 (concat "\\<" org-deadline-string
5192 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5193 org-deadline-line-regexp
5194 (concat "\\<\\(" org-deadline-string "\\).*")
5195 org-scheduled-regexp
5196 (concat "\\<" org-scheduled-string)
5197 org-scheduled-time-regexp
5198 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5199 org-scheduled-time-hour-regexp
5200 (concat "\\<" org-scheduled-string
5201 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5202 org-closed-time-regexp
5203 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5204 org-keyword-time-regexp
5205 (concat "\\<\\(" org-scheduled-string
5206 "\\|" org-deadline-string
5207 "\\|" org-closed-string
5208 "\\|" org-clock-string "\\)"
5209 " *[[<]\\([^]>]+\\)[]>]")
5210 org-keyword-time-not-clock-regexp
5211 (concat "\\<\\(" org-scheduled-string
5212 "\\|" org-deadline-string
5213 "\\|" org-closed-string
5214 "\\)"
5215 " *[[<]\\([^]>]+\\)[]>]")
5216 org-maybe-keyword-time-regexp
5217 (concat "\\(\\<\\(" org-scheduled-string
5218 "\\|" org-deadline-string
5219 "\\|" org-closed-string
5220 "\\|" org-clock-string "\\)\\)?"
5221 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5222 org-all-time-keywords
5223 (mapcar (lambda (w) (substring w 0 -1))
5224 (list org-scheduled-string org-deadline-string
5225 org-clock-string org-closed-string)))
5226 (setq org-ota nil)
5227 (org-compute-latex-and-related-regexp))))
5229 (defun org-file-contents (file &optional noerror)
5230 "Return the contents of FILE, as a string."
5231 (if (and file (file-readable-p file))
5232 (with-temp-buffer
5233 (insert-file-contents file)
5234 (buffer-string))
5235 (funcall (if noerror #'message #'error)
5236 "Cannot read file \"%s\"%s"
5237 file
5238 (let ((from (buffer-file-name (buffer-base-buffer))))
5239 (if from (concat " (referenced in file \"" from "\")") "")))))
5241 (defun org-extract-log-state-settings (x)
5242 "Extract the log state setting from a TODO keyword string.
5243 This will extract info from a string like \"WAIT(w@/!)\"."
5244 (let (kw key log1 log2)
5245 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5246 (setq kw (match-string 1 x)
5247 key (and (match-end 2) (match-string 2 x))
5248 log1 (and (match-end 3) (match-string 3 x))
5249 log2 (and (match-end 4) (match-string 4 x)))
5250 (and (or log1 log2)
5251 (list kw
5252 (and log1 (if (equal log1 "!") 'time 'note))
5253 (and log2 (if (equal log2 "!") 'time 'note)))))))
5255 (defun org-remove-keyword-keys (list)
5256 "Remove a pair of parenthesis at the end of each string in LIST."
5257 (mapcar (lambda (x)
5258 (if (string-match "(.*)$" x)
5259 (substring x 0 (match-beginning 0))
5261 list))
5263 (defun org-assign-fast-keys (alist)
5264 "Assign fast keys to a keyword-key alist.
5265 Respect keys that are already there."
5266 (let (new e (alt ?0))
5267 (while (setq e (pop alist))
5268 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5269 (cdr e)) ;; Key already assigned.
5270 (push e new)
5271 (let ((clist (string-to-list (downcase (car e))))
5272 (used (append new alist)))
5273 (when (= (car clist) ?@)
5274 (pop clist))
5275 (while (and clist (rassoc (car clist) used))
5276 (pop clist))
5277 (unless clist
5278 (while (rassoc alt used)
5279 (incf alt)))
5280 (push (cons (car e) (or (car clist) alt)) new))))
5281 (nreverse new)))
5283 ;;; Some variables used in various places
5285 (defvar org-window-configuration nil
5286 "Used in various places to store a window configuration.")
5287 (defvar org-selected-window nil
5288 "Used in various places to store a window configuration.")
5289 (defvar org-finish-function nil
5290 "Function to be called when `C-c C-c' is used.
5291 This is for getting out of special buffers like capture.")
5294 ;; FIXME: Occasionally check by commenting these, to make sure
5295 ;; no other functions uses these, forgetting to let-bind them.
5296 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5297 (defvar org-last-state)
5298 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5300 ;; Defined somewhere in this file, but used before definition.
5301 (defvar org-entities) ;; defined in org-entities.el
5302 (defvar org-struct-menu)
5303 (defvar org-org-menu)
5304 (defvar org-tbl-menu)
5306 ;;;; Define the Org-mode
5308 ;; We use a before-change function to check if a table might need
5309 ;; an update.
5310 (defvar org-table-may-need-update t
5311 "Indicates that a table might need an update.
5312 This variable is set by `org-before-change-function'.
5313 `org-table-align' sets it back to nil.")
5314 (defun org-before-change-function (beg end)
5315 "Every change indicates that a table might need an update."
5316 (setq org-table-may-need-update t))
5317 (defvar org-mode-map)
5318 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5319 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5320 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5321 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5322 (defvar org-table-buffer-is-an nil)
5324 (defvar bidi-paragraph-direction)
5325 (defvar buffer-face-mode-face)
5327 (require 'outline)
5328 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5329 (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"))
5330 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5332 ;; Other stuff we need.
5333 (require 'time-date)
5334 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5335 (require 'easymenu)
5336 (require 'overlay)
5338 ;; (require 'org-macs) moved higher up in the file before it is first used
5339 (require 'org-entities)
5340 ;; (require 'org-compat) moved higher up in the file before it is first used
5341 (require 'org-faces)
5342 (require 'org-list)
5343 (require 'org-pcomplete)
5344 (require 'org-src)
5345 (require 'org-footnote)
5346 (require 'org-macro)
5348 ;; babel
5349 (require 'ob)
5351 ;;;###autoload
5352 (define-derived-mode org-mode outline-mode "Org"
5353 "Outline-based notes management and organizer, alias
5354 \"Carsten's outline-mode for keeping track of everything.\"
5356 Org-mode develops organizational tasks around a NOTES file which
5357 contains information about projects as plain text. Org-mode is
5358 implemented on top of outline-mode, which is ideal to keep the content
5359 of large files well structured. It supports ToDo items, deadlines and
5360 time stamps, which magically appear in the diary listing of the Emacs
5361 calendar. Tables are easily created with a built-in table editor.
5362 Plain text URL-like links connect to websites, emails (VM), Usenet
5363 messages (Gnus), BBDB entries, and any files related to the project.
5364 For printing and sharing of notes, an Org-mode file (or a part of it)
5365 can be exported as a structured ASCII or HTML file.
5367 The following commands are available:
5369 \\{org-mode-map}"
5371 ;; Get rid of Outline menus, they are not needed
5372 ;; Need to do this here because define-derived-mode sets up
5373 ;; the keymap so late. Still, it is a waste to call this each time
5374 ;; we switch another buffer into org-mode.
5375 (if (featurep 'xemacs)
5376 (when (boundp 'outline-mode-menu-heading)
5377 ;; Assume this is Greg's port, it uses easymenu
5378 (easy-menu-remove outline-mode-menu-heading)
5379 (easy-menu-remove outline-mode-menu-show)
5380 (easy-menu-remove outline-mode-menu-hide))
5381 (define-key org-mode-map [menu-bar headings] 'undefined)
5382 (define-key org-mode-map [menu-bar hide] 'undefined)
5383 (define-key org-mode-map [menu-bar show] 'undefined))
5385 (org-load-modules-maybe)
5386 (easy-menu-add org-org-menu)
5387 (easy-menu-add org-tbl-menu)
5388 (org-install-agenda-files-menu)
5389 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5390 (add-to-invisibility-spec '(org-cwidth))
5391 (add-to-invisibility-spec '(org-hide-block . t))
5392 (when (featurep 'xemacs)
5393 (org-set-local 'line-move-ignore-invisible t))
5394 (org-set-local 'outline-regexp org-outline-regexp)
5395 (org-set-local 'outline-level 'org-outline-level)
5396 (setq bidi-paragraph-direction 'left-to-right)
5397 (when (and org-ellipsis
5398 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5399 (fboundp 'make-glyph-code))
5400 (unless org-display-table
5401 (setq org-display-table (make-display-table)))
5402 (set-display-table-slot
5403 org-display-table 4
5404 (vconcat (mapcar
5405 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5406 org-ellipsis)))
5407 (if (stringp org-ellipsis) org-ellipsis "..."))))
5408 (setq buffer-display-table org-display-table))
5409 (org-set-regexps-and-options-for-tags)
5410 (org-set-regexps-and-options)
5411 (org-set-font-lock-defaults)
5412 (when (and org-tag-faces (not org-tags-special-faces-re))
5413 ;; tag faces set outside customize.... force initialization.
5414 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5415 ;; Calc embedded
5416 (org-set-local 'calc-embedded-open-mode "# ")
5417 ;; Modify a few syntax entries
5418 (modify-syntax-entry ?@ "w")
5419 (modify-syntax-entry ?\" "\"")
5420 (modify-syntax-entry ?\\ "_")
5421 (modify-syntax-entry ?~ "_")
5422 (if org-startup-truncated (setq truncate-lines t))
5423 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5424 (org-set-local 'font-lock-unfontify-region-function
5425 'org-unfontify-region)
5426 ;; Activate before-change-function
5427 (org-set-local 'org-table-may-need-update t)
5428 (org-add-hook 'before-change-functions 'org-before-change-function nil
5429 'local)
5430 ;; Check for running clock before killing a buffer
5431 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5432 ;; Initialize macros templates.
5433 (org-macro-initialize-templates)
5434 ;; Initialize radio targets.
5435 (org-update-radio-target-regexp)
5436 ;; Indentation.
5437 (org-set-local 'indent-line-function 'org-indent-line)
5438 (org-set-local 'indent-region-function 'org-indent-region)
5439 ;; Filling and auto-filling.
5440 (org-setup-filling)
5441 ;; Comments.
5442 (org-setup-comments-handling)
5443 ;; Initialize cache.
5444 (org-element-cache-reset)
5445 ;; Beginning/end of defun
5446 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5447 (org-set-local 'end-of-defun-function 'org-forward-element)
5448 ;; Next error for sparse trees
5449 (org-set-local 'next-error-function 'org-occur-next-match)
5450 ;; Make sure dependence stuff works reliably, even for users who set it
5451 ;; too late :-(
5452 (if org-enforce-todo-dependencies
5453 (add-hook 'org-blocker-hook
5454 'org-block-todo-from-children-or-siblings-or-parent)
5455 (remove-hook 'org-blocker-hook
5456 'org-block-todo-from-children-or-siblings-or-parent))
5457 (if org-enforce-todo-checkbox-dependencies
5458 (add-hook 'org-blocker-hook
5459 'org-block-todo-from-checkboxes)
5460 (remove-hook 'org-blocker-hook
5461 'org-block-todo-from-checkboxes))
5463 ;; Align options lines
5464 (org-set-local
5465 'align-mode-rules-list
5466 '((org-in-buffer-settings
5467 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5468 (modes . '(org-mode)))))
5470 ;; Imenu
5471 (org-set-local 'imenu-create-index-function
5472 'org-imenu-get-tree)
5474 ;; Make isearch reveal context
5475 (if (or (featurep 'xemacs)
5476 (not (boundp 'outline-isearch-open-invisible-function)))
5477 ;; Emacs 21 and XEmacs make use of the hook
5478 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5479 ;; Emacs 22 deals with this through a special variable
5480 (org-set-local 'outline-isearch-open-invisible-function
5481 (lambda (&rest ignore) (org-show-context 'isearch)))
5482 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5484 ;; Setup the pcomplete hooks
5485 (set (make-local-variable 'pcomplete-command-completion-function)
5486 'org-pcomplete-initial)
5487 (set (make-local-variable 'pcomplete-command-name-function)
5488 'org-command-at-point)
5489 (set (make-local-variable 'pcomplete-default-completion-function)
5490 'ignore)
5491 (set (make-local-variable 'pcomplete-parse-arguments-function)
5492 'org-parse-arguments)
5493 (set (make-local-variable 'pcomplete-termination-string) "")
5494 (when (>= emacs-major-version 23)
5495 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5497 ;; If empty file that did not turn on org-mode automatically, make it to.
5498 (if (and org-insert-mode-line-in-empty-file
5499 (org-called-interactively-p 'any)
5500 (= (point-min) (point-max)))
5501 (insert "# -*- mode: org -*-\n\n"))
5502 (unless org-inhibit-startup
5503 (org-unmodified
5504 (and org-startup-with-beamer-mode (org-beamer-mode))
5505 (when org-startup-align-all-tables
5506 (org-table-map-tables 'org-table-align 'quietly))
5507 (when org-startup-with-inline-images
5508 (org-display-inline-images))
5509 (when org-startup-with-latex-preview
5510 (org-preview-latex-fragment))
5511 (unless org-inhibit-startup-visibility-stuff
5512 (org-set-startup-visibility))))
5513 ;; Try to set org-hide correctly
5514 (let ((foreground (org-find-invisible-foreground)))
5515 (if foreground
5516 (set-face-foreground 'org-hide 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.2.6" . "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" "file+emacs"
5591 "file+sys" "news" "shell" "elisp" "doi" "message"
5592 "help"))
5593 (defvar org-link-types-re nil
5594 "Matches a link that has a url-like prefix like \"http:\"")
5595 (defvar org-link-re-with-space nil
5596 "Matches a link with spaces, optional angular brackets around it.")
5597 (defvar org-link-re-with-space2 nil
5598 "Matches a link with spaces, optional angular brackets around it.")
5599 (defvar org-link-re-with-space3 nil
5600 "Matches a link with spaces, only for internal part in bracket links.")
5601 (defvar org-angle-link-re nil
5602 "Matches link with angular brackets, spaces are allowed.")
5603 (defvar org-plain-link-re nil
5604 "Matches plain link, without spaces.")
5605 (defvar org-bracket-link-regexp nil
5606 "Matches a link in double brackets.")
5607 (defvar org-bracket-link-analytic-regexp nil
5608 "Regular expression used to analyze links.
5609 Here is what the match groups contain after a match:
5610 1: http:
5611 2: http
5612 3: path
5613 4: [desc]
5614 5: desc")
5615 (defvar org-bracket-link-analytic-regexp++ nil
5616 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5617 (defvar org-any-link-re nil
5618 "Regular expression matching any link.")
5620 (defconst org-match-sexp-depth 3
5621 "Number of stacked braces for sub/superscript matching.")
5623 (defun org-create-multibrace-regexp (left right n)
5624 "Create a regular expression which will match a balanced sexp.
5625 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5626 as single character strings.
5627 The regexp returned will match the entire expression including the
5628 delimiters. It will also define a single group which contains the
5629 match except for the outermost delimiters. The maximum depth of
5630 stacked delimiters is N. Escaping delimiters is not possible."
5631 (let* ((nothing (concat "[^" left right "]*?"))
5632 (or "\\|")
5633 (re nothing)
5634 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5635 (while (> n 1)
5636 (setq n (1- n)
5637 re (concat re or next)
5638 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5639 (concat left "\\(" re "\\)" right)))
5641 (defconst org-match-substring-regexp
5642 (concat
5643 "\\(\\S-\\)\\([_^]\\)\\("
5644 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5645 "\\|"
5646 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5647 "\\|"
5648 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5649 "The regular expression matching a sub- or superscript.")
5651 (defconst org-match-substring-with-braces-regexp
5652 (concat
5653 "\\(\\S-\\)\\([_^]\\)"
5654 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
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 (let* ((border (char-after (match-beginning 3)))
5723 (bre (regexp-quote (char-to-string border))))
5724 (if (and (not (= border (char-after (match-beginning 4))))
5725 (not (save-match-data
5726 (string-match (concat bre ".*" bre)
5727 (replace-regexp-in-string
5728 "\n" " "
5729 (substring (match-string 2) 1 -1))))))
5730 (progn
5731 (setq rtn t)
5732 (setq a (assoc (match-string 3) org-emphasis-alist))
5733 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5734 'face
5735 (nth 1 a))
5736 (and (nth 2 a)
5737 (org-remove-flyspell-overlays-in
5738 (match-beginning 0) (match-end 0)))
5739 (add-text-properties (match-beginning 2) (match-end 2)
5740 '(font-lock-multiline t org-emphasis t))
5741 (when org-hide-emphasis-markers
5742 (add-text-properties (match-end 4) (match-beginning 5)
5743 '(invisible org-link))
5744 (add-text-properties (match-beginning 3) (match-end 3)
5745 '(invisible org-link))))))
5746 (goto-char (1+ (match-beginning 0))))
5747 rtn))
5749 (defun org-emphasize (&optional char)
5750 "Insert or change an emphasis, i.e. a font like bold or italic.
5751 If there is an active region, change that region to a new emphasis.
5752 If there is no region, just insert the marker characters and position
5753 the cursor between them.
5754 CHAR should be the marker character. If it is a space, it means to
5755 remove the emphasis of the selected region.
5756 If CHAR is not given (for example in an interactive call) it will be
5757 prompted for."
5758 (interactive)
5759 (let ((erc org-emphasis-regexp-components)
5760 (prompt "")
5761 (string "") beg end move c s)
5762 (if (org-region-active-p)
5763 (setq beg (region-beginning) end (region-end)
5764 string (buffer-substring beg end))
5765 (setq move t))
5767 (unless char
5768 (message "Emphasis marker or tag: [%s]"
5769 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5770 (setq char (read-char-exclusive)))
5771 (if (equal char ?\ )
5772 (setq s "" move nil)
5773 (unless (assoc (char-to-string char) org-emphasis-alist)
5774 (user-error "No such emphasis marker: \"%c\"" char))
5775 (setq s (char-to-string char)))
5776 (while (and (> (length string) 1)
5777 (equal (substring string 0 1) (substring string -1))
5778 (assoc (substring string 0 1) org-emphasis-alist))
5779 (setq string (substring string 1 -1)))
5780 (setq string (concat s string s))
5781 (if beg (delete-region beg end))
5782 (unless (or (bolp)
5783 (string-match (concat "[" (nth 0 erc) "\n]")
5784 (char-to-string (char-before (point)))))
5785 (insert " "))
5786 (unless (or (eobp)
5787 (string-match (concat "[" (nth 1 erc) "\n]")
5788 (char-to-string (char-after (point)))))
5789 (insert " ") (backward-char 1))
5790 (insert string)
5791 (and move (backward-char 1))))
5793 (defconst org-nonsticky-props
5794 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5796 (defsubst org-rear-nonsticky-at (pos)
5797 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5799 (defun org-activate-plain-links (limit)
5800 "Run through the buffer and add overlays to links."
5801 (let (f hl)
5802 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5803 (not (org-in-src-block-p)))
5804 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5805 (setq f (get-text-property (match-beginning 0) 'face))
5806 (setq hl (org-match-string-no-properties 0))
5807 (if (or (eq f 'org-tag)
5808 (and (listp f) (memq 'org-tag f)))
5810 (add-text-properties (match-beginning 0) (match-end 0)
5811 (list 'mouse-face 'highlight
5812 'face 'org-link
5813 'htmlize-link `(:uri ,hl)
5814 'keymap org-mouse-map))
5815 (org-rear-nonsticky-at (match-end 0)))
5816 t)))
5818 (defun org-activate-code (limit)
5819 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5820 (progn
5821 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5822 (remove-text-properties (match-beginning 0) (match-end 0)
5823 '(display t invisible t intangible t))
5824 t)))
5826 (defcustom org-src-fontify-natively t
5827 "When non-nil, fontify code in code blocks."
5828 :type 'boolean
5829 :version "24.4"
5830 :package-version '(Org . "8.3")
5831 :group 'org-appearance
5832 :group 'org-babel)
5834 (defcustom org-allow-promoting-top-level-subtree nil
5835 "When non-nil, allow promoting a top level subtree.
5836 The leading star of the top level headline will be replaced
5837 by a #."
5838 :type 'boolean
5839 :version "24.1"
5840 :group 'org-appearance)
5842 (defun org-fontify-meta-lines-and-blocks (limit)
5843 (condition-case nil
5844 (org-fontify-meta-lines-and-blocks-1 limit)
5845 (error (message "org-mode fontification error"))))
5847 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5848 "Fontify #+ lines and blocks."
5849 (let ((case-fold-search t))
5850 (if (re-search-forward
5851 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5852 limit t)
5853 (let ((beg (match-beginning 0))
5854 (block-start (match-end 0))
5855 (block-end nil)
5856 (lang (match-string 7))
5857 (beg1 (line-beginning-position 2))
5858 (dc1 (downcase (match-string 2)))
5859 (dc3 (downcase (match-string 3)))
5860 end end1 quoting block-type ovl)
5861 (cond
5862 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5863 ;; a single line of backend-specific content
5864 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5865 (remove-text-properties (match-beginning 0) (match-end 0)
5866 '(display t invisible t intangible t))
5867 (add-text-properties (match-beginning 1) (match-end 3)
5868 '(font-lock-fontified t face org-meta-line))
5869 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5870 '(font-lock-fontified t face org-block))
5871 ; for backend-specific code
5873 ((and (match-end 4) (equal dc3 "+begin"))
5874 ;; Truly a block
5875 (setq block-type (downcase (match-string 5))
5876 quoting (member block-type org-protecting-blocks))
5877 (when (re-search-forward
5878 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5879 nil t) ;; on purpose, we look further than LIMIT
5880 (setq end (min (point-max) (match-end 0))
5881 end1 (min (point-max) (1- (match-beginning 0))))
5882 (setq block-end (match-beginning 0))
5883 (when quoting
5884 (org-remove-flyspell-overlays-in beg1 end1)
5885 (remove-text-properties beg end
5886 '(display t invisible t intangible t)))
5887 (add-text-properties
5888 beg end '(font-lock-fontified t font-lock-multiline t))
5889 (add-text-properties beg beg1 '(face org-meta-line))
5890 (org-remove-flyspell-overlays-in beg beg1)
5891 (add-text-properties ; For end_src
5892 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5893 (org-remove-flyspell-overlays-in end1 end)
5894 (cond
5895 ((and lang (not (string= lang "")) org-src-fontify-natively)
5896 (org-src-font-lock-fontify-block lang block-start block-end)
5897 ;; remove old background overlays
5898 (mapc (lambda (ov)
5899 (if (eq (overlay-get ov 'face) 'org-block-background)
5900 (delete-overlay ov)))
5901 (overlays-at (/ (+ beg1 block-end) 2)))
5902 ;; add a background overlay
5903 (setq ovl (make-overlay beg1 block-end))
5904 (overlay-put ovl 'face 'org-block-background)
5905 (overlay-put ovl 'evaporate t)) ; make it go away when empty
5906 (quoting
5907 (add-text-properties beg1 (min (point-max) (1+ end1))
5908 '(face org-block))) ; end of source block
5909 ((not org-fontify-quote-and-verse-blocks))
5910 ((string= block-type "quote")
5911 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5912 ((string= block-type "verse")
5913 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5914 (add-text-properties beg beg1 '(face org-block-begin-line))
5915 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5916 '(face org-block-end-line))
5918 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5919 (org-remove-flyspell-overlays-in
5920 (match-beginning 0)
5921 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5922 (add-text-properties
5923 beg (match-end 3)
5924 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5925 '(font-lock-fontified t invisible t)
5926 '(font-lock-fontified t face org-document-info-keyword)))
5927 (add-text-properties
5928 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5929 (if (string-equal dc1 "+title:")
5930 '(font-lock-fontified t face org-document-title)
5931 '(font-lock-fontified t face org-document-info))))
5932 ((or (equal dc1 "+results")
5933 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5934 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5935 "+call:" "+header:" "+headers:" "+name:"))
5936 (and (match-end 4) (equal dc3 "+attr")))
5937 (org-remove-flyspell-overlays-in
5938 (match-beginning 0)
5939 (if (equal "+caption:" dc1) (match-end 2) (match-end 0)))
5940 (add-text-properties
5941 beg (match-end 0)
5942 '(font-lock-fontified t face org-meta-line))
5944 ((member dc3 '(" " ""))
5945 (org-remove-flyspell-overlays-in beg (match-end 0))
5946 (add-text-properties
5947 beg (match-end 0)
5948 '(font-lock-fontified t face font-lock-comment-face)))
5949 (t ;; just any other in-buffer setting, but not indented
5950 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5951 (add-text-properties
5952 beg (match-end 0)
5953 '(font-lock-fontified t face org-meta-line))
5954 t))))))
5956 (defun org-fontify-drawers (limit)
5957 "Fontify drawers."
5958 (when (re-search-forward org-drawer-regexp limit t)
5959 (add-text-properties
5960 (match-beginning 0) (match-end 0)
5961 '(font-lock-fontified t face org-special-keyword))
5962 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5965 (defun org-fontify-macros (limit)
5966 "Fontify macros."
5967 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
5968 (add-text-properties
5969 (match-beginning 0) (match-end 0)
5970 '(font-lock-fontified t face org-macro))
5971 (when org-hide-macro-markers
5972 (add-text-properties (match-end 2) (match-beginning 2)
5973 '(invisible t))
5974 (add-text-properties (match-beginning 1) (match-end 1)
5975 '(invisible t)))
5976 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5979 (defun org-activate-angle-links (limit)
5980 "Run through the buffer and add overlays to links."
5981 (if (and (re-search-forward org-angle-link-re limit t)
5982 (not (org-in-src-block-p)))
5983 (progn
5984 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5985 (add-text-properties (match-beginning 0) (match-end 0)
5986 (list 'mouse-face 'highlight
5987 'keymap org-mouse-map))
5988 (org-rear-nonsticky-at (match-end 0))
5989 t)))
5991 (defun org-activate-footnote-links (limit)
5992 "Run through the buffer and add overlays to footnotes."
5993 (let ((fn (org-footnote-next-reference-or-definition limit)))
5994 (when fn
5995 (let* ((beg (nth 1 fn))
5996 (end (nth 2 fn))
5997 (label (car fn))
5998 (referencep (/= (line-beginning-position) beg)))
5999 (when (and referencep (nth 3 fn))
6000 (save-excursion
6001 (goto-char beg)
6002 (search-forward (or label "fn:"))
6003 (org-remove-flyspell-overlays-in beg (match-end 0))))
6004 (add-text-properties beg end
6005 (list 'mouse-face 'highlight
6006 'keymap org-mouse-map
6007 'help-echo
6008 (if referencep "Footnote reference"
6009 "Footnote definition")
6010 'font-lock-fontified t
6011 'font-lock-multiline t
6012 'face 'org-footnote))))))
6014 (defun org-activate-bracket-links (limit)
6015 "Run through the buffer and add overlays to bracketed links."
6016 (if (and (re-search-forward org-bracket-link-regexp limit t)
6017 (not (org-in-src-block-p)))
6018 (let* ((hl (org-match-string-no-properties 1))
6019 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
6020 (ip (org-maybe-intangible
6021 (list 'invisible 'org-link
6022 'keymap org-mouse-map 'mouse-face 'highlight
6023 'font-lock-multiline t 'help-echo help
6024 'htmlize-link `(:uri ,hl))))
6025 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
6026 'font-lock-multiline t 'help-echo help
6027 'htmlize-link `(:uri ,hl))))
6028 ;; We need to remove the invisible property here. Table narrowing
6029 ;; may have made some of this invisible.
6030 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6031 (remove-text-properties (match-beginning 0) (match-end 0)
6032 '(invisible nil))
6033 (if (match-end 3)
6034 (progn
6035 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
6036 (org-rear-nonsticky-at (match-beginning 3))
6037 (add-text-properties (match-beginning 3) (match-end 3) vp)
6038 (org-rear-nonsticky-at (match-end 3))
6039 (add-text-properties (match-end 3) (match-end 0) ip)
6040 (org-rear-nonsticky-at (match-end 0)))
6041 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
6042 (org-rear-nonsticky-at (match-beginning 1))
6043 (add-text-properties (match-beginning 1) (match-end 1) vp)
6044 (org-rear-nonsticky-at (match-end 1))
6045 (add-text-properties (match-end 1) (match-end 0) ip)
6046 (org-rear-nonsticky-at (match-end 0)))
6047 t)))
6049 (defun org-activate-dates (limit)
6050 "Run through the buffer and add overlays to dates."
6051 (if (and (re-search-forward org-tsr-regexp-both limit t)
6052 (not (equal (char-before (match-beginning 0)) 91)))
6053 (progn
6054 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6055 (add-text-properties (match-beginning 0) (match-end 0)
6056 (list 'mouse-face 'highlight
6057 'keymap org-mouse-map))
6058 (org-rear-nonsticky-at (match-end 0))
6059 (when org-display-custom-times
6060 (if (match-end 3)
6061 (org-display-custom-time (match-beginning 3) (match-end 3)))
6062 (org-display-custom-time (match-beginning 1) (match-end 1)))
6063 t)))
6065 (defvar org-target-link-regexp nil
6066 "Regular expression matching radio targets in plain text.")
6067 (make-variable-buffer-local 'org-target-link-regexp)
6069 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6070 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6071 border border border))
6072 "Regular expression matching a link target.")
6074 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6075 "Regular expression matching a radio target.")
6077 (defconst org-any-target-regexp
6078 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6079 "Regular expression matching any target.")
6081 (defun org-activate-target-links (limit)
6082 "Run through the buffer and add overlays to target matches."
6083 (when org-target-link-regexp
6084 (let ((case-fold-search t))
6085 (if (re-search-forward org-target-link-regexp limit t)
6086 (progn
6087 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6088 (add-text-properties (match-beginning 0) (match-end 0)
6089 (list 'mouse-face 'highlight
6090 'keymap org-mouse-map
6091 'help-echo "Radio target link"
6092 'org-linked-text t))
6093 (org-rear-nonsticky-at (match-end 0))
6094 t)))))
6096 (defun org-update-radio-target-regexp ()
6097 "Find all radio targets in this file and update the regular expression."
6098 (interactive)
6099 (when (memq 'radio org-activate-links)
6100 (setq org-target-link-regexp
6101 (org-make-target-link-regexp (org-all-targets 'radio)))
6102 (org-restart-font-lock)))
6104 (defun org-hide-wide-columns (limit)
6105 (let (s e)
6106 (setq s (text-property-any (point) (or limit (point-max))
6107 'org-cwidth t))
6108 (when s
6109 (setq e (next-single-property-change s 'org-cwidth))
6110 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6111 (goto-char e)
6112 t)))
6114 (defvar org-latex-and-related-regexp nil
6115 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6117 (defun org-compute-latex-and-related-regexp ()
6118 "Compute regular expression for LaTeX, entities and sub/superscript.
6119 Result depends on variable `org-highlight-latex-and-related'."
6120 (org-set-local
6121 'org-latex-and-related-regexp
6122 (let* ((re-sub
6123 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6124 ((eq org-use-sub-superscripts '{})
6125 (list org-match-substring-with-braces-regexp))
6126 (org-use-sub-superscripts (list org-match-substring-regexp))))
6127 (re-latex
6128 (when (memq 'latex org-highlight-latex-and-related)
6129 (let ((matchers (plist-get org-format-latex-options :matchers)))
6130 (delq nil
6131 (mapcar (lambda (x)
6132 (and (member (car x) matchers) (nth 1 x)))
6133 org-latex-regexps)))))
6134 (re-entities
6135 (when (memq 'entities org-highlight-latex-and-related)
6136 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6137 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6139 (defun org-do-latex-and-related (limit)
6140 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6141 LIMIT bounds the search for syntax to highlight. Stop at first
6142 highlighted object, if any. Return t if some highlighting was
6143 done, nil otherwise."
6144 (when (org-string-nw-p org-latex-and-related-regexp)
6145 (catch 'found
6146 (while (re-search-forward org-latex-and-related-regexp limit t)
6147 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6148 'face))
6149 '(org-code org-verbatim underline))
6150 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6151 '(?_ ?^))
6153 0)))
6154 (font-lock-prepend-text-property
6155 (+ offset (match-beginning 0)) (match-end 0)
6156 'face 'org-latex-and-related)
6157 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6158 '(font-lock-multiline t)))
6159 (throw 'found t)))
6160 nil)))
6162 (defun org-restart-font-lock ()
6163 "Restart `font-lock-mode', to force refontification."
6164 (when (and (boundp 'font-lock-mode) font-lock-mode)
6165 (font-lock-mode -1)
6166 (font-lock-mode 1)))
6168 (defun org-all-targets (&optional radio)
6169 "Return a list of all targets in this file.
6170 When optional argument RADIO is non-nil, only find radio
6171 targets."
6172 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
6173 (save-excursion
6174 (goto-char (point-min))
6175 (while (re-search-forward re nil t)
6176 ;; Make sure point is really within the object.
6177 (backward-char)
6178 (let ((obj (org-element-context)))
6179 (when (memq (org-element-type obj) '(radio-target target))
6180 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
6181 rtn)))
6183 (defun org-make-target-link-regexp (targets)
6184 "Make regular expression matching all strings in TARGETS.
6185 The regular expression finds the targets also if there is a line break
6186 between words."
6187 (and targets
6188 (concat "\\("
6189 (mapconcat
6190 (lambda (x)
6191 (replace-regexp-in-string " +" "\\s-+" (regexp-quote x) t t))
6192 targets
6193 "\\|")
6194 "\\)")))
6196 (defun org-activate-tags (limit)
6197 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6198 (progn
6199 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6200 (add-text-properties (match-beginning 1) (match-end 1)
6201 (list 'mouse-face 'highlight
6202 'keymap org-mouse-map))
6203 (org-rear-nonsticky-at (match-end 1))
6204 t)))
6206 (defun org-outline-level ()
6207 "Compute the outline level of the heading at point.
6208 If this is called at a normal headline, the level is the number of stars.
6209 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6210 (save-excursion
6211 (if (not (condition-case nil
6212 (org-back-to-heading t)
6213 (error nil)))
6215 (looking-at org-outline-regexp)
6216 (1- (- (match-end 0) (match-beginning 0))))))
6218 (defvar org-font-lock-keywords nil)
6220 (defsubst org-re-property (property &optional literal)
6221 "Return a regexp matching a PROPERTY line.
6222 Match group 3 will be set to the value if it exists."
6223 (concat "^\\(?4:[ \t]*\\)\\(?1::\\(?2:"
6224 (if literal property (regexp-quote property))
6225 "\\):\\)[ \t]+\\(?3:[^ \t\r\n].*?\\)\\(?5:[ \t]*\\)$"))
6227 (defconst org-property-re
6228 (org-re-property ".*?" 'literal)
6229 "Regular expression matching a property line.
6230 There are four matching groups:
6231 1: :PROPKEY: including the leading and trailing colon,
6232 2: PROPKEY without the leading and trailing colon,
6233 3: PROPVAL without leading or trailing spaces,
6234 4: the indentation of the current line,
6235 5: trailing whitespace.")
6237 (defvar org-font-lock-hook nil
6238 "Functions to be called for special font lock stuff.")
6240 (defvar org-font-lock-set-keywords-hook nil
6241 "Functions that can manipulate `org-font-lock-extra-keywords'.
6242 This is called after `org-font-lock-extra-keywords' is defined, but before
6243 it is installed to be used by font lock. This can be useful if something
6244 needs to be inserted at a specific position in the font-lock sequence.")
6246 (defun org-font-lock-hook (limit)
6247 "Run `org-font-lock-hook' within LIMIT."
6248 (run-hook-with-args 'org-font-lock-hook limit))
6250 (defun org-set-font-lock-defaults ()
6251 "Set font lock defaults for the current buffer."
6252 (let* ((em org-fontify-emphasized-text)
6253 (lk org-activate-links)
6254 (org-font-lock-extra-keywords
6255 (list
6256 ;; Call the hook
6257 '(org-font-lock-hook)
6258 ;; Headlines
6259 `(,(if org-fontify-whole-heading-line
6260 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6261 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6262 (1 (org-get-level-face 1))
6263 (2 (org-get-level-face 2))
6264 (3 (org-get-level-face 3)))
6265 ;; Table lines
6266 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6267 (1 'org-table t))
6268 ;; Table internals
6269 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6270 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6271 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6272 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6273 ;; Drawers
6274 '(org-fontify-drawers)
6275 ;; Properties
6276 (list org-property-re
6277 '(1 'org-special-keyword t)
6278 '(3 'org-property-value t))
6279 ;; Links
6280 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6281 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6282 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6283 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6284 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6285 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6286 (if (memq 'footnote lk) '(org-activate-footnote-links))
6287 ;; Targets.
6288 (list org-any-target-regexp '(0 'org-target t))
6289 ;; Diary sexps.
6290 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6291 ;; Macro
6292 '(org-fontify-macros)
6293 '(org-hide-wide-columns (0 nil append))
6294 ;; TODO keyword
6295 (list (format org-heading-keyword-regexp-format
6296 org-todo-regexp)
6297 '(2 (org-get-todo-face 2) t))
6298 ;; DONE
6299 (if org-fontify-done-headline
6300 (list (format org-heading-keyword-regexp-format
6301 (concat
6302 "\\(?:"
6303 (mapconcat 'regexp-quote org-done-keywords "\\|")
6304 "\\)"))
6305 '(2 'org-headline-done t))
6306 nil)
6307 ;; Priorities
6308 '(org-font-lock-add-priority-faces)
6309 ;; Tags
6310 '(org-font-lock-add-tag-faces)
6311 ;; Tags groups
6312 (if (and org-group-tags org-tag-groups-alist)
6313 (list (concat org-outline-regexp-bol ".+\\(:"
6314 (regexp-opt (mapcar 'car org-tag-groups-alist))
6315 ":\\).*$")
6316 '(1 'org-tag-group prepend)))
6317 ;; Special keywords
6318 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6319 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6320 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6321 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6322 ;; Emphasis
6323 (if em
6324 (if (featurep 'xemacs)
6325 '(org-do-emphasis-faces (0 nil append))
6326 '(org-do-emphasis-faces)))
6327 ;; Checkboxes
6328 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6329 1 'org-checkbox prepend)
6330 (if (cdr (assq 'checkbox org-list-automatic-rules))
6331 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6332 (0 (org-get-checkbox-statistics-face) t)))
6333 ;; Description list items
6334 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6335 1 'org-list-dt prepend)
6336 ;; ARCHIVEd headings
6337 (list (concat
6338 org-outline-regexp-bol
6339 "\\(.*:" org-archive-tag ":.*\\)")
6340 '(1 'org-archived prepend))
6341 ;; Specials
6342 '(org-do-latex-and-related)
6343 '(org-fontify-entities)
6344 '(org-raise-scripts)
6345 ;; Code
6346 '(org-activate-code (1 'org-code t))
6347 ;; COMMENT
6348 (list (format org-heading-keyword-regexp-format
6349 (concat "\\(" org-comment-string "\\)"))
6350 '(2 'org-special-keyword t))
6351 ;; Blocks and meta lines
6352 '(org-fontify-meta-lines-and-blocks))))
6353 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6354 (run-hooks 'org-font-lock-set-keywords-hook)
6355 ;; Now set the full font-lock-keywords
6356 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6357 (org-set-local 'font-lock-defaults
6358 '(org-font-lock-keywords t nil nil backward-paragraph))
6359 (kill-local-variable 'font-lock-keywords) nil))
6361 (defun org-toggle-pretty-entities ()
6362 "Toggle the composition display of entities as UTF8 characters."
6363 (interactive)
6364 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6365 (org-restart-font-lock)
6366 (if org-pretty-entities
6367 (message "Entities are now displayed as UTF8 characters")
6368 (save-restriction
6369 (widen)
6370 (org-decompose-region (point-min) (point-max))
6371 (message "Entities are now displayed as plain text"))))
6373 (defvar org-custom-properties-overlays nil
6374 "List of overlays used for custom properties.")
6375 (make-variable-buffer-local 'org-custom-properties-overlays)
6377 (defun org-toggle-custom-properties-visibility ()
6378 "Display or hide properties in `org-custom-properties'."
6379 (interactive)
6380 (if org-custom-properties-overlays
6381 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6382 (setq org-custom-properties-overlays nil))
6383 (unless (not org-custom-properties)
6384 (save-excursion
6385 (save-restriction
6386 (widen)
6387 (goto-char (point-min))
6388 (while (re-search-forward org-property-re nil t)
6389 (mapc (lambda(p)
6390 (when (equal p (substring (match-string 1) 1 -1))
6391 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6392 (overlay-put o 'invisible t)
6393 (overlay-put o 'org-custom-property t)
6394 (push o org-custom-properties-overlays))))
6395 org-custom-properties)))))))
6397 (defun org-fontify-entities (limit)
6398 "Find an entity to fontify."
6399 (let (ee)
6400 (when org-pretty-entities
6401 (catch 'match
6402 (while (re-search-forward
6403 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6404 limit t)
6405 (if (and (not (org-in-indented-comment-line))
6406 (setq ee (org-entity-get (match-string 1)))
6407 (= (length (nth 6 ee)) 1))
6408 (let*
6409 ((end (if (equal (match-string 2) "{}")
6410 (match-end 2)
6411 (match-end 1))))
6412 (add-text-properties
6413 (match-beginning 0) end
6414 (list 'font-lock-fontified t))
6415 (compose-region (match-beginning 0) end
6416 (nth 6 ee) nil)
6417 (backward-char 1)
6418 (throw 'match t))))
6419 nil))))
6421 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6422 "Fontify string S like in Org-mode."
6423 (with-temp-buffer
6424 (insert s)
6425 (let ((org-odd-levels-only odd-levels))
6426 (org-mode)
6427 (font-lock-fontify-buffer)
6428 (buffer-string))))
6430 (defvar org-m nil)
6431 (defvar org-l nil)
6432 (defvar org-f nil)
6433 (defun org-get-level-face (n)
6434 "Get the right face for match N in font-lock matching of headlines."
6435 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6436 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6437 (if org-cycle-level-faces
6438 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6439 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6440 (cond
6441 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6442 ((eq n 2) org-f)
6443 (t (if org-level-color-stars-only nil org-f))))
6446 (defun org-get-todo-face (kwd)
6447 "Get the right face for a TODO keyword KWD.
6448 If KWD is a number, get the corresponding match group."
6449 (if (numberp kwd) (setq kwd (match-string kwd)))
6450 (or (org-face-from-face-or-color
6451 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6452 (and (member kwd org-done-keywords) 'org-done)
6453 'org-todo))
6455 (defun org-face-from-face-or-color (context inherit face-or-color)
6456 "Create a face list that inherits INHERIT, but sets the foreground color.
6457 When FACE-OR-COLOR is not a string, just return it."
6458 (if (stringp face-or-color)
6459 (list :inherit inherit
6460 (cdr (assoc context org-faces-easy-properties))
6461 face-or-color)
6462 face-or-color))
6464 (defun org-font-lock-add-tag-faces (limit)
6465 "Add the special tag faces."
6466 (when (and org-tag-faces org-tags-special-faces-re)
6467 (while (re-search-forward org-tags-special-faces-re limit t)
6468 (add-text-properties (match-beginning 1) (match-end 1)
6469 (list 'face (org-get-tag-face 1)
6470 'font-lock-fontified t))
6471 (backward-char 1))))
6473 (defun org-font-lock-add-priority-faces (limit)
6474 "Add the special priority faces."
6475 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6476 (when (save-match-data (org-at-heading-p))
6477 (add-text-properties
6478 (match-beginning 0) (match-end 0)
6479 (list 'face (or (org-face-from-face-or-color
6480 'priority 'org-priority
6481 (cdr (assoc (char-after (match-beginning 1))
6482 org-priority-faces)))
6483 'org-priority)
6484 'font-lock-fontified t)))))
6486 (defun org-get-tag-face (kwd)
6487 "Get the right face for a TODO keyword KWD.
6488 If KWD is a number, get the corresponding match group."
6489 (if (numberp kwd) (setq kwd (match-string kwd)))
6490 (or (org-face-from-face-or-color
6491 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6492 'org-tag))
6494 (defun org-unfontify-region (beg end &optional maybe_loudly)
6495 "Remove fontification and activation overlays from links."
6496 (font-lock-default-unfontify-region beg end)
6497 (let* ((buffer-undo-list t)
6498 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6499 (inhibit-modification-hooks t)
6500 deactivate-mark buffer-file-name buffer-file-truename)
6501 (org-decompose-region beg end)
6502 (remove-text-properties beg end
6503 '(mouse-face t keymap t org-linked-text t
6504 invisible t intangible t
6505 org-emphasis t))
6506 (org-remove-font-lock-display-properties beg end)))
6508 (defconst org-script-display '(((raise -0.3) (height 0.7))
6509 ((raise 0.3) (height 0.7))
6510 ((raise -0.5))
6511 ((raise 0.5)))
6512 "Display properties for showing superscripts and subscripts.")
6514 (defun org-remove-font-lock-display-properties (beg end)
6515 "Remove specific display properties that have been added by font lock.
6516 The will remove the raise properties that are used to show superscripts
6517 and subscripts."
6518 (let (next prop)
6519 (while (< beg end)
6520 (setq next (next-single-property-change beg 'display nil end)
6521 prop (get-text-property beg 'display))
6522 (if (member prop org-script-display)
6523 (put-text-property beg next 'display nil))
6524 (setq beg next))))
6526 (defun org-raise-scripts (limit)
6527 "Add raise properties to sub/superscripts."
6528 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6529 (if (re-search-forward
6530 (if (eq org-use-sub-superscripts t)
6531 org-match-substring-regexp
6532 org-match-substring-with-braces-regexp)
6533 limit t)
6534 (let* ((pos (point)) table-p comment-p
6535 (mpos (match-beginning 3))
6536 (emph-p (get-text-property mpos 'org-emphasis))
6537 (link-p (get-text-property mpos 'mouse-face))
6538 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6539 (goto-char (point-at-bol))
6540 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6541 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6542 (goto-char pos)
6543 ;; Handle a_b^c
6544 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6545 (if (or comment-p emph-p link-p keyw-p)
6547 (put-text-property (match-beginning 3) (match-end 0)
6548 'display
6549 (if (equal (char-after (match-beginning 2)) ?^)
6550 (nth (if table-p 3 1) org-script-display)
6551 (nth (if table-p 2 0) org-script-display)))
6552 (add-text-properties (match-beginning 2) (match-end 2)
6553 (list 'invisible t
6554 'org-dwidth t 'org-dwidth-n 1))
6555 (if (and (eq (char-after (match-beginning 3)) ?{)
6556 (eq (char-before (match-end 3)) ?}))
6557 (progn
6558 (add-text-properties
6559 (match-beginning 3) (1+ (match-beginning 3))
6560 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6561 (add-text-properties
6562 (1- (match-end 3)) (match-end 3)
6563 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6564 t)))))
6566 ;;;; Visibility cycling, including org-goto and indirect buffer
6568 ;;; Cycling
6570 (defvar org-cycle-global-status nil)
6571 (make-variable-buffer-local 'org-cycle-global-status)
6572 (put 'org-cycle-global-status 'org-state t)
6573 (defvar org-cycle-subtree-status nil)
6574 (make-variable-buffer-local 'org-cycle-subtree-status)
6575 (put 'org-cycle-subtree-status 'org-state t)
6577 (defvar org-inlinetask-min-level)
6579 (defun org-unlogged-message (&rest args)
6580 "Display a message, but avoid logging it in the *Messages* buffer."
6581 (let ((message-log-max nil))
6582 (apply 'message args)))
6584 ;;;###autoload
6585 (defun org-cycle (&optional arg)
6586 "TAB-action and visibility cycling for Org-mode.
6588 This is the command invoked in Org-mode by the TAB key. Its main purpose
6589 is outline visibility cycling, but it also invokes other actions
6590 in special contexts.
6592 - When this function is called with a prefix argument, rotate the entire
6593 buffer through 3 states (global cycling)
6594 1. OVERVIEW: Show only top-level headlines.
6595 2. CONTENTS: Show all headlines of all levels, but no body text.
6596 3. SHOW ALL: Show everything.
6597 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6598 determined by the variable `org-startup-folded', and by any VISIBILITY
6599 properties in the buffer.
6600 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6601 including any drawers.
6603 - When inside a table, re-align the table and move to the next field.
6605 - When point is at the beginning of a headline, rotate the subtree started
6606 by this line through 3 different states (local cycling)
6607 1. FOLDED: Only the main headline is shown.
6608 2. CHILDREN: The main headline and the direct children are shown.
6609 From this state, you can move to one of the children
6610 and zoom in further.
6611 3. SUBTREE: Show the entire subtree, including body text.
6612 If there is no subtree, switch directly from CHILDREN to FOLDED.
6614 - When point is at the beginning of an empty headline and the variable
6615 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6616 of the headline by demoting and promoting it to likely levels. This
6617 speeds up creation document structure by pressing TAB once or several
6618 times right after creating a new headline.
6620 - When there is a numeric prefix, go up to a heading with level ARG, do
6621 a `show-subtree' and return to the previous cursor position. If ARG
6622 is negative, go up that many levels.
6624 - When point is not at the beginning of a headline, execute the global
6625 binding for TAB, which is re-indenting the line. See the option
6626 `org-cycle-emulate-tab' for details.
6628 - Special case: if point is at the beginning of the buffer and there is
6629 no headline in line 1, this function will act as if called with prefix arg
6630 (C-u TAB, same as S-TAB) also when called without prefix arg.
6631 But only if also the variable `org-cycle-global-at-bob' is t."
6632 (interactive "P")
6633 (org-load-modules-maybe)
6634 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6635 (and org-cycle-level-after-item/entry-creation
6636 (or (org-cycle-level)
6637 (org-cycle-item-indentation))))
6638 (let* ((limit-level
6639 (or org-cycle-max-level
6640 (and (boundp 'org-inlinetask-min-level)
6641 org-inlinetask-min-level
6642 (1- org-inlinetask-min-level))))
6643 (nstars (and limit-level
6644 (if org-odd-levels-only
6645 (and limit-level (1- (* limit-level 2)))
6646 limit-level)))
6647 (org-outline-regexp
6648 (if (not (derived-mode-p 'org-mode))
6649 outline-regexp
6650 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6651 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6652 (not (looking-at org-outline-regexp))))
6653 (org-cycle-hook
6654 (if bob-special
6655 (delq 'org-optimize-window-after-visibility-change
6656 (copy-sequence org-cycle-hook))
6657 org-cycle-hook))
6658 (pos (point)))
6660 (if (or bob-special (equal arg '(4)))
6661 ;; special case: use global cycling
6662 (setq arg t))
6664 (cond
6666 ((equal arg '(16))
6667 (setq last-command 'dummy)
6668 (org-set-startup-visibility)
6669 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6671 ((equal arg '(64))
6672 (show-all)
6673 (org-unlogged-message "Entire buffer visible, including drawers"))
6675 ;; Table: enter it or move to the next field.
6676 ((org-at-table-p 'any)
6677 (if (org-at-table.el-p)
6678 (message "Use C-c ' to edit table.el tables")
6679 (if arg (org-table-edit-field t)
6680 (org-table-justify-field-maybe)
6681 (call-interactively 'org-table-next-field))))
6683 ((run-hook-with-args-until-success
6684 'org-tab-after-check-for-table-hook))
6686 ;; Global cycling: delegate to `org-cycle-internal-global'.
6687 ((eq arg t) (org-cycle-internal-global))
6689 ;; Drawers: delegate to `org-flag-drawer'.
6690 ((save-excursion
6691 (beginning-of-line 1)
6692 (looking-at org-drawer-regexp))
6693 (org-flag-drawer ; toggle block visibility
6694 (not (get-char-property (match-end 0) 'invisible))))
6696 ;; Show-subtree, ARG levels up from here.
6697 ((integerp arg)
6698 (save-excursion
6699 (org-back-to-heading)
6700 (outline-up-heading (if (< arg 0) (- arg)
6701 (- (funcall outline-level) arg)))
6702 (org-show-subtree)))
6704 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6705 ((and (featurep 'org-inlinetask)
6706 (org-inlinetask-at-task-p)
6707 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6708 (org-inlinetask-toggle-visibility))
6710 ((org-try-cdlatex-tab))
6712 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6713 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6714 (save-excursion (beginning-of-line 1)
6715 (looking-at org-outline-regexp)))
6716 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6717 (org-cycle-internal-local))
6719 ;; From there: TAB emulation and template completion.
6720 (buffer-read-only (org-back-to-heading))
6722 ((run-hook-with-args-until-success
6723 'org-tab-after-check-for-cycling-hook))
6725 ((org-try-structure-completion))
6727 ((run-hook-with-args-until-success
6728 'org-tab-before-tab-emulation-hook))
6730 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6731 (or (not (bolp))
6732 (not (looking-at org-outline-regexp))))
6733 (call-interactively (global-key-binding "\t")))
6735 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6736 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6737 (or (and (eq org-cycle-emulate-tab 'white)
6738 (= (match-end 0) (point-at-eol)))
6739 (and (eq org-cycle-emulate-tab 'whitestart)
6740 (>= (match-end 0) pos))))
6742 (eq org-cycle-emulate-tab t))
6743 (call-interactively (global-key-binding "\t")))
6745 (t (save-excursion
6746 (org-back-to-heading)
6747 (org-cycle)))))))
6749 (defun org-cycle-internal-global ()
6750 "Do the global cycling action."
6751 ;; Hack to avoid display of messages for .org attachments in Gnus
6752 (let ((ga (string-match "\\*fontification" (buffer-name))))
6753 (cond
6754 ((and (eq last-command this-command)
6755 (eq org-cycle-global-status 'overview))
6756 ;; We just created the overview - now do table of contents
6757 ;; This can be slow in very large buffers, so indicate action
6758 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6759 (unless ga (org-unlogged-message "CONTENTS..."))
6760 (org-content)
6761 (unless ga (org-unlogged-message "CONTENTS...done"))
6762 (setq org-cycle-global-status 'contents)
6763 (run-hook-with-args 'org-cycle-hook 'contents))
6765 ((and (eq last-command this-command)
6766 (eq org-cycle-global-status 'contents))
6767 ;; We just showed the table of contents - now show everything
6768 (run-hook-with-args 'org-pre-cycle-hook 'all)
6769 (show-all)
6770 (unless ga (org-unlogged-message "SHOW ALL"))
6771 (setq org-cycle-global-status 'all)
6772 (run-hook-with-args 'org-cycle-hook 'all))
6775 ;; Default action: go to overview
6776 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6777 (org-overview)
6778 (unless ga (org-unlogged-message "OVERVIEW"))
6779 (setq org-cycle-global-status 'overview)
6780 (run-hook-with-args 'org-cycle-hook 'overview)))))
6782 (defvar org-called-with-limited-levels);Dyn-bound in ̀org-with-limited-levels'.
6784 (defun org-cycle-internal-local ()
6785 "Do the local cycling action."
6786 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6787 ;; First, determine end of headline (EOH), end of subtree or item
6788 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6789 (save-excursion
6790 (if (org-at-item-p)
6791 (progn
6792 (beginning-of-line)
6793 (setq struct (org-list-struct))
6794 (setq eoh (point-at-eol))
6795 (setq eos (org-list-get-item-end-before-blank (point) struct))
6796 (setq has-children (org-list-has-child-p (point) struct)))
6797 (org-back-to-heading)
6798 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6799 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6800 (setq has-children
6801 (or (save-excursion
6802 (let ((level (funcall outline-level)))
6803 (outline-next-heading)
6804 (and (org-at-heading-p t)
6805 (> (funcall outline-level) level))))
6806 (save-excursion
6807 (org-list-search-forward (org-item-beginning-re) eos t)))))
6808 ;; Determine end invisible part of buffer (EOL)
6809 (beginning-of-line 2)
6810 ;; XEmacs doesn't have `next-single-char-property-change'
6811 (if (featurep 'xemacs)
6812 (while (and (not (eobp)) ;; this is like `next-line'
6813 (get-char-property (1- (point)) 'invisible))
6814 (beginning-of-line 2))
6815 (while (and (not (eobp)) ;; this is like `next-line'
6816 (get-char-property (1- (point)) 'invisible))
6817 (goto-char (next-single-char-property-change (point) 'invisible))
6818 (and (eolp) (beginning-of-line 2))))
6819 (setq eol (point)))
6820 ;; Find out what to do next and set `this-command'
6821 (cond
6822 ((= eos eoh)
6823 ;; Nothing is hidden behind this heading
6824 (unless (org-before-first-heading-p)
6825 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6826 (org-unlogged-message "EMPTY ENTRY")
6827 (setq org-cycle-subtree-status nil)
6828 (save-excursion
6829 (goto-char eos)
6830 (outline-next-heading)
6831 (if (outline-invisible-p) (org-flag-heading nil))))
6832 ((and (or (>= eol eos)
6833 (not (string-match "\\S-" (buffer-substring eol eos))))
6834 (or has-children
6835 (not (setq children-skipped
6836 org-cycle-skip-children-state-if-no-children))))
6837 ;; Entire subtree is hidden in one line: children view
6838 (unless (org-before-first-heading-p)
6839 (run-hook-with-args 'org-pre-cycle-hook 'children))
6840 (if (org-at-item-p)
6841 (org-list-set-item-visibility (point-at-bol) struct 'children)
6842 (org-show-entry)
6843 (org-with-limited-levels (show-children))
6844 ;; FIXME: This slows down the func way too much.
6845 ;; How keep drawers hidden in subtree anyway?
6846 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6847 ;; (org-cycle-hide-drawers 'subtree))
6849 ;; Fold every list in subtree to top-level items.
6850 (when (eq org-cycle-include-plain-lists 'integrate)
6851 (save-excursion
6852 (org-back-to-heading)
6853 (while (org-list-search-forward (org-item-beginning-re) eos t)
6854 (beginning-of-line 1)
6855 (let* ((struct (org-list-struct))
6856 (prevs (org-list-prevs-alist struct))
6857 (end (org-list-get-bottom-point struct)))
6858 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6859 (org-list-get-all-items (point) struct prevs))
6860 (goto-char (if (< end eos) end eos)))))))
6861 (org-unlogged-message "CHILDREN")
6862 (save-excursion
6863 (goto-char eos)
6864 (outline-next-heading)
6865 (if (outline-invisible-p) (org-flag-heading nil)))
6866 (setq org-cycle-subtree-status 'children)
6867 (unless (org-before-first-heading-p)
6868 (run-hook-with-args 'org-cycle-hook 'children)))
6869 ((or children-skipped
6870 (and (eq last-command this-command)
6871 (eq org-cycle-subtree-status 'children)))
6872 ;; We just showed the children, or no children are there,
6873 ;; now show everything.
6874 (unless (org-before-first-heading-p)
6875 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6876 (outline-flag-region eoh eos nil)
6877 (org-unlogged-message
6878 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6879 (setq org-cycle-subtree-status 'subtree)
6880 (unless (org-before-first-heading-p)
6881 (run-hook-with-args 'org-cycle-hook 'subtree)))
6883 ;; Default action: hide the subtree.
6884 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6885 (outline-flag-region eoh eos t)
6886 (org-unlogged-message "FOLDED")
6887 (setq org-cycle-subtree-status 'folded)
6888 (unless (org-before-first-heading-p)
6889 (run-hook-with-args 'org-cycle-hook 'folded))))))
6891 ;;;###autoload
6892 (defun org-global-cycle (&optional arg)
6893 "Cycle the global visibility. For details see `org-cycle'.
6894 With \\[universal-argument] prefix arg, switch to startup visibility.
6895 With a numeric prefix, show all headlines up to that level."
6896 (interactive "P")
6897 (let ((org-cycle-include-plain-lists
6898 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6899 (cond
6900 ((integerp arg)
6901 (show-all)
6902 (hide-sublevels arg)
6903 (setq org-cycle-global-status 'contents))
6904 ((equal arg '(4))
6905 (org-set-startup-visibility)
6906 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6908 (org-cycle '(4))))))
6910 (defun org-set-startup-visibility ()
6911 "Set the visibility required by startup options and properties."
6912 (cond
6913 ((eq org-startup-folded t)
6914 (org-overview))
6915 ((eq org-startup-folded 'content)
6916 (org-content))
6917 ((or (eq org-startup-folded 'showeverything)
6918 (eq org-startup-folded nil))
6919 (show-all)))
6920 (unless (eq org-startup-folded 'showeverything)
6921 (if org-hide-block-startup (org-hide-block-all))
6922 (org-set-visibility-according-to-property 'no-cleanup)
6923 (org-cycle-hide-archived-subtrees 'all)
6924 (org-cycle-hide-drawers 'all)
6925 (org-cycle-show-empty-lines t)))
6927 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6928 "Switch subtree visibilities according to :VISIBILITY: property."
6929 (interactive)
6930 (let (org-show-entry-below state)
6931 (save-excursion
6932 (goto-char (point-min))
6933 (while (re-search-forward
6934 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6935 nil t)
6936 (setq state (match-string 1))
6937 (save-excursion
6938 (org-back-to-heading t)
6939 (hide-subtree)
6940 (org-reveal)
6941 (cond
6942 ((equal state '("fold" "folded"))
6943 (hide-subtree))
6944 ((equal state "children")
6945 (org-show-hidden-entry)
6946 (show-children))
6947 ((equal state "content")
6948 (save-excursion
6949 (save-restriction
6950 (org-narrow-to-subtree)
6951 (org-content))))
6952 ((member state '("all" "showall"))
6953 (show-subtree)))))
6954 (unless no-cleanup
6955 (org-cycle-hide-archived-subtrees 'all)
6956 (org-cycle-hide-drawers 'all)
6957 (org-cycle-show-empty-lines 'all)))))
6959 ;; This function uses outline-regexp instead of the more fundamental
6960 ;; org-outline-regexp so that org-cycle-global works outside of Org
6961 ;; buffers, where outline-regexp is needed.
6962 (defun org-overview ()
6963 "Switch to overview mode, showing only top-level headlines.
6964 Really, this shows all headlines with level equal or greater than the level
6965 of the first headline in the buffer. This is important, because if the
6966 first headline is not level one, then (hide-sublevels 1) gives confusing
6967 results."
6968 (interactive)
6969 (let ((pos (point))
6970 (level (save-excursion
6971 (goto-char (point-min))
6972 (if (re-search-forward (concat "^" outline-regexp) nil t)
6973 (progn
6974 (goto-char (match-beginning 0))
6975 (funcall outline-level))))))
6976 (and level (hide-sublevels level))
6977 (recenter '(4))
6978 (goto-char pos)))
6980 (defun org-content (&optional arg)
6981 "Show all headlines in the buffer, like a table of contents.
6982 With numerical argument N, show content up to level N."
6983 (interactive "P")
6984 (org-overview)
6985 (save-excursion
6986 ;; Visit all headings and show their offspring
6987 (and (integerp arg) (org-overview))
6988 (goto-char (point-max))
6989 (catch 'exit
6990 (while (and (progn (condition-case nil
6991 (outline-previous-visible-heading 1)
6992 (error (goto-char (point-min))))
6994 (looking-at org-outline-regexp))
6995 (if (integerp arg)
6996 (show-children (1- arg))
6997 (show-branches))
6998 (if (bobp) (throw 'exit nil))))))
7000 (defun org-optimize-window-after-visibility-change (state)
7001 "Adjust the window after a change in outline visibility.
7002 This function is the default value of the hook `org-cycle-hook'."
7003 (when (get-buffer-window (current-buffer))
7004 (cond
7005 ((eq state 'content) nil)
7006 ((eq state 'all) nil)
7007 ((eq state 'folded) nil)
7008 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7009 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7011 (defun org-remove-empty-overlays-at (pos)
7012 "Remove outline overlays that do not contain non-white stuff."
7013 (mapc
7014 (lambda (o)
7015 (and (eq 'outline (overlay-get o 'invisible))
7016 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7017 (overlay-end o))))
7018 (delete-overlay o)))
7019 (overlays-at pos)))
7021 (defun org-clean-visibility-after-subtree-move ()
7022 "Fix visibility issues after moving a subtree."
7023 ;; First, find a reasonable region to look at:
7024 ;; Start two siblings above, end three below
7025 (let* ((beg (save-excursion
7026 (and (org-get-last-sibling)
7027 (org-get-last-sibling))
7028 (point)))
7029 (end (save-excursion
7030 (and (org-get-next-sibling)
7031 (org-get-next-sibling)
7032 (org-get-next-sibling))
7033 (if (org-at-heading-p)
7034 (point-at-eol)
7035 (point))))
7036 (level (looking-at "\\*+"))
7037 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
7038 (save-excursion
7039 (save-restriction
7040 (narrow-to-region beg end)
7041 (when re
7042 ;; Properly fold already folded siblings
7043 (goto-char (point-min))
7044 (while (re-search-forward re nil t)
7045 (if (and (not (outline-invisible-p))
7046 (save-excursion
7047 (goto-char (point-at-eol)) (outline-invisible-p)))
7048 (hide-entry))))
7049 (org-cycle-show-empty-lines 'overview)
7050 (org-cycle-hide-drawers 'overview)))))
7052 (defun org-cycle-show-empty-lines (state)
7053 "Show empty lines above all visible headlines.
7054 The region to be covered depends on STATE when called through
7055 `org-cycle-hook'. Lisp program can use t for STATE to get the
7056 entire buffer covered. Note that an empty line is only shown if there
7057 are at least `org-cycle-separator-lines' empty lines before the headline."
7058 (when (not (= org-cycle-separator-lines 0))
7059 (save-excursion
7060 (let* ((n (abs org-cycle-separator-lines))
7061 (re (cond
7062 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7063 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7064 (t (let ((ns (number-to-string (- n 2))))
7065 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7066 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7067 beg end b e)
7068 (cond
7069 ((memq state '(overview contents t))
7070 (setq beg (point-min) end (point-max)))
7071 ((memq state '(children folded))
7072 (setq beg (point) end (progn (org-end-of-subtree t t)
7073 (beginning-of-line 2)
7074 (point)))))
7075 (when beg
7076 (goto-char beg)
7077 (while (re-search-forward re end t)
7078 (unless (get-char-property (match-end 1) 'invisible)
7079 (setq e (match-end 1))
7080 (if (< org-cycle-separator-lines 0)
7081 (setq b (save-excursion
7082 (goto-char (match-beginning 0))
7083 (org-back-over-empty-lines)
7084 (if (save-excursion
7085 (goto-char (max (point-min) (1- (point))))
7086 (org-at-heading-p))
7087 (1- (point))
7088 (point))))
7089 (setq b (match-beginning 1)))
7090 (outline-flag-region b e nil)))))))
7091 ;; Never hide empty lines at the end of the file.
7092 (save-excursion
7093 (goto-char (point-max))
7094 (outline-previous-heading)
7095 (outline-end-of-heading)
7096 (if (and (looking-at "[ \t\n]+")
7097 (= (match-end 0) (point-max)))
7098 (outline-flag-region (point) (match-end 0) nil))))
7100 (defun org-show-empty-lines-in-parent ()
7101 "Move to the parent and re-show empty lines before visible headlines."
7102 (save-excursion
7103 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7104 (org-cycle-show-empty-lines context))))
7106 (defun org-files-list ()
7107 "Return `org-agenda-files' list, plus all open org-mode files.
7108 This is useful for operations that need to scan all of a user's
7109 open and agenda-wise Org files."
7110 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7111 (dolist (buf (buffer-list))
7112 (with-current-buffer buf
7113 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7114 (let ((file (expand-file-name (buffer-file-name))))
7115 (unless (member file files)
7116 (push file files))))))
7117 files))
7119 (defsubst org-entry-beginning-position ()
7120 "Return the beginning position of the current entry."
7121 (save-excursion (outline-back-to-heading t) (point)))
7123 (defsubst org-entry-end-position ()
7124 "Return the end position of the current entry."
7125 (save-excursion (outline-next-heading) (point)))
7127 (defun org-cycle-hide-drawers (state &optional exceptions)
7128 "Re-hide all drawers after a visibility state change.
7129 When non-nil, optional argument EXCEPTIONS is a list of strings
7130 specifying which drawers should not be hidden."
7131 (when (and (derived-mode-p 'org-mode)
7132 (not (memq state '(overview folded contents))))
7133 (save-excursion
7134 (let* ((globalp (memq state '(contents all)))
7135 (beg (if globalp (point-min) (point)))
7136 (end (if globalp (point-max)
7137 (if (eq state 'children)
7138 (save-excursion (outline-next-heading) (point))
7139 (org-end-of-subtree t)))))
7140 (goto-char beg)
7141 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7142 (unless (member-ignore-case (match-string 1) exceptions)
7143 (let ((drawer (org-element-at-point)))
7144 (when (memq (org-element-type drawer) '(drawer property-drawer))
7145 (org-flag-drawer t drawer)
7146 ;; Make sure to skip drawer entirely or we might flag
7147 ;; it another time when matching its ending line with
7148 ;; `org-drawer-regexp'.
7149 (goto-char (org-element-property :end drawer))))))))))
7151 (defun org-cycle-hide-inline-tasks (state)
7152 "Re-hide inline tasks when switching to 'contents or 'children
7153 visibility state."
7154 (case state
7155 (contents
7156 (when (org-bound-and-true-p org-inlinetask-min-level)
7157 (hide-sublevels (1- org-inlinetask-min-level))))
7158 (children
7159 (when (featurep 'org-inlinetask)
7160 (save-excursion
7161 (while (and (outline-next-heading)
7162 (org-inlinetask-at-task-p))
7163 (org-inlinetask-toggle-visibility)
7164 (org-inlinetask-goto-end)))))))
7166 (defun org-flag-drawer (flag &optional element)
7167 "When FLAG is non-nil, hide the drawer we are at.
7168 Otherwise make it visible. When optional argument ELEMENT is
7169 a parsed drawer, as returned by `org-element-at-point', hide or
7170 show that drawer instead."
7171 (let ((drawer (or element (org-element-at-point))))
7172 (when (memq (org-element-type drawer) '(drawer property-drawer))
7173 (save-excursion
7174 (goto-char (org-element-property :post-affiliated drawer))
7175 (outline-flag-region
7176 (line-end-position)
7177 (progn (goto-char (org-element-property :end drawer))
7178 (skip-chars-backward " \r\t\n")
7179 (line-end-position))
7180 flag)))))
7182 (defun org-subtree-end-visible-p ()
7183 "Is the end of the current subtree visible?"
7184 (pos-visible-in-window-p
7185 (save-excursion (org-end-of-subtree t) (point))))
7187 (defun org-first-headline-recenter (&optional N)
7188 "Move cursor to the first headline and recenter the headline.
7189 Optional argument N means put the headline into the Nth line of the window."
7190 (goto-char (point-min))
7191 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7192 (beginning-of-line)
7193 (recenter (prefix-numeric-value N))))
7195 ;;; Saving and restoring visibility
7197 (defun org-outline-overlay-data (&optional use-markers)
7198 "Return a list of the locations of all outline overlays.
7199 These are overlays with the `invisible' property value `outline'.
7200 The return value is a list of cons cells, with start and stop
7201 positions for each overlay.
7202 If USE-MARKERS is set, return the positions as markers."
7203 (let (beg end)
7204 (save-excursion
7205 (save-restriction
7206 (widen)
7207 (delq nil
7208 (mapcar (lambda (o)
7209 (when (eq (overlay-get o 'invisible) 'outline)
7210 (setq beg (overlay-start o)
7211 end (overlay-end o))
7212 (and beg end (> end beg)
7213 (if use-markers
7214 (cons (copy-marker beg)
7215 (copy-marker end t))
7216 (cons beg end)))))
7217 (overlays-in (point-min) (point-max))))))))
7219 (defun org-set-outline-overlay-data (data)
7220 "Create visibility overlays for all positions in DATA.
7221 DATA should have been made by `org-outline-overlay-data'."
7222 (let (o)
7223 (save-excursion
7224 (save-restriction
7225 (widen)
7226 (show-all)
7227 (mapc (lambda (c)
7228 (outline-flag-region (car c) (cdr c) t))
7229 data)))))
7231 ;;; Folding of blocks
7233 (defvar org-hide-block-overlays nil
7234 "Overlays hiding blocks.")
7235 (make-variable-buffer-local 'org-hide-block-overlays)
7237 (defun org-block-map (function &optional start end)
7238 "Call FUNCTION at the head of all source blocks in the current buffer.
7239 Optional arguments START and END can be used to limit the range."
7240 (let ((start (or start (point-min)))
7241 (end (or end (point-max))))
7242 (save-excursion
7243 (goto-char start)
7244 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7245 (save-excursion
7246 (save-match-data
7247 (goto-char (match-beginning 0))
7248 (funcall function)))))))
7250 (defun org-hide-block-toggle-all ()
7251 "Toggle the visibility of all blocks in the current buffer."
7252 (org-block-map #'org-hide-block-toggle))
7254 (defun org-hide-block-all ()
7255 "Fold all blocks in the current buffer."
7256 (interactive)
7257 (org-show-block-all)
7258 (org-block-map #'org-hide-block-toggle-maybe))
7260 (defun org-show-block-all ()
7261 "Unfold all blocks in the current buffer."
7262 (interactive)
7263 (mapc 'delete-overlay org-hide-block-overlays)
7264 (setq org-hide-block-overlays nil))
7266 (defun org-hide-block-toggle-maybe ()
7267 "Toggle visibility of block at point."
7268 (interactive)
7269 (let ((case-fold-search t))
7270 (if (save-excursion
7271 (beginning-of-line 1)
7272 (looking-at org-block-regexp))
7273 (progn (org-hide-block-toggle)
7274 t) ;; to signal that we took action
7275 nil))) ;; to signal that we did not
7277 (defun org-hide-block-toggle (&optional force)
7278 "Toggle the visibility of the current block."
7279 (interactive)
7280 (save-excursion
7281 (beginning-of-line)
7282 (if (re-search-forward org-block-regexp nil t)
7283 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7284 (end (match-end 0)) ;; end of entire body
7286 (if (memq t (mapcar (lambda (overlay)
7287 (eq (overlay-get overlay 'invisible)
7288 'org-hide-block))
7289 (overlays-at start)))
7290 (if (or (not force) (eq force 'off))
7291 (mapc (lambda (ov)
7292 (when (member ov org-hide-block-overlays)
7293 (setq org-hide-block-overlays
7294 (delq ov org-hide-block-overlays)))
7295 (when (eq (overlay-get ov 'invisible)
7296 'org-hide-block)
7297 (delete-overlay ov)))
7298 (overlays-at start)))
7299 (setq ov (make-overlay start end))
7300 (overlay-put ov 'invisible 'org-hide-block)
7301 ;; make the block accessible to isearch
7302 (overlay-put
7303 ov 'isearch-open-invisible
7304 (lambda (ov)
7305 (when (member ov org-hide-block-overlays)
7306 (setq org-hide-block-overlays
7307 (delq ov org-hide-block-overlays)))
7308 (when (eq (overlay-get ov 'invisible)
7309 'org-hide-block)
7310 (delete-overlay ov))))
7311 (push ov org-hide-block-overlays)))
7312 (user-error "Not looking at a source block"))))
7314 ;; org-tab-after-check-for-cycling-hook
7315 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7316 ;; Remove overlays when changing major mode
7317 (add-hook 'org-mode-hook
7318 (lambda () (org-add-hook 'change-major-mode-hook
7319 'org-show-block-all 'append 'local)))
7321 ;;; Org-goto
7323 (defvar org-goto-window-configuration nil)
7324 (defvar org-goto-marker nil)
7325 (defvar org-goto-map)
7326 (defun org-goto-map ()
7327 "Set the keymap `org-goto'."
7328 (setq org-goto-map
7329 (let ((map (make-sparse-keymap)))
7330 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7331 mouse-drag-region universal-argument org-occur))
7332 cmd)
7333 (while (setq cmd (pop cmds))
7334 (substitute-key-definition cmd cmd map global-map)))
7335 (suppress-keymap map)
7336 (org-defkey map "\C-m" 'org-goto-ret)
7337 (org-defkey map [(return)] 'org-goto-ret)
7338 (org-defkey map [(left)] 'org-goto-left)
7339 (org-defkey map [(right)] 'org-goto-right)
7340 (org-defkey map [(control ?g)] 'org-goto-quit)
7341 (org-defkey map "\C-i" 'org-cycle)
7342 (org-defkey map [(tab)] 'org-cycle)
7343 (org-defkey map [(down)] 'outline-next-visible-heading)
7344 (org-defkey map [(up)] 'outline-previous-visible-heading)
7345 (if org-goto-auto-isearch
7346 (if (fboundp 'define-key-after)
7347 (define-key-after map [t] 'org-goto-local-auto-isearch)
7348 nil)
7349 (org-defkey map "q" 'org-goto-quit)
7350 (org-defkey map "n" 'outline-next-visible-heading)
7351 (org-defkey map "p" 'outline-previous-visible-heading)
7352 (org-defkey map "f" 'outline-forward-same-level)
7353 (org-defkey map "b" 'outline-backward-same-level)
7354 (org-defkey map "u" 'outline-up-heading))
7355 (org-defkey map "/" 'org-occur)
7356 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7357 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7358 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7359 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7360 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7361 map)))
7363 (defconst org-goto-help
7364 "Browse buffer copy, to find location or copy text.%s
7365 RET=jump to location C-g=quit and return to previous location
7366 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7368 (defvar org-goto-start-pos) ; dynamically scoped parameter
7370 (defun org-goto (&optional alternative-interface)
7371 "Look up a different location in the current file, keeping current visibility.
7373 When you want look-up or go to a different location in a
7374 document, the fastest way is often to fold the entire buffer and
7375 then dive into the tree. This method has the disadvantage, that
7376 the previous location will be folded, which may not be what you
7377 want.
7379 This command works around this by showing a copy of the current
7380 buffer in an indirect buffer, in overview mode. You can dive
7381 into the tree in that copy, use org-occur and incremental search
7382 to find a location. When pressing RET or `Q', the command
7383 returns to the original buffer in which the visibility is still
7384 unchanged. After RET it will also jump to the location selected
7385 in the indirect buffer and expose the headline hierarchy above.
7387 With a prefix argument, use the alternative interface: e.g. if
7388 `org-goto-interface' is 'outline use 'outline-path-completion."
7389 (interactive "P")
7390 (org-goto-map)
7391 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7392 (org-refile-use-outline-path t)
7393 (org-refile-target-verify-function nil)
7394 (interface
7395 (if (not alternative-interface)
7396 org-goto-interface
7397 (if (eq org-goto-interface 'outline)
7398 'outline-path-completion
7399 'outline)))
7400 (org-goto-start-pos (point))
7401 (selected-point
7402 (if (eq interface 'outline)
7403 (car (org-get-location (current-buffer) org-goto-help))
7404 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7405 (org-refile-check-position pa)
7406 (nth 3 pa)))))
7407 (if selected-point
7408 (progn
7409 (org-mark-ring-push org-goto-start-pos)
7410 (goto-char selected-point)
7411 (if (or (outline-invisible-p) (org-invisible-p2))
7412 (org-show-context 'org-goto)))
7413 (message "Quit"))))
7415 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7416 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7417 (defvar org-goto-local-auto-isearch-map) ; defined below
7419 (defun org-get-location (buf help)
7420 "Let the user select a location in the Org-mode buffer BUF.
7421 This function uses a recursive edit. It returns the selected position
7422 or nil."
7423 (org-no-popups
7424 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7425 (isearch-hide-immediately nil)
7426 (isearch-search-fun-function
7427 (lambda () 'org-goto-local-search-headings))
7428 (org-goto-selected-point org-goto-exit-command))
7429 (save-excursion
7430 (save-window-excursion
7431 (delete-other-windows)
7432 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7433 (org-pop-to-buffer-same-window
7434 (condition-case nil
7435 (make-indirect-buffer (current-buffer) "*org-goto*")
7436 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7437 (with-output-to-temp-buffer "*Org Help*"
7438 (princ (format help (if org-goto-auto-isearch
7439 " Just type for auto-isearch."
7440 " n/p/f/b/u to navigate, q to quit."))))
7441 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7442 (setq buffer-read-only nil)
7443 (let ((org-startup-truncated t)
7444 (org-startup-folded nil)
7445 (org-startup-align-all-tables nil))
7446 (org-mode)
7447 (org-overview))
7448 (setq buffer-read-only t)
7449 (if (and (boundp 'org-goto-start-pos)
7450 (integer-or-marker-p org-goto-start-pos))
7451 (let ((org-show-hierarchy-above t)
7452 (org-show-siblings t)
7453 (org-show-following-heading t))
7454 (goto-char org-goto-start-pos)
7455 (and (outline-invisible-p) (org-show-context)))
7456 (goto-char (point-min)))
7457 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7458 (message "Select location and press RET")
7459 (use-local-map org-goto-map)
7460 (recursive-edit)))
7461 (kill-buffer "*org-goto*")
7462 (cons org-goto-selected-point org-goto-exit-command))))
7464 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7465 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7466 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7467 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7469 (defun org-goto-local-search-headings (string bound noerror)
7470 "Search and make sure that any matches are in headlines."
7471 (catch 'return
7472 (while (if isearch-forward
7473 (search-forward string bound noerror)
7474 (search-backward string bound noerror))
7475 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7476 (and (member :headline context)
7477 (not (member :tags context))))
7478 (throw 'return (point))))))
7480 (defun org-goto-local-auto-isearch ()
7481 "Start isearch."
7482 (interactive)
7483 (goto-char (point-min))
7484 (let ((keys (this-command-keys)))
7485 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7486 (isearch-mode t)
7487 (isearch-process-search-char (string-to-char keys)))))
7489 (defun org-goto-ret (&optional arg)
7490 "Finish `org-goto' by going to the new location."
7491 (interactive "P")
7492 (setq org-goto-selected-point (point)
7493 org-goto-exit-command 'return)
7494 (throw 'exit nil))
7496 (defun org-goto-left ()
7497 "Finish `org-goto' by going to the new location."
7498 (interactive)
7499 (if (org-at-heading-p)
7500 (progn
7501 (beginning-of-line 1)
7502 (setq org-goto-selected-point (point)
7503 org-goto-exit-command 'left)
7504 (throw 'exit nil))
7505 (user-error "Not on a heading")))
7507 (defun org-goto-right ()
7508 "Finish `org-goto' by going to the new location."
7509 (interactive)
7510 (if (org-at-heading-p)
7511 (progn
7512 (setq org-goto-selected-point (point)
7513 org-goto-exit-command 'right)
7514 (throw 'exit nil))
7515 (user-error "Not on a heading")))
7517 (defun org-goto-quit ()
7518 "Finish `org-goto' without cursor motion."
7519 (interactive)
7520 (setq org-goto-selected-point nil)
7521 (setq org-goto-exit-command 'quit)
7522 (throw 'exit nil))
7524 ;;; Indirect buffer display of subtrees
7526 (defvar org-indirect-dedicated-frame nil
7527 "This is the frame being used for indirect tree display.")
7528 (defvar org-last-indirect-buffer nil)
7530 (defun org-tree-to-indirect-buffer (&optional arg)
7531 "Create indirect buffer and narrow it to current subtree.
7532 With a numerical prefix ARG, go up to this level and then take that tree.
7533 If ARG is negative, go up that many levels.
7535 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7536 indirect buffer previously made with this command, to avoid proliferation of
7537 indirect buffers. However, when you call the command with a \
7538 \\[universal-argument] prefix, or
7539 when `org-indirect-buffer-display' is `new-frame', the last buffer
7540 is kept so that you can work with several indirect buffers at the same time.
7541 If `org-indirect-buffer-display' is `dedicated-frame', the \
7542 \\[universal-argument] prefix also
7543 requests that a new frame be made for the new buffer, so that the dedicated
7544 frame is not changed."
7545 (interactive "P")
7546 (let ((cbuf (current-buffer))
7547 (cwin (selected-window))
7548 (pos (point))
7549 beg end level heading ibuf)
7550 (save-excursion
7551 (org-back-to-heading t)
7552 (when (numberp arg)
7553 (setq level (org-outline-level))
7554 (if (< arg 0) (setq arg (+ level arg)))
7555 (while (> (setq level (org-outline-level)) arg)
7556 (org-up-heading-safe)))
7557 (setq beg (point)
7558 heading (org-get-heading))
7559 (org-end-of-subtree t t)
7560 (if (org-at-heading-p) (backward-char 1))
7561 (setq end (point)))
7562 (if (and (buffer-live-p org-last-indirect-buffer)
7563 (not (eq org-indirect-buffer-display 'new-frame))
7564 (not arg))
7565 (kill-buffer org-last-indirect-buffer))
7566 (setq ibuf (org-get-indirect-buffer cbuf heading)
7567 org-last-indirect-buffer ibuf)
7568 (cond
7569 ((or (eq org-indirect-buffer-display 'new-frame)
7570 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7571 (select-frame (make-frame))
7572 (delete-other-windows)
7573 (org-pop-to-buffer-same-window ibuf)
7574 (org-set-frame-title heading))
7575 ((eq org-indirect-buffer-display 'dedicated-frame)
7576 (raise-frame
7577 (select-frame (or (and org-indirect-dedicated-frame
7578 (frame-live-p org-indirect-dedicated-frame)
7579 org-indirect-dedicated-frame)
7580 (setq org-indirect-dedicated-frame (make-frame)))))
7581 (delete-other-windows)
7582 (org-pop-to-buffer-same-window ibuf)
7583 (org-set-frame-title (concat "Indirect: " heading)))
7584 ((eq org-indirect-buffer-display 'current-window)
7585 (org-pop-to-buffer-same-window ibuf))
7586 ((eq org-indirect-buffer-display 'other-window)
7587 (pop-to-buffer ibuf))
7588 (t (error "Invalid value")))
7589 (if (featurep 'xemacs)
7590 (save-excursion (org-mode) (turn-on-font-lock)))
7591 (narrow-to-region beg end)
7592 (show-all)
7593 (goto-char pos)
7594 (run-hook-with-args 'org-cycle-hook 'all)
7595 (and (window-live-p cwin) (select-window cwin))))
7597 (defun org-get-indirect-buffer (&optional buffer heading)
7598 (setq buffer (or buffer (current-buffer)))
7599 (let ((n 1) (base (buffer-name buffer)) bname)
7600 (while (buffer-live-p
7601 (get-buffer
7602 (setq bname
7603 (concat base "-"
7604 (if heading (concat heading "-" (number-to-string n))
7605 (number-to-string n))))))
7606 (setq n (1+ n)))
7607 (condition-case nil
7608 (make-indirect-buffer buffer bname 'clone)
7609 (error (make-indirect-buffer buffer bname)))))
7611 (defun org-set-frame-title (title)
7612 "Set the title of the current frame to the string TITLE."
7613 ;; FIXME: how to name a single frame in XEmacs???
7614 (unless (featurep 'xemacs)
7615 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7617 ;;;; Structure editing
7619 ;;; Inserting headlines
7621 (defun org-previous-line-empty-p (&optional next)
7622 "Is the previous line a blank line?
7623 When NEXT is non-nil, check the next line instead."
7624 (save-excursion
7625 (and (not (bobp))
7626 (or (beginning-of-line (if next 2 0)) t)
7627 (save-match-data
7628 (looking-at "[ \t]*$")))))
7630 (defun org-insert-heading (&optional arg invisible-ok)
7631 "Insert a new heading or item with same depth at point.
7632 If point is in a plain list and ARG is nil, create a new list item.
7633 With one universal prefix argument, insert a heading even in lists.
7634 With two universal prefix arguments, insert the heading at the end
7635 of the parent subtree.
7637 If point is at the beginning of a headline, insert a sibling before
7638 the current headline. If point is not at the beginning, split the line
7639 and create a new headline with the text in the current line after point
7640 \(see `org-M-RET-may-split-line' on how to modify this behavior).
7642 If point is at the beginning of a normal line, turn this line into
7643 a heading.
7645 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7646 This is important for non-interactive uses of the command."
7647 (interactive "P")
7648 (if (org-called-interactively-p 'any) (org-reveal))
7649 (let ((itemp (org-in-item-p))
7650 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7651 (respect-content (or org-insert-heading-respect-content
7652 (equal arg '(4))))
7653 (initial-content "")
7654 (adjust-empty-lines t))
7656 (cond
7658 ((or (= (buffer-size) 0)
7659 (and (not (save-excursion
7660 (and (ignore-errors (org-back-to-heading invisible-ok))
7661 (org-at-heading-p))))
7662 (or arg (not itemp))))
7663 ;; At beginning of buffer or so high up that only a heading
7664 ;; makes sense.
7665 (insert
7666 (if (or (bobp) (org-previous-line-empty-p)) "" "\n")
7667 (if (org-in-src-block-p) ",* " "* "))
7668 (run-hooks 'org-insert-heading-hook))
7670 ((and itemp (not (equal arg '(4))))
7671 ;; Insert an item
7672 (org-insert-item))
7675 ;; Maybe move at the end of the subtree
7676 (when (equal arg '(16))
7677 (org-up-heading-safe)
7678 (org-end-of-subtree t))
7679 ;; Insert a heading
7680 (save-restriction
7681 (widen)
7682 (let* ((level nil)
7683 (on-heading (org-at-heading-p))
7684 (empty-line-p (if on-heading
7685 (org-previous-line-empty-p)
7686 ;; We will decide later
7687 nil))
7688 ;; Get a level string to fall back on
7689 (fix-level
7690 (save-excursion
7691 (org-back-to-heading t)
7692 (if (org-previous-line-empty-p) (setq empty-line-p t))
7693 (looking-at org-outline-regexp)
7694 (make-string (1- (length (match-string 0))) ?*)))
7695 (stars
7696 (save-excursion
7697 (condition-case nil
7698 (progn
7699 (org-back-to-heading invisible-ok)
7700 (when (and (not on-heading)
7701 (featurep 'org-inlinetask)
7702 (integerp org-inlinetask-min-level)
7703 (>= (length (match-string 0))
7704 org-inlinetask-min-level))
7705 ;; Find a heading level before the inline task
7706 (while (and (setq level (org-up-heading-safe))
7707 (>= level org-inlinetask-min-level)))
7708 (if (org-at-heading-p)
7709 (org-back-to-heading invisible-ok)
7710 (error "This should not happen")))
7711 (unless (and (save-excursion
7712 (save-match-data
7713 (org-backward-heading-same-level
7714 1 invisible-ok))
7715 (= (point) (match-beginning 0)))
7716 (not (org-previous-line-empty-p t)))
7717 (setq empty-line-p (or empty-line-p
7718 (org-previous-line-empty-p))))
7719 (match-string 0))
7720 (error (or fix-level "* ")))))
7721 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7722 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7723 pos hide-previous previous-pos)
7725 ;; If we insert after content, move there and clean up whitespace
7726 (when respect-content
7727 (org-end-of-subtree nil t)
7728 (skip-chars-backward " \r\n")
7729 (and (not (looking-back "^\*+"))
7730 (looking-at "[ \t]+") (replace-match ""))
7731 (unless (eobp) (forward-char 1))
7732 (when (looking-at "^\\*")
7733 (unless (bobp) (backward-char 1))
7734 (insert "\n")))
7736 ;; If we are splitting, grab the text that should be moved to the new headline
7737 (when may-split
7738 (if (org-on-heading-p)
7739 ;; This is a heading, we split intelligently (keeping tags)
7740 (let ((pos (point)))
7741 (goto-char (point-at-bol))
7742 (unless (looking-at org-complex-heading-regexp)
7743 (error "This should not happen"))
7744 (when (and (match-beginning 4)
7745 (> pos (match-beginning 4))
7746 (< pos (match-end 4)))
7747 (setq initial-content (buffer-substring pos (match-end 4)))
7748 (goto-char pos)
7749 (delete-region (point) (match-end 4))
7750 (if (looking-at "[ \t]*$")
7751 (replace-match "")
7752 (insert (make-string (length initial-content) ?\ )))
7753 (setq initial-content (org-trim initial-content)))
7754 (goto-char pos))
7755 ;; a normal line
7756 (unless (bolp)
7757 (setq initial-content (buffer-substring (point) (point-at-eol)))
7758 (delete-region (point) (point-at-eol))
7759 (setq initial-content (org-trim initial-content)))))
7761 ;; If we are at the beginning of the line, insert before it. Else after
7762 (cond
7763 ((and (bolp) (looking-at "[ \t]*$")))
7764 ((and (bolp) (not (looking-at "[ \t]*$")))
7765 (open-line 1))
7767 (goto-char (point-at-eol))
7768 (insert "\n")))
7770 ;; Insert the new heading
7771 (insert stars)
7772 (just-one-space)
7773 (insert initial-content)
7774 (when adjust-empty-lines
7775 (if (or (not blank)
7776 (and blank (not (org-previous-line-empty-p))))
7777 (org-N-empty-lines-before-current (if blank 1 0))))
7778 (run-hooks 'org-insert-heading-hook)))))))
7780 (defun org-N-empty-lines-before-current (N)
7781 "Make the number of empty lines before current exactly N.
7782 So this will delete or add empty lines."
7783 (save-excursion
7784 (goto-char (point-at-bol))
7785 (if (looking-back "\\s-+" nil 'greedy)
7786 (replace-match ""))
7787 (or (bobp) (insert "\n"))
7788 (while (> N 0)
7789 (insert "\n")
7790 (setq N (1- N)))))
7792 (defun org-get-heading (&optional no-tags no-todo)
7793 "Return the heading of the current entry, without the stars.
7794 When NO-TAGS is non-nil, don't include tags.
7795 When NO-TODO is non-nil, don't include TODO keywords."
7796 (save-excursion
7797 (org-back-to-heading t)
7798 (cond
7799 ((and no-tags no-todo)
7800 (looking-at org-complex-heading-regexp)
7801 (match-string 4))
7802 (no-tags
7803 (looking-at (concat org-outline-regexp
7804 "\\(.*?\\)"
7805 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7806 (match-string 1))
7807 (no-todo
7808 (looking-at org-todo-line-regexp)
7809 (match-string 3))
7810 (t (looking-at org-heading-regexp)
7811 (match-string 2)))))
7813 (defvar orgstruct-mode) ; defined below
7815 (defun org-heading-components ()
7816 "Return the components of the current heading.
7817 This is a list with the following elements:
7818 - the level as an integer
7819 - the reduced level, different if `org-odd-levels-only' is set.
7820 - the TODO keyword, or nil
7821 - the priority character, like ?A, or nil if no priority is given
7822 - the headline text itself, or the tags string if no headline text
7823 - the tags string, or nil."
7824 (save-excursion
7825 (org-back-to-heading t)
7826 (if (let (case-fold-search)
7827 (looking-at
7828 (if orgstruct-mode
7829 org-heading-regexp
7830 org-complex-heading-regexp)))
7831 (if orgstruct-mode
7832 (list (length (match-string 1))
7833 (org-reduced-level (length (match-string 1)))
7836 (match-string 2)
7837 nil)
7838 (list (length (match-string 1))
7839 (org-reduced-level (length (match-string 1)))
7840 (org-match-string-no-properties 2)
7841 (and (match-end 3) (aref (match-string 3) 2))
7842 (org-match-string-no-properties 4)
7843 (org-match-string-no-properties 5))))))
7845 (defun org-get-entry ()
7846 "Get the entry text, after heading, entire subtree."
7847 (save-excursion
7848 (org-back-to-heading t)
7849 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7851 (defun org-insert-heading-after-current ()
7852 "Insert a new heading with same level as current, after current subtree."
7853 (interactive)
7854 (org-back-to-heading)
7855 (org-insert-heading)
7856 (org-move-subtree-down)
7857 (end-of-line 1))
7859 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7860 "Insert heading with `org-insert-heading-respect-content' set to t."
7861 (interactive "P")
7862 (let ((org-insert-heading-respect-content t))
7863 (org-insert-heading '(4) invisible-ok)))
7865 (defun org-insert-todo-heading-respect-content (&optional force-state)
7866 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7867 (interactive "P")
7868 (let ((org-insert-heading-respect-content t))
7869 (org-insert-todo-heading force-state '(4))))
7871 (defun org-insert-todo-heading (arg &optional force-heading)
7872 "Insert a new heading with the same level and TODO state as current heading.
7873 If the heading has no TODO state, or if the state is DONE, use the first
7874 state (TODO by default). Also with one prefix arg, force first state. With
7875 two prefix args, force inserting at the end of the parent subtree."
7876 (interactive "P")
7877 (when (or force-heading (not (org-insert-item 'checkbox)))
7878 (org-insert-heading (or (and (equal arg '(16)) '(16))
7879 force-heading))
7880 (save-excursion
7881 (org-back-to-heading)
7882 (outline-previous-heading)
7883 (looking-at org-todo-line-regexp))
7884 (let*
7885 ((new-mark-x
7886 (if (or (equal arg '(4))
7887 (not (match-beginning 2))
7888 (member (match-string 2) org-done-keywords))
7889 (car org-todo-keywords-1)
7890 (match-string 2)))
7891 (new-mark
7893 (run-hook-with-args-until-success
7894 'org-todo-get-default-hook new-mark-x nil)
7895 new-mark-x)))
7896 (beginning-of-line 1)
7897 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7898 (if org-treat-insert-todo-heading-as-state-change
7899 (org-todo new-mark)
7900 (insert new-mark " "))))
7901 (when org-provide-todo-statistics
7902 (org-update-parent-todo-statistics))))
7904 (defun org-insert-subheading (arg)
7905 "Insert a new subheading and demote it.
7906 Works for outline headings and for plain lists alike."
7907 (interactive "P")
7908 (org-insert-heading arg)
7909 (cond
7910 ((org-at-heading-p) (org-do-demote))
7911 ((org-at-item-p) (org-indent-item))))
7913 (defun org-insert-todo-subheading (arg)
7914 "Insert a new subheading with TODO keyword or checkbox and demote it.
7915 Works for outline headings and for plain lists alike."
7916 (interactive "P")
7917 (org-insert-todo-heading arg)
7918 (cond
7919 ((org-at-heading-p) (org-do-demote))
7920 ((org-at-item-p) (org-indent-item))))
7922 ;;; Promotion and Demotion
7924 (defvar org-after-demote-entry-hook nil
7925 "Hook run after an entry has been demoted.
7926 The cursor will be at the beginning of the entry.
7927 When a subtree is being demoted, the hook will be called for each node.")
7929 (defvar org-after-promote-entry-hook nil
7930 "Hook run after an entry has been promoted.
7931 The cursor will be at the beginning of the entry.
7932 When a subtree is being promoted, the hook will be called for each node.")
7934 (defun org-promote-subtree ()
7935 "Promote the entire subtree.
7936 See also `org-promote'."
7937 (interactive)
7938 (save-excursion
7939 (org-with-limited-levels (org-map-tree 'org-promote)))
7940 (org-fix-position-after-promote))
7942 (defun org-demote-subtree ()
7943 "Demote the entire subtree. See `org-demote'.
7944 See also `org-promote'."
7945 (interactive)
7946 (save-excursion
7947 (org-with-limited-levels (org-map-tree 'org-demote)))
7948 (org-fix-position-after-promote))
7951 (defun org-do-promote ()
7952 "Promote the current heading higher up the tree.
7953 If the region is active in `transient-mark-mode', promote all headings
7954 in the region."
7955 (interactive)
7956 (save-excursion
7957 (if (org-region-active-p)
7958 (org-map-region 'org-promote (region-beginning) (region-end))
7959 (org-promote)))
7960 (org-fix-position-after-promote))
7962 (defun org-do-demote ()
7963 "Demote the current heading lower down the tree.
7964 If the region is active in `transient-mark-mode', demote all headings
7965 in the region."
7966 (interactive)
7967 (save-excursion
7968 (if (org-region-active-p)
7969 (org-map-region 'org-demote (region-beginning) (region-end))
7970 (org-demote)))
7971 (org-fix-position-after-promote))
7973 (defun org-fix-position-after-promote ()
7974 "Make sure that after pro/demotion cursor position is right."
7975 (let ((pos (point)))
7976 (when (save-excursion
7977 (beginning-of-line 1)
7978 (looking-at org-todo-line-regexp)
7979 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7980 (cond ((eobp) (insert " "))
7981 ((eolp) (insert " "))
7982 ((equal (char-after) ?\ ) (forward-char 1))))))
7984 (defun org-current-level ()
7985 "Return the level of the current entry, or nil if before the first headline.
7986 The level is the number of stars at the beginning of the headline."
7987 (save-excursion
7988 (org-with-limited-levels
7989 (if (ignore-errors (org-back-to-heading t))
7990 (funcall outline-level)))))
7992 (defun org-get-previous-line-level ()
7993 "Return the outline depth of the last headline before the current line.
7994 Returns 0 for the first headline in the buffer, and nil if before the
7995 first headline."
7996 (and (org-current-level)
7997 (or (and (/= (line-beginning-position) (point-min))
7998 (save-excursion (beginning-of-line 0) (org-current-level)))
7999 0)))
8001 (defun org-reduced-level (l)
8002 "Compute the effective level of a heading.
8003 This takes into account the setting of `org-odd-levels-only'."
8004 (cond
8005 ((zerop l) 0)
8006 (org-odd-levels-only (1+ (floor (/ l 2))))
8007 (t l)))
8009 (defun org-level-increment ()
8010 "Return the number of stars that will be added or removed at a
8011 time to headlines when structure editing, based on the value of
8012 `org-odd-levels-only'."
8013 (if org-odd-levels-only 2 1))
8015 (defun org-get-valid-level (level &optional change)
8016 "Rectify a level change under the influence of `org-odd-levels-only'
8017 LEVEL is a current level, CHANGE is by how much the level should be
8018 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8019 even level numbers will become the next higher odd number."
8020 (if org-odd-levels-only
8021 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8022 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8023 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8024 (max 1 (+ level (or change 0)))))
8026 (if (boundp 'define-obsolete-function-alias)
8027 (if (or (featurep 'xemacs) (< emacs-major-version 23))
8028 (define-obsolete-function-alias 'org-get-legal-level
8029 'org-get-valid-level)
8030 (define-obsolete-function-alias 'org-get-legal-level
8031 'org-get-valid-level "23.1")))
8033 (defun org-promote ()
8034 "Promote the current heading higher up the tree.
8035 If the region is active in `transient-mark-mode', promote all headings
8036 in the region."
8037 (org-back-to-heading t)
8038 (let* ((level (save-match-data (funcall outline-level)))
8039 (after-change-functions (remove 'flyspell-after-change-function
8040 after-change-functions))
8041 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8042 (diff (abs (- level (length up-head) -1))))
8043 (cond ((and (= level 1) org-called-with-limited-levels
8044 org-allow-promoting-top-level-subtree)
8045 (replace-match "# " nil t))
8046 ((= level 1)
8047 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8048 (t (replace-match up-head nil t)))
8049 ;; Fixup tag positioning
8050 (unless (= level 1)
8051 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
8052 (if org-adapt-indentation (org-fixup-indentation (- diff))))
8053 (run-hooks 'org-after-promote-entry-hook)))
8055 (defun org-demote ()
8056 "Demote the current heading lower down the tree.
8057 If the region is active in `transient-mark-mode', demote all headings
8058 in the region."
8059 (org-back-to-heading t)
8060 (let* ((level (save-match-data (funcall outline-level)))
8061 (after-change-functions (remove 'flyspell-after-change-function
8062 after-change-functions))
8063 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8064 (diff (abs (- level (length down-head) -1))))
8065 (replace-match down-head nil t)
8066 ;; Fixup tag positioning
8067 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
8068 (if org-adapt-indentation (org-fixup-indentation diff))
8069 (run-hooks 'org-after-demote-entry-hook)))
8071 (defun org-cycle-level ()
8072 "Cycle the level of an empty headline through possible states.
8073 This goes first to child, then to parent, level, then up the hierarchy.
8074 After top level, it switches back to sibling level."
8075 (interactive)
8076 (let ((org-adapt-indentation nil))
8077 (when (org-point-at-end-of-empty-headline)
8078 (setq this-command 'org-cycle-level) ; Only needed for caching
8079 (let ((cur-level (org-current-level))
8080 (prev-level (org-get-previous-line-level)))
8081 (cond
8082 ;; If first headline in file, promote to top-level.
8083 ((= prev-level 0)
8084 (loop repeat (/ (- cur-level 1) (org-level-increment))
8085 do (org-do-promote)))
8086 ;; If same level as prev, demote one.
8087 ((= prev-level cur-level)
8088 (org-do-demote))
8089 ;; If parent is top-level, promote to top level if not already.
8090 ((= prev-level 1)
8091 (loop repeat (/ (- cur-level 1) (org-level-increment))
8092 do (org-do-promote)))
8093 ;; If top-level, return to prev-level.
8094 ((= cur-level 1)
8095 (loop repeat (/ (- prev-level 1) (org-level-increment))
8096 do (org-do-demote)))
8097 ;; If less than prev-level, promote one.
8098 ((< cur-level prev-level)
8099 (org-do-promote))
8100 ;; If deeper than prev-level, promote until higher than
8101 ;; prev-level.
8102 ((> cur-level prev-level)
8103 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8104 do (org-do-promote))))
8105 t))))
8107 (defun org-map-tree (fun)
8108 "Call FUN for every heading underneath the current one."
8109 (org-back-to-heading)
8110 (let ((level (funcall outline-level)))
8111 (save-excursion
8112 (funcall fun)
8113 (while (and (progn
8114 (outline-next-heading)
8115 (> (funcall outline-level) level))
8116 (not (eobp)))
8117 (funcall fun)))))
8119 (defun org-map-region (fun beg end)
8120 "Call FUN for every heading between BEG and END."
8121 (let ((org-ignore-region t))
8122 (save-excursion
8123 (setq end (copy-marker end))
8124 (goto-char beg)
8125 (if (and (re-search-forward org-outline-regexp-bol nil t)
8126 (< (point) end))
8127 (funcall fun))
8128 (while (and (progn
8129 (outline-next-heading)
8130 (< (point) end))
8131 (not (eobp)))
8132 (funcall fun)))))
8134 (defvar org-property-end-re) ; silence byte-compiler
8135 (defun org-fixup-indentation (diff)
8136 "Change the indentation in the current entry by DIFF.
8137 However, if any line in the current entry has no indentation, or if it
8138 would end up with no indentation after the change, nothing at all is done."
8139 (save-excursion
8140 (let ((end (save-excursion (outline-next-heading)
8141 (point-marker)))
8142 (prohibit (if (> diff 0)
8143 "^\\S-"
8144 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8145 col)
8146 (unless (save-excursion (end-of-line 1)
8147 (re-search-forward prohibit end t))
8148 (while (and (< (point) end)
8149 (re-search-forward "^[ \t]+" end t))
8150 (goto-char (match-end 0))
8151 (setq col (current-column))
8152 (if (< diff 0) (replace-match ""))
8153 (org-indent-to-column (+ diff col))))
8154 (move-marker end nil))))
8156 (defun org-convert-to-odd-levels ()
8157 "Convert an org-mode file with all levels allowed to one with odd levels.
8158 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8159 level 5 etc."
8160 (interactive)
8161 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8162 (let ((outline-level 'org-outline-level)
8163 (org-odd-levels-only nil) n)
8164 (save-excursion
8165 (goto-char (point-min))
8166 (while (re-search-forward "^\\*\\*+ " nil t)
8167 (setq n (- (length (match-string 0)) 2))
8168 (while (>= (setq n (1- n)) 0)
8169 (org-demote))
8170 (end-of-line 1))))))
8172 (defun org-convert-to-oddeven-levels ()
8173 "Convert an org-mode file with only odd levels to one with odd/even levels.
8174 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8175 file contains a section with an even level, conversion would
8176 destroy the structure of the file. An error is signaled in this
8177 case."
8178 (interactive)
8179 (goto-char (point-min))
8180 ;; First check if there are no even levels
8181 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8182 (org-show-context t)
8183 (error "Not all levels are odd in this file. Conversion not possible"))
8184 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8185 (let ((outline-regexp org-outline-regexp)
8186 (outline-level 'org-outline-level)
8187 (org-odd-levels-only nil) n)
8188 (save-excursion
8189 (goto-char (point-min))
8190 (while (re-search-forward "^\\*\\*+ " nil t)
8191 (setq n (/ (1- (length (match-string 0))) 2))
8192 (while (>= (setq n (1- n)) 0)
8193 (org-promote))
8194 (end-of-line 1))))))
8196 (defun org-tr-level (n)
8197 "Make N odd if required."
8198 (if org-odd-levels-only (1+ (/ n 2)) n))
8200 ;;; Vertical tree motion, cutting and pasting of subtrees
8202 (defun org-move-subtree-up (&optional arg)
8203 "Move the current subtree up past ARG headlines of the same level."
8204 (interactive "p")
8205 (org-move-subtree-down (- (prefix-numeric-value arg))))
8207 (defun org-move-subtree-down (&optional arg)
8208 "Move the current subtree down past ARG headlines of the same level."
8209 (interactive "p")
8210 (setq arg (prefix-numeric-value arg))
8211 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8212 'org-get-last-sibling))
8213 (ins-point (make-marker))
8214 (cnt (abs arg))
8215 (col (current-column))
8216 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8217 ;; Select the tree
8218 (org-back-to-heading)
8219 (setq beg0 (point))
8220 (save-excursion
8221 (setq ne-beg (org-back-over-empty-lines))
8222 (setq beg (point)))
8223 (save-match-data
8224 (save-excursion (outline-end-of-heading)
8225 (setq folded (outline-invisible-p)))
8226 (outline-end-of-subtree))
8227 (outline-next-heading)
8228 (setq ne-end (org-back-over-empty-lines))
8229 (setq end (point))
8230 (goto-char beg0)
8231 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8232 ;; include less whitespace
8233 (save-excursion
8234 (goto-char beg)
8235 (forward-line (- ne-beg ne-end))
8236 (setq beg (point))))
8237 ;; Find insertion point, with error handling
8238 (while (> cnt 0)
8239 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8240 (progn (goto-char beg0)
8241 (user-error "Cannot move past superior level or buffer limit")))
8242 (setq cnt (1- cnt)))
8243 (if (> arg 0)
8244 ;; Moving forward - still need to move over subtree
8245 (progn (org-end-of-subtree t t)
8246 (save-excursion
8247 (org-back-over-empty-lines)
8248 (or (bolp) (newline)))))
8249 (setq ne-ins (org-back-over-empty-lines))
8250 (move-marker ins-point (point))
8251 (setq txt (buffer-substring beg end))
8252 (org-save-markers-in-region beg end)
8253 (delete-region beg end)
8254 (org-remove-empty-overlays-at beg)
8255 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8256 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8257 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8258 (let ((bbb (point)))
8259 (insert-before-markers txt)
8260 (org-reinstall-markers-in-region bbb)
8261 (move-marker ins-point bbb))
8262 (or (bolp) (insert "\n"))
8263 (setq ins-end (point))
8264 (goto-char ins-point)
8265 (org-skip-whitespace)
8266 (when (and (< arg 0)
8267 (org-first-sibling-p)
8268 (> ne-ins ne-beg))
8269 ;; Move whitespace back to beginning
8270 (save-excursion
8271 (goto-char ins-end)
8272 (let ((kill-whole-line t))
8273 (kill-line (- ne-ins ne-beg)) (point)))
8274 (insert (make-string (- ne-ins ne-beg) ?\n)))
8275 (move-marker ins-point nil)
8276 (if folded
8277 (hide-subtree)
8278 (org-show-entry)
8279 (show-children)
8280 (org-cycle-hide-drawers 'children))
8281 (org-clean-visibility-after-subtree-move)
8282 ;; move back to the initial column we were at
8283 (move-to-column col)))
8285 (defvar org-subtree-clip ""
8286 "Clipboard for cut and paste of subtrees.
8287 This is actually only a copy of the kill, because we use the normal kill
8288 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8290 (defvar org-subtree-clip-folded nil
8291 "Was the last copied subtree folded?
8292 This is used to fold the tree back after pasting.")
8294 (defun org-cut-subtree (&optional n)
8295 "Cut the current subtree into the clipboard.
8296 With prefix arg N, cut this many sequential subtrees.
8297 This is a short-hand for marking the subtree and then cutting it."
8298 (interactive "p")
8299 (org-copy-subtree n 'cut))
8301 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8302 "Copy the current subtree it in the clipboard.
8303 With prefix arg N, copy this many sequential subtrees.
8304 This is a short-hand for marking the subtree and then copying it.
8305 If CUT is non-nil, actually cut the subtree.
8306 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8307 of some markers in the region, even if CUT is non-nil. This is
8308 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8309 (interactive "p")
8310 (let (beg end folded (beg0 (point)))
8311 (if (org-called-interactively-p 'any)
8312 (org-back-to-heading nil) ; take what looks like a subtree
8313 (org-back-to-heading t)) ; take what is really there
8314 (setq beg (point))
8315 (skip-chars-forward " \t\r\n")
8316 (save-match-data
8317 (if nosubtrees
8318 (outline-next-heading)
8319 (save-excursion (outline-end-of-heading)
8320 (setq folded (outline-invisible-p)))
8321 (condition-case nil
8322 (org-forward-heading-same-level (1- n) t)
8323 (error nil))
8324 (org-end-of-subtree t t)))
8325 (setq end (point))
8326 (goto-char beg0)
8327 (when (> end beg)
8328 (setq org-subtree-clip-folded folded)
8329 (when (or cut force-store-markers)
8330 (org-save-markers-in-region beg end))
8331 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8332 (setq org-subtree-clip (current-kill 0))
8333 (message "%s: Subtree(s) with %d characters"
8334 (if cut "Cut" "Copied")
8335 (length org-subtree-clip)))))
8337 (defun org-paste-subtree (&optional level tree for-yank)
8338 "Paste the clipboard as a subtree, with modification of headline level.
8339 The entire subtree is promoted or demoted in order to match a new headline
8340 level.
8342 If the cursor is at the beginning of a headline, the same level as
8343 that headline is used to paste the tree.
8345 If not, the new level is derived from the *visible* headings
8346 before and after the insertion point, and taken to be the inferior headline
8347 level of the two. So if the previous visible heading is level 3 and the
8348 next is level 4 (or vice versa), level 4 will be used for insertion.
8349 This makes sure that the subtree remains an independent subtree and does
8350 not swallow low level entries.
8352 You can also force a different level, either by using a numeric prefix
8353 argument, or by inserting the heading marker by hand. For example, if the
8354 cursor is after \"*****\", then the tree will be shifted to level 5.
8356 If optional TREE is given, use this text instead of the kill ring.
8358 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8359 move back over whitespace before inserting, and move point to the end of
8360 the inserted text when done."
8361 (interactive "P")
8362 (setq tree (or tree (and kill-ring (current-kill 0))))
8363 (unless (org-kill-is-subtree-p tree)
8364 (user-error "%s"
8365 (substitute-command-keys
8366 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8367 (org-with-limited-levels
8368 (let* ((visp (not (outline-invisible-p)))
8369 (txt tree)
8370 (^re_ "\\(\\*+\\)[ \t]*")
8371 (old-level (if (string-match org-outline-regexp-bol txt)
8372 (- (match-end 0) (match-beginning 0) 1)
8373 -1))
8374 (force-level (cond (level (prefix-numeric-value level))
8375 ((and (looking-at "[ \t]*$")
8376 (string-match
8377 "^\\*+$" (buffer-substring
8378 (point-at-bol) (point))))
8379 (- (match-end 1) (match-beginning 1)))
8380 ((and (bolp)
8381 (looking-at org-outline-regexp))
8382 (- (match-end 0) (point) 1))))
8383 (previous-level (save-excursion
8384 (condition-case nil
8385 (progn
8386 (outline-previous-visible-heading 1)
8387 (if (looking-at ^re_)
8388 (- (match-end 0) (match-beginning 0) 1)
8390 (error 1))))
8391 (next-level (save-excursion
8392 (condition-case nil
8393 (progn
8394 (or (looking-at org-outline-regexp)
8395 (outline-next-visible-heading 1))
8396 (if (looking-at ^re_)
8397 (- (match-end 0) (match-beginning 0) 1)
8399 (error 1))))
8400 (new-level (or force-level (max previous-level next-level)))
8401 (shift (if (or (= old-level -1)
8402 (= new-level -1)
8403 (= old-level new-level))
8405 (- new-level old-level)))
8406 (delta (if (> shift 0) -1 1))
8407 (func (if (> shift 0) 'org-demote 'org-promote))
8408 (org-odd-levels-only nil)
8409 beg end newend)
8410 ;; Remove the forced level indicator
8411 (if force-level
8412 (delete-region (point-at-bol) (point)))
8413 ;; Paste
8414 (beginning-of-line (if (bolp) 1 2))
8415 (setq beg (point))
8416 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8417 (insert-before-markers txt)
8418 (unless (string-match "\n\\'" txt) (insert "\n"))
8419 (setq newend (point))
8420 (org-reinstall-markers-in-region beg)
8421 (setq end (point))
8422 (goto-char beg)
8423 (skip-chars-forward " \t\n\r")
8424 (setq beg (point))
8425 (if (and (outline-invisible-p) visp)
8426 (save-excursion (outline-show-heading)))
8427 ;; Shift if necessary
8428 (unless (= shift 0)
8429 (save-restriction
8430 (narrow-to-region beg end)
8431 (while (not (= shift 0))
8432 (org-map-region func (point-min) (point-max))
8433 (setq shift (+ delta shift)))
8434 (goto-char (point-min))
8435 (setq newend (point-max))))
8436 (when (or (org-called-interactively-p 'interactive) for-yank)
8437 (message "Clipboard pasted as level %d subtree" new-level))
8438 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8439 kill-ring
8440 (eq org-subtree-clip (current-kill 0))
8441 org-subtree-clip-folded)
8442 ;; The tree was folded before it was killed/copied
8443 (hide-subtree))
8444 (and for-yank (goto-char newend)))))
8446 (defun org-kill-is-subtree-p (&optional txt)
8447 "Check if the current kill is an outline subtree, or a set of trees.
8448 Returns nil if kill does not start with a headline, or if the first
8449 headline level is not the largest headline level in the tree.
8450 So this will actually accept several entries of equal levels as well,
8451 which is OK for `org-paste-subtree'.
8452 If optional TXT is given, check this string instead of the current kill."
8453 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8454 (re (org-get-limited-outline-regexp))
8455 (^re (concat "^" re))
8456 (start-level (and kill
8457 (string-match
8458 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8459 kill)
8460 (- (match-end 2) (match-beginning 2) 1)))
8461 (start (1+ (or (match-beginning 2) -1))))
8462 (if (not start-level)
8463 (progn
8464 nil) ;; does not even start with a heading
8465 (catch 'exit
8466 (while (setq start (string-match ^re kill (1+ start)))
8467 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8468 (throw 'exit nil)))
8469 t))))
8471 (defvar org-markers-to-move nil
8472 "Markers that should be moved with a cut-and-paste operation.
8473 Those markers are stored together with their positions relative to
8474 the start of the region.")
8476 (defun org-save-markers-in-region (beg end)
8477 "Check markers in region.
8478 If these markers are between BEG and END, record their position relative
8479 to BEG, so that after moving the block of text, we can put the markers back
8480 into place.
8481 This function gets called just before an entry or tree gets cut from the
8482 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8483 called immediately, to move the markers with the entries."
8484 (setq org-markers-to-move nil)
8485 (when (featurep 'org-clock)
8486 (org-clock-save-markers-for-cut-and-paste beg end))
8487 (when (featurep 'org-agenda)
8488 (org-agenda-save-markers-for-cut-and-paste beg end)))
8490 (defun org-check-and-save-marker (marker beg end)
8491 "Check if MARKER is between BEG and END.
8492 If yes, remember the marker and the distance to BEG."
8493 (when (and (marker-buffer marker)
8494 (equal (marker-buffer marker) (current-buffer)))
8495 (if (and (>= marker beg) (< marker end))
8496 (push (cons marker (- marker beg)) org-markers-to-move))))
8498 (defun org-reinstall-markers-in-region (beg)
8499 "Move all remembered markers to their position relative to BEG."
8500 (mapc (lambda (x)
8501 (move-marker (car x) (+ beg (cdr x))))
8502 org-markers-to-move)
8503 (setq org-markers-to-move nil))
8505 (defun org-narrow-to-subtree ()
8506 "Narrow buffer to the current subtree."
8507 (interactive)
8508 (save-excursion
8509 (save-match-data
8510 (org-with-limited-levels
8511 (narrow-to-region
8512 (progn (org-back-to-heading t) (point))
8513 (progn (org-end-of-subtree t t)
8514 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8515 (point)))))))
8517 (defun org-narrow-to-block ()
8518 "Narrow buffer to the current block."
8519 (interactive)
8520 (let* ((case-fold-search t)
8521 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8522 "^[ \t]*#\\+end_.*")))
8523 (if blockp
8524 (narrow-to-region (car blockp) (cdr blockp))
8525 (user-error "Not in a block"))))
8527 (eval-when-compile
8528 (defvar org-property-drawer-re))
8530 (defvar org-property-start-re) ;; defined below
8531 (defun org-clone-subtree-with-time-shift (n &optional shift)
8532 "Clone the task (subtree) at point N times.
8533 The clones will be inserted as siblings.
8535 In interactive use, the user will be prompted for the number of
8536 clones to be produced. If the entry has a timestamp, the user
8537 will also be prompted for a time shift, which may be a repeater
8538 as used in time stamps, for example `+3d'. To disable this,
8539 you can call the function with a universal prefix argument.
8541 When a valid repeater is given and the entry contains any time
8542 stamps, the clones will become a sequence in time, with time
8543 stamps in the subtree shifted for each clone produced. If SHIFT
8544 is nil or the empty string, time stamps will be left alone. The
8545 ID property of the original subtree is removed.
8547 If the original subtree did contain time stamps with a repeater,
8548 the following will happen:
8549 - the repeater will be removed in each clone
8550 - an additional clone will be produced, with the current, unshifted
8551 date(s) in the entry.
8552 - the original entry will be placed *after* all the clones, with
8553 repeater intact.
8554 - the start days in the repeater in the original entry will be shifted
8555 to past the last clone.
8556 In this way you can spell out a number of instances of a repeating task,
8557 and still retain the repeater to cover future instances of the task."
8558 (interactive "nNumber of clones to produce: ")
8559 (let ((shift
8560 (or shift
8561 (if (and (not (equal current-prefix-arg '(4)))
8562 (save-excursion
8563 (re-search-forward org-ts-regexp-both
8564 (save-excursion
8565 (org-end-of-subtree t)
8566 (point)) t)))
8567 (read-from-minibuffer
8568 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8569 ""))) ;; No time shift
8570 (n-no-remove -1)
8571 (drawer-re org-drawer-regexp)
8572 beg end template task idprop
8573 shift-n shift-what doshift nmin nmax)
8574 (if (not (and (integerp n) (> n 0)))
8575 (error "Invalid number of replications %s" n))
8576 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8577 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8578 shift)))
8579 (error "Invalid shift specification %s" shift))
8580 (when doshift
8581 (setq shift-n (string-to-number (match-string 1 shift))
8582 shift-what (cdr (assoc (match-string 2 shift)
8583 '(("d" . day) ("w" . week)
8584 ("m" . month) ("y" . year))))))
8585 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8586 (setq nmin 1 nmax n)
8587 (org-back-to-heading t)
8588 (setq beg (point))
8589 (setq idprop (org-entry-get nil "ID"))
8590 (org-end-of-subtree t t)
8591 (or (bolp) (insert "\n"))
8592 (setq end (point))
8593 (setq template (buffer-substring beg end))
8594 (when (and doshift
8595 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8596 (delete-region beg end)
8597 (setq end beg)
8598 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8599 (goto-char end)
8600 (loop for n from nmin to nmax do
8601 ;; prepare clone
8602 (with-temp-buffer
8603 (insert template)
8604 (org-mode)
8605 (goto-char (point-min))
8606 (org-show-subtree)
8607 (and idprop (if org-clone-delete-id
8608 (org-entry-delete nil "ID")
8609 (org-id-get-create t)))
8610 (unless (= n 0)
8611 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8612 (kill-whole-line))
8613 (goto-char (point-min))
8614 (while (re-search-forward drawer-re nil t)
8615 (org-remove-empty-drawer-at (point))))
8616 (goto-char (point-min))
8617 (when doshift
8618 (while (re-search-forward org-ts-regexp-both nil t)
8619 (org-timestamp-change (* n shift-n) shift-what))
8620 (unless (= n n-no-remove)
8621 (goto-char (point-min))
8622 (while (re-search-forward org-ts-regexp nil t)
8623 (save-excursion
8624 (goto-char (match-beginning 0))
8625 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8626 (delete-region (match-beginning 1) (match-end 1)))))))
8627 (setq task (buffer-string)))
8628 (insert task))
8629 (goto-char beg)))
8631 ;;; Outline Sorting
8633 (defun org-sort (with-case)
8634 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8635 Optional argument WITH-CASE means sort case-sensitively."
8636 (interactive "P")
8637 (cond
8638 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8639 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8641 (org-call-with-arg 'org-sort-entries with-case))))
8643 (defun org-sort-remove-invisible (s)
8644 "Remove invisible links from string S."
8645 (remove-text-properties 0 (length s) org-rm-props s)
8646 (while (string-match org-bracket-link-regexp s)
8647 (setq s (replace-match (if (match-end 2)
8648 (match-string 3 s)
8649 (match-string 1 s)) t t s)))
8650 (let ((st (format " %s " s)))
8651 (while (string-match org-emph-re st)
8652 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8653 (setq s (substring st 1 -1)))
8656 (defvar org-priority-regexp) ; defined later in the file
8658 (defvar org-after-sorting-entries-or-items-hook nil
8659 "Hook that is run after a bunch of entries or items have been sorted.
8660 When children are sorted, the cursor is in the parent line when this
8661 hook gets called. When a region or a plain list is sorted, the cursor
8662 will be in the first entry of the sorted region/list.")
8664 (defun org-sort-entries
8665 (&optional with-case sorting-type getkey-func compare-func property)
8666 "Sort entries on a certain level of an outline tree.
8667 If there is an active region, the entries in the region are sorted.
8668 Else, if the cursor is before the first entry, sort the top-level items.
8669 Else, the children of the entry at point are sorted.
8671 Sorting can be alphabetically, numerically, by date/time as given by
8672 a time stamp, by a property, by priority order, or by a custom function.
8674 The command prompts for the sorting type unless it has been given to the
8675 function through the SORTING-TYPE argument, which needs to be a character,
8676 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8677 precise meaning of each character:
8679 n Numerically, by converting the beginning of the entry/item to a number.
8680 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8681 o By order of TODO keywords.
8682 t By date/time, either the first active time stamp in the entry, or, if
8683 none exist, by the first inactive one.
8684 s By the scheduled date/time.
8685 d By deadline date/time.
8686 c By creation time, which is assumed to be the first inactive time stamp
8687 at the beginning of a line.
8688 p By priority according to the cookie.
8689 r By the value of a property.
8691 Capital letters will reverse the sort order.
8693 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8694 called with point at the beginning of the record. It must return either
8695 a string or a number that should serve as the sorting key for that record.
8697 Comparing entries ignores case by default. However, with an optional argument
8698 WITH-CASE, the sorting considers case as well.
8700 Sorting is done against the visible part of the headlines, it ignores hidden
8701 links.
8703 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
8704 (interactive "P")
8705 (let ((case-func (if with-case 'identity 'downcase))
8706 (cmstr
8707 ;; The clock marker is lost when using `sort-subr', let's
8708 ;; store the clocking string.
8709 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8710 (save-excursion
8711 (goto-char org-clock-marker)
8712 (looking-back "^.*") (match-string-no-properties 0))))
8713 start beg end stars re re2
8714 txt what tmp)
8715 ;; Find beginning and end of region to sort
8716 (cond
8717 ((org-region-active-p)
8718 ;; we will sort the region
8719 (setq end (region-end)
8720 what "region")
8721 (goto-char (region-beginning))
8722 (if (not (org-at-heading-p)) (outline-next-heading))
8723 (setq start (point)))
8724 ((or (org-at-heading-p)
8725 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8726 ;; we will sort the children of the current headline
8727 (org-back-to-heading)
8728 (setq start (point)
8729 end (progn (org-end-of-subtree t t)
8730 (or (bolp) (insert "\n"))
8731 (org-back-over-empty-lines)
8732 (point))
8733 what "children")
8734 (goto-char start)
8735 (show-subtree)
8736 (outline-next-heading))
8738 ;; we will sort the top-level entries in this file
8739 (goto-char (point-min))
8740 (or (org-at-heading-p) (outline-next-heading))
8741 (setq start (point))
8742 (goto-char (point-max))
8743 (beginning-of-line 1)
8744 (when (looking-at ".*?\\S-")
8745 ;; File ends in a non-white line
8746 (end-of-line 1)
8747 (insert "\n"))
8748 (setq end (point-max))
8749 (setq what "top-level")
8750 (goto-char start)
8751 (show-all)))
8753 (setq beg (point))
8754 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8756 (looking-at "\\(\\*+\\)")
8757 (setq stars (match-string 1)
8758 re (concat "^" (regexp-quote stars) " +")
8759 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8760 txt (buffer-substring beg end))
8761 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8762 (if (and (not (equal stars "*")) (string-match re2 txt))
8763 (user-error "Region to sort contains a level above the first entry"))
8765 (unless sorting-type
8766 (message
8767 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8768 [t]ime [s]cheduled [d]eadline [c]reated
8769 A/N/P/R/O/F/T/S/D/C means reversed:"
8770 what)
8771 (setq sorting-type (read-char-exclusive))
8773 (unless getkey-func
8774 (and (= (downcase sorting-type) ?f)
8775 (setq getkey-func
8776 (org-icompleting-read "Sort using function: "
8777 obarray 'fboundp t nil nil))
8778 (setq getkey-func (intern getkey-func))))
8780 (and (= (downcase sorting-type) ?r)
8781 (not property)
8782 (setq property
8783 (org-icompleting-read "Property: "
8784 (mapcar 'list (org-buffer-property-keys t))
8785 nil t))))
8787 (message "Sorting entries...")
8789 (save-restriction
8790 (narrow-to-region start end)
8791 (let ((dcst (downcase sorting-type))
8792 (case-fold-search nil)
8793 (now (current-time)))
8794 (sort-subr
8795 (/= dcst sorting-type)
8796 ;; This function moves to the beginning character of the "record" to
8797 ;; be sorted.
8798 (lambda nil
8799 (if (re-search-forward re nil t)
8800 (goto-char (match-beginning 0))
8801 (goto-char (point-max))))
8802 ;; This function moves to the last character of the "record" being
8803 ;; sorted.
8804 (lambda nil
8805 (save-match-data
8806 (condition-case nil
8807 (outline-forward-same-level 1)
8808 (error
8809 (goto-char (point-max))))))
8810 ;; This function returns the value that gets sorted against.
8811 (lambda nil
8812 (cond
8813 ((= dcst ?n)
8814 (if (looking-at org-complex-heading-regexp)
8815 (string-to-number (org-sort-remove-invisible (match-string 4)))
8816 nil))
8817 ((= dcst ?a)
8818 (if (looking-at org-complex-heading-regexp)
8819 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8820 nil))
8821 ((= dcst ?t)
8822 (let ((end (save-excursion (outline-next-heading) (point))))
8823 (if (or (re-search-forward org-ts-regexp end t)
8824 (re-search-forward org-ts-regexp-both end t))
8825 (org-time-string-to-seconds (match-string 0))
8826 (org-float-time now))))
8827 ((= dcst ?c)
8828 (let ((end (save-excursion (outline-next-heading) (point))))
8829 (if (re-search-forward
8830 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8831 end t)
8832 (org-time-string-to-seconds (match-string 0))
8833 (org-float-time now))))
8834 ((= dcst ?s)
8835 (let ((end (save-excursion (outline-next-heading) (point))))
8836 (if (re-search-forward org-scheduled-time-regexp end t)
8837 (org-time-string-to-seconds (match-string 1))
8838 (org-float-time now))))
8839 ((= dcst ?d)
8840 (let ((end (save-excursion (outline-next-heading) (point))))
8841 (if (re-search-forward org-deadline-time-regexp end t)
8842 (org-time-string-to-seconds (match-string 1))
8843 (org-float-time now))))
8844 ((= dcst ?p)
8845 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8846 (string-to-char (match-string 2))
8847 org-default-priority))
8848 ((= dcst ?r)
8849 (or (org-entry-get nil property) ""))
8850 ((= dcst ?o)
8851 (if (looking-at org-complex-heading-regexp)
8852 (- 9999 (length (member (match-string 2)
8853 org-todo-keywords-1)))))
8854 ((= dcst ?f)
8855 (if getkey-func
8856 (progn
8857 (setq tmp (funcall getkey-func))
8858 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8859 tmp)
8860 (error "Invalid key function `%s'" getkey-func)))
8861 (t (error "Invalid sorting type `%c'" sorting-type))))
8863 (cond
8864 ((= dcst ?a) 'string<)
8865 ((= dcst ?f) compare-func)
8866 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8867 (run-hooks 'org-after-sorting-entries-or-items-hook)
8868 ;; Reset the clock marker if needed
8869 (when cmstr
8870 (save-excursion
8871 (goto-char start)
8872 (search-forward cmstr nil t)
8873 (move-marker org-clock-marker (point))))
8874 (message "Sorting entries...done")))
8876 (defun org-do-sort (table what &optional with-case sorting-type)
8877 "Sort TABLE of WHAT according to SORTING-TYPE.
8878 The user will be prompted for the SORTING-TYPE if the call to this
8879 function does not specify it. WHAT is only for the prompt, to indicate
8880 what is being sorted. The sorting key will be extracted from
8881 the car of the elements of the table.
8882 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8883 (unless sorting-type
8884 (message
8885 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8886 what)
8887 (setq sorting-type (read-char-exclusive)))
8888 (let ((dcst (downcase sorting-type))
8889 extractfun comparefun)
8890 ;; Define the appropriate functions
8891 (cond
8892 ((= dcst ?n)
8893 (setq extractfun 'string-to-number
8894 comparefun (if (= dcst sorting-type) '< '>)))
8895 ((= dcst ?a)
8896 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8897 (lambda(x) (downcase (org-sort-remove-invisible x))))
8898 comparefun (if (= dcst sorting-type)
8899 'string<
8900 (lambda (a b) (and (not (string< a b))
8901 (not (string= a b)))))))
8902 ((= dcst ?t)
8903 (setq extractfun
8904 (lambda (x)
8905 (if (or (string-match org-ts-regexp x)
8906 (string-match org-ts-regexp-both x))
8907 (org-float-time
8908 (org-time-string-to-time (match-string 0 x)))
8910 comparefun (if (= dcst sorting-type) '< '>)))
8911 (t (error "Invalid sorting type `%c'" sorting-type)))
8913 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8914 table)
8915 (lambda (a b) (funcall comparefun (car a) (car b))))))
8918 ;;; The orgstruct minor mode
8920 ;; Define a minor mode which can be used in other modes in order to
8921 ;; integrate the org-mode structure editing commands.
8923 ;; This is really a hack, because the org-mode structure commands use
8924 ;; keys which normally belong to the major mode. Here is how it
8925 ;; works: The minor mode defines all the keys necessary to operate the
8926 ;; structure commands, but wraps the commands into a function which
8927 ;; tests if the cursor is currently at a headline or a plain list
8928 ;; item. If that is the case, the structure command is used,
8929 ;; temporarily setting many Org-mode variables like regular
8930 ;; expressions for filling etc. However, when any of those keys is
8931 ;; used at a different location, function uses `key-binding' to look
8932 ;; up if the key has an associated command in another currently active
8933 ;; keymap (minor modes, major mode, global), and executes that
8934 ;; command. There might be problems if any of the keys is otherwise
8935 ;; used as a prefix key.
8937 (defcustom orgstruct-heading-prefix-regexp ""
8938 "Regexp that matches the custom prefix of Org headlines in
8939 orgstruct(++)-mode."
8940 :group 'org
8941 :version "24.4"
8942 :package-version '(Org . "8.3")
8943 :type 'regexp)
8944 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8946 (defcustom orgstruct-setup-hook nil
8947 "Hook run after orgstruct-mode-map is filled."
8948 :group 'org
8949 :version "24.4"
8950 :package-version '(Org . "8.0")
8951 :type 'hook)
8953 (defvar orgstruct-initialized nil)
8955 (defvar org-local-vars nil
8956 "List of local variables, for use by `orgstruct-mode'.")
8958 ;;;###autoload
8959 (define-minor-mode orgstruct-mode
8960 "Toggle the minor mode `orgstruct-mode'.
8961 This mode is for using Org-mode structure commands in other
8962 modes. The following keys behave as if Org-mode were active, if
8963 the cursor is on a headline, or on a plain list item (both as
8964 defined by Org-mode)."
8965 nil " OrgStruct" (make-sparse-keymap)
8966 (funcall (if orgstruct-mode
8967 'add-to-invisibility-spec
8968 'remove-from-invisibility-spec)
8969 '(outline . t))
8970 (when orgstruct-mode
8971 (org-load-modules-maybe)
8972 (unless orgstruct-initialized
8973 (orgstruct-setup)
8974 (setq orgstruct-initialized t))))
8976 ;;;###autoload
8977 (defun turn-on-orgstruct ()
8978 "Unconditionally turn on `orgstruct-mode'."
8979 (orgstruct-mode 1))
8981 (defvar org-fb-vars nil)
8982 (make-variable-buffer-local 'org-fb-vars)
8983 (defun orgstruct++-mode (&optional arg)
8984 "Toggle `orgstruct-mode', the enhanced version of it.
8985 In addition to setting orgstruct-mode, this also exports all
8986 indentation and autofilling variables from org-mode into the
8987 buffer. It will also recognize item context in multiline items."
8988 (interactive "P")
8989 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8990 (if (< arg 1)
8991 (progn (orgstruct-mode -1)
8992 (mapc (lambda(v)
8993 (org-set-local (car v)
8994 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8995 org-fb-vars))
8996 (orgstruct-mode 1)
8997 (setq org-fb-vars nil)
8998 (unless org-local-vars
8999 (setq org-local-vars (org-get-local-variables)))
9000 (let (var val)
9001 (mapc
9002 (lambda (x)
9003 (when (string-match
9004 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
9005 (symbol-name (car x)))
9006 (setq var (car x) val (nth 1 x))
9007 (push (list var `(quote ,(eval var))) org-fb-vars)
9008 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9009 org-local-vars)
9010 (org-set-local 'orgstruct-is-++ t))))
9012 (defvar orgstruct-is-++ nil
9013 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9014 (make-variable-buffer-local 'orgstruct-is-++)
9016 ;;;###autoload
9017 (defun turn-on-orgstruct++ ()
9018 "Unconditionally turn on `orgstruct++-mode'."
9019 (orgstruct++-mode 1))
9021 (defun orgstruct-error ()
9022 "Error when there is no default binding for a structure key."
9023 (interactive)
9024 (funcall (if (fboundp 'user-error)
9025 'user-error
9026 'error)
9027 "This key has no function outside structure elements"))
9029 (defun orgstruct-setup ()
9030 "Setup orgstruct keymap."
9031 (dolist (cell '((org-demote . t)
9032 (org-metaleft . t)
9033 (org-metaright . t)
9034 (org-promote . t)
9035 (org-shiftmetaleft . t)
9036 (org-shiftmetaright . t)
9037 org-backward-element
9038 org-backward-heading-same-level
9039 org-ctrl-c-ret
9040 org-ctrl-c-minus
9041 org-ctrl-c-star
9042 org-cycle
9043 org-forward-heading-same-level
9044 org-insert-heading
9045 org-insert-heading-respect-content
9046 org-kill-note-or-show-branches
9047 org-mark-subtree
9048 org-meta-return
9049 org-metadown
9050 org-metaup
9051 org-narrow-to-subtree
9052 org-promote-subtree
9053 org-reveal
9054 org-shiftdown
9055 org-shiftleft
9056 org-shiftmetadown
9057 org-shiftmetaup
9058 org-shiftright
9059 org-shifttab
9060 org-shifttab
9061 org-shiftup
9062 org-show-subtree
9063 org-sort
9064 org-up-element
9065 outline-demote
9066 outline-next-visible-heading
9067 outline-previous-visible-heading
9068 outline-promote
9069 outline-up-heading
9070 show-children))
9071 (let ((f (or (car-safe cell) cell))
9072 (disable-when-heading-prefix (cdr-safe cell)))
9073 (when (fboundp f)
9074 (let ((new-bindings))
9075 (dolist (binding (nconc (where-is-internal f org-mode-map)
9076 (where-is-internal f outline-mode-map)))
9077 (push binding new-bindings)
9078 ;; TODO use local-function-key-map
9079 (dolist (rep '(("<tab>" . "TAB")
9080 ("<return>" . "RET")
9081 ("<escape>" . "ESC")
9082 ("<delete>" . "DEL")))
9083 (setq binding (read-kbd-macro
9084 (let ((case-fold-search))
9085 (replace-regexp-in-string
9086 (regexp-quote (cdr rep))
9087 (car rep)
9088 (key-description binding)))))
9089 (pushnew binding new-bindings :test 'equal)))
9090 (dolist (binding new-bindings)
9091 (let ((key (lookup-key orgstruct-mode-map binding)))
9092 (when (or (not key) (numberp key))
9093 (condition-case nil
9094 (org-defkey orgstruct-mode-map
9095 binding
9096 (orgstruct-make-binding f binding disable-when-heading-prefix))
9097 (error nil)))))))))
9098 (run-hooks 'orgstruct-setup-hook))
9100 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9101 "Create a function for binding in the structure minor mode.
9102 FUN is the command to call inside a table. KEY is the key that
9103 should be checked in for a command to execute outside of tables.
9104 Non-nil `disable-when-heading-prefix' means to disable the command
9105 if `orgstruct-heading-prefix-regexp' is not empty."
9106 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9107 (let ((nname name)
9108 (i 0))
9109 (while (fboundp (intern nname))
9110 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9111 (setq name (intern nname)))
9112 (eval
9113 (let ((bindings '((org-heading-regexp
9114 (concat "^"
9115 orgstruct-heading-prefix-regexp
9116 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9117 (org-outline-regexp
9118 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9119 (org-outline-regexp-bol
9120 (concat "^" org-outline-regexp))
9121 (outline-regexp org-outline-regexp)
9122 (outline-heading-end-regexp "\n")
9123 (outline-level 'org-outline-level)
9124 (outline-heading-alist))))
9125 `(defun ,name (arg)
9126 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9127 "Outside of structure, run the binding of `"
9128 (key-description key) "'."
9129 (when disable-when-heading-prefix
9130 (concat
9131 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9132 "back to the default binding due to limitations of Org's implementation of\n"
9133 "`" (symbol-name fun) "'.")))
9134 (interactive "p")
9135 (let* ((disable
9136 ,(and disable-when-heading-prefix
9137 '(not (string= orgstruct-heading-prefix-regexp ""))))
9138 (fallback
9139 (or disable
9140 (not
9141 (let* ,bindings
9142 (org-context-p 'headline 'item
9143 ,(when (memq fun
9144 '(org-insert-heading
9145 org-insert-heading-respect-content
9146 org-meta-return))
9147 '(when orgstruct-is-++
9148 'item-body))))))))
9149 (if fallback
9150 (let* ((orgstruct-mode)
9151 (binding
9152 (loop with key = ,key
9153 for rep in
9154 '(nil
9155 ("<\\([^>]*\\)tab>" . "\\1TAB")
9156 ("<\\([^>]*\\)return>" . "\\1RET")
9157 ("<\\([^>]*\\)escape>" . "\\1ESC")
9158 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9160 (when rep
9161 (setq key (read-kbd-macro
9162 (let ((case-fold-search))
9163 (replace-regexp-in-string
9164 (car rep)
9165 (cdr rep)
9166 (key-description key))))))
9167 thereis (key-binding key))))
9168 (if (keymapp binding)
9169 (org-set-transient-map binding)
9170 (let ((func (or binding
9171 (unless disable
9172 'orgstruct-error))))
9173 (when func
9174 (call-interactively func)))))
9175 (org-run-like-in-org-mode
9176 (lambda ()
9177 (interactive)
9178 (let* ,bindings
9179 (call-interactively ',fun)))))))))
9180 name))
9182 (defun org-contextualize-keys (alist contexts)
9183 "Return valid elements in ALIST depending on CONTEXTS.
9185 `org-agenda-custom-commands' or `org-capture-templates' are the
9186 values used for ALIST, and `org-agenda-custom-commands-contexts'
9187 or `org-capture-templates-contexts' are the associated contexts
9188 definitions."
9189 (let ((contexts
9190 ;; normalize contexts
9191 (mapcar
9192 (lambda(c) (cond ((listp (cadr c))
9193 (list (car c) (car c) (cadr c)))
9194 ((string= "" (cadr c))
9195 (list (car c) (car c) (caddr c)))
9196 (t c))) contexts))
9197 (a alist) c r s)
9198 ;; loop over all commands or templates
9199 (while (setq c (pop a))
9200 (let (vrules repl)
9201 (cond
9202 ((not (assoc (car c) contexts))
9203 (push c r))
9204 ((and (assoc (car c) contexts)
9205 (setq vrules (org-contextualize-validate-key
9206 (car c) contexts)))
9207 (mapc (lambda (vr)
9208 (when (not (equal (car vr) (cadr vr)))
9209 (setq repl vr))) vrules)
9210 (if (not repl) (push c r)
9211 (push (cadr repl) s)
9212 (push
9213 (cons (car c)
9214 (cdr (or (assoc (cadr repl) alist)
9215 (error "Undefined key `%s' as contextual replacement for `%s'"
9216 (cadr repl) (car c)))))
9217 r))))))
9218 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9219 (delq
9221 (delete-dups
9222 (mapcar (lambda (x)
9223 (let ((tpl (car x)))
9224 (when (not (delq
9226 (mapcar (lambda(y)
9227 (equal y tpl)) s))) x)))
9228 (reverse r))))))
9230 (defun org-contextualize-validate-key (key contexts)
9231 "Check CONTEXTS for agenda or capture KEY."
9232 (let (r rr res)
9233 (while (setq r (pop contexts))
9234 (mapc
9235 (lambda (rr)
9236 (when
9237 (and (equal key (car r))
9238 (if (functionp rr) (funcall rr)
9239 (or (and (eq (car rr) 'in-file)
9240 (buffer-file-name)
9241 (string-match (cdr rr) (buffer-file-name)))
9242 (and (eq (car rr) 'in-mode)
9243 (string-match (cdr rr) (symbol-name major-mode)))
9244 (and (eq (car rr) 'in-buffer)
9245 (string-match (cdr rr) (buffer-name)))
9246 (if (and (eq (car rr) 'not-in-file)
9247 (buffer-file-name))
9248 (not (string-match (cdr rr) (buffer-file-name)))
9250 (when (eq (car rr) 'not-in-mode)
9251 (not (string-match (cdr rr) (symbol-name major-mode))))
9252 (when (eq (car rr) 'not-in-buffer)
9253 (not (string-match (cdr rr) (buffer-name)))))))
9254 (push r res)))
9255 (car (last r))))
9256 (delete-dups (delq nil res))))
9258 (defun org-context-p (&rest contexts)
9259 "Check if local context is any of CONTEXTS.
9260 Possible values in the list of contexts are `table', `headline', and `item'."
9261 (let ((pos (point)))
9262 (goto-char (point-at-bol))
9263 (prog1 (or (and (memq 'table contexts)
9264 (looking-at "[ \t]*|"))
9265 (and (memq 'headline contexts)
9266 (looking-at org-outline-regexp))
9267 (and (memq 'item contexts)
9268 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9269 (and (memq 'item-body contexts)
9270 (org-in-item-p)))
9271 (goto-char pos))))
9273 (defun org-get-local-variables ()
9274 "Return a list of all local variables in an Org mode buffer."
9275 (let (varlist)
9276 (with-current-buffer (get-buffer-create "*Org tmp*")
9277 (erase-buffer)
9278 (org-mode)
9279 (setq varlist (buffer-local-variables)))
9280 (kill-buffer "*Org tmp*")
9281 (delq nil
9282 (mapcar
9283 (lambda (x)
9284 (setq x
9285 (if (symbolp x)
9286 (list x)
9287 (list (car x) (cdr x))))
9288 (if (and (not (get (car x) 'org-state))
9289 (string-match
9290 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9291 (symbol-name (car x))))
9292 x nil))
9293 varlist))))
9295 (defun org-clone-local-variables (from-buffer &optional regexp)
9296 "Clone local variables from FROM-BUFFER.
9297 Optional argument REGEXP selects variables to clone."
9298 (mapc
9299 (lambda (pair)
9300 (and (symbolp (car pair))
9301 (or (null regexp)
9302 (string-match regexp (symbol-name (car pair))))
9303 (set (make-local-variable (car pair))
9304 (cdr pair))))
9305 (buffer-local-variables from-buffer)))
9307 ;;;###autoload
9308 (defun org-run-like-in-org-mode (cmd)
9309 "Run a command, pretending that the current buffer is in Org-mode.
9310 This will temporarily bind local variables that are typically bound in
9311 Org-mode to the values they have in Org-mode, and then interactively
9312 call CMD."
9313 (org-load-modules-maybe)
9314 (unless org-local-vars
9315 (setq org-local-vars (org-get-local-variables)))
9316 (let (binds)
9317 (dolist (var org-local-vars)
9318 (when (or (not (boundp (car var)))
9319 (eq (symbol-value (car var))
9320 (default-value (car var))))
9321 (push (list (car var) `(quote ,(cadr var))) binds)))
9322 (eval `(let ,binds
9323 (call-interactively (quote ,cmd))))))
9325 ;;;; Archiving
9327 (defun org-get-category (&optional pos force-refresh)
9328 "Get the category applying to position POS."
9329 (save-match-data
9330 (if force-refresh (org-refresh-category-properties))
9331 (let ((pos (or pos (point))))
9332 (or (get-text-property pos 'org-category)
9333 (progn (org-refresh-category-properties)
9334 (get-text-property pos 'org-category))))))
9336 (defun org-refresh-category-properties ()
9337 "Refresh category text properties in the buffer."
9338 (let ((case-fold-search t)
9339 (inhibit-read-only t)
9340 (def-cat (cond
9341 ((null org-category)
9342 (if buffer-file-name
9343 (file-name-sans-extension
9344 (file-name-nondirectory buffer-file-name))
9345 "???"))
9346 ((symbolp org-category) (symbol-name org-category))
9347 (t org-category)))
9348 beg end cat pos optionp)
9349 (org-with-silent-modifications
9350 (save-excursion
9351 (save-restriction
9352 (widen)
9353 (goto-char (point-min))
9354 (put-text-property (point) (point-max) 'org-category def-cat)
9355 (while (re-search-forward
9356 "^[ \t]*\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9357 (setq pos (match-end 0)
9358 optionp (equal (char-after (match-beginning 0)) ?#)
9359 cat (org-trim (match-string 2)))
9360 (if optionp
9361 (setq beg (point-at-bol) end (point-max))
9362 (org-back-to-heading t)
9363 (setq beg (point) end (org-end-of-subtree t t)))
9364 (put-text-property beg end 'org-category cat)
9365 (put-text-property beg end 'org-category-position beg)
9366 (goto-char pos)))))))
9368 (defun org-refresh-properties (dprop tprop)
9369 "Refresh buffer text properties.
9370 DPROP is the drawer property and TPROP is the corresponding text
9371 property to set."
9372 (let ((case-fold-search t)
9373 (inhibit-read-only t) p)
9374 (org-with-silent-modifications
9375 (save-excursion
9376 (save-restriction
9377 (widen)
9378 (goto-char (point-min))
9379 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9380 (setq p (org-match-string-no-properties 1))
9381 (save-excursion
9382 (org-back-to-heading t)
9383 (put-text-property
9384 (point-at-bol) (outline-next-heading) tprop p))))))))
9387 ;;;; Link Stuff
9389 ;;; Link abbreviations
9391 (defun org-link-expand-abbrev (link)
9392 "Apply replacements as defined in `org-link-abbrev-alist'."
9393 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9394 (let* ((key (match-string 1 link))
9395 (as (or (assoc key org-link-abbrev-alist-local)
9396 (assoc key org-link-abbrev-alist)))
9397 (tag (and (match-end 2) (match-string 3 link)))
9398 rpl)
9399 (if (not as)
9400 link
9401 (setq rpl (cdr as))
9402 (cond
9403 ((symbolp rpl) (funcall rpl tag))
9404 ((string-match "%(\\([^)]+\\))" rpl)
9405 (replace-match
9406 (save-match-data
9407 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9408 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9409 ((string-match "%h" rpl)
9410 (replace-match (url-hexify-string (or tag "")) t t rpl))
9411 (t (concat rpl tag)))))
9412 link))
9414 ;;; Storing and inserting links
9416 (defvar org-insert-link-history nil
9417 "Minibuffer history for links inserted with `org-insert-link'.")
9419 (defvar org-stored-links nil
9420 "Contains the links stored with `org-store-link'.")
9422 (defvar org-store-link-plist nil
9423 "Plist with info about the most recently link created with `org-store-link'.")
9425 (defvar org-link-protocols nil
9426 "Link protocols added to Org-mode using `org-add-link-type'.")
9428 (defvar org-store-link-functions nil
9429 "List of functions that are called to create and store a link.
9430 Each function will be called in turn until one returns a non-nil
9431 value. Each function should check if it is responsible for creating
9432 this link (for example by looking at the major mode).
9433 If not, it must exit and return nil.
9434 If yes, it should return a non-nil value after a calling
9435 `org-store-link-props' with a list of properties and values.
9436 Special properties are:
9438 :type The link prefix, like \"http\". This must be given.
9439 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9440 This is obligatory as well.
9441 :description Optional default description for the second pair
9442 of brackets in an Org-mode link. The user can still change
9443 this when inserting this link into an Org-mode buffer.
9445 In addition to these, any additional properties can be specified
9446 and then used in capture templates.")
9448 (defun org-add-link-type (type &optional follow export)
9449 "Add TYPE to the list of `org-link-types'.
9450 Re-compute all regular expressions depending on `org-link-types'
9452 FOLLOW and EXPORT are two functions.
9454 FOLLOW should take the link path as the single argument and do whatever
9455 is necessary to follow the link, for example find a file or display
9456 a mail message.
9458 EXPORT should format the link path for export to one of the export formats.
9459 It should be a function accepting three arguments:
9461 path the path of the link, the text after the prefix (like \"http:\")
9462 desc the description of the link, if any, or a description added by
9463 org-export-normalize-links if there is none
9464 format the export format, a symbol like `html' or `latex' or `ascii'..
9466 The function may use the FORMAT information to return different values
9467 depending on the format. The return value will be put literally into
9468 the exported file. If the return value is nil, this means Org should
9469 do what it normally does with links which do not have EXPORT defined.
9471 Org-mode has a built-in default for exporting links. If you are happy with
9472 this default, there is no need to define an export function for the link
9473 type. For a simple example of an export function, see `org-bbdb.el'."
9474 (add-to-list 'org-link-types type t)
9475 (org-make-link-regexps)
9476 (if (assoc type org-link-protocols)
9477 (setcdr (assoc type org-link-protocols) (list follow export))
9478 (push (list type follow export) org-link-protocols)))
9480 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9481 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9483 ;;;###autoload
9484 (defun org-store-link (arg)
9485 "\\<org-mode-map>Store an org-link to the current location.
9486 This link is added to `org-stored-links' and can later be inserted
9487 into an org-buffer with \\[org-insert-link].
9489 For some link types, a prefix arg is interpreted.
9490 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9491 For file links, arg negates `org-context-in-file-links'.
9493 A double prefix arg force skipping storing functions that are not
9494 part of Org's core.
9496 A triple prefix arg force storing a link for each line in the
9497 active region."
9498 (interactive "P")
9499 (org-load-modules-maybe)
9500 (if (and (equal arg '(64)) (org-region-active-p))
9501 (save-excursion
9502 (let ((end (region-end)))
9503 (goto-char (region-beginning))
9504 (set-mark (point))
9505 (while (< (point-at-eol) end)
9506 (move-end-of-line 1) (activate-mark)
9507 (let (current-prefix-arg)
9508 (call-interactively 'org-store-link))
9509 (move-beginning-of-line 2)
9510 (set-mark (point)))))
9511 (org-with-limited-levels
9512 (setq org-store-link-plist nil)
9513 (let (link cpltxt desc description search
9514 txt custom-id agenda-link sfuns sfunsn)
9515 (cond
9517 ;; Store a link using an external link type
9518 ((and (not (equal arg '(16)))
9519 (setq sfuns
9520 (delq
9521 nil (mapcar (lambda (f)
9522 (let (fs) (if (funcall f) (push f fs))))
9523 org-store-link-functions))
9524 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9525 (or (and (cdr sfuns)
9526 (funcall (intern
9527 (completing-read
9528 "Which function for creating the link? "
9529 sfunsn nil t (car sfunsn)))))
9530 (funcall (caar sfuns)))
9531 (setq link (plist-get org-store-link-plist :link)
9532 desc (or (plist-get org-store-link-plist
9533 :description) link))))
9535 ;; Store a link from a source code buffer
9536 ((org-src-edit-buffer-p)
9537 (let (label gc)
9538 (while (or (not label)
9539 (save-excursion
9540 (save-restriction
9541 (widen)
9542 (goto-char (point-min))
9543 (re-search-forward
9544 (regexp-quote (format org-coderef-label-format label))
9545 nil t))))
9546 (when label (message "Label exists already") (sit-for 2))
9547 (setq label (read-string "Code line label: " label)))
9548 (end-of-line 1)
9549 (setq link (format org-coderef-label-format label))
9550 (setq gc (- 79 (length link)))
9551 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9552 (insert link)
9553 (setq link (concat "(" label ")") desc nil)))
9555 ;; We are in the agenda, link to referenced location
9556 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9557 (let ((m (or (get-text-property (point) 'org-hd-marker)
9558 (get-text-property (point) 'org-marker))))
9559 (when m
9560 (org-with-point-at m
9561 (setq agenda-link
9562 (if (org-called-interactively-p 'any)
9563 (call-interactively 'org-store-link)
9564 (org-store-link nil)))))))
9566 ((eq major-mode 'calendar-mode)
9567 (let ((cd (calendar-cursor-to-date)))
9568 (setq link
9569 (format-time-string
9570 (car org-time-stamp-formats)
9571 (apply 'encode-time
9572 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9573 nil nil nil))))
9574 (org-store-link-props :type "calendar" :date cd)))
9576 ((eq major-mode 'help-mode)
9577 (setq link (concat "help:" (save-excursion
9578 (goto-char (point-min))
9579 (looking-at "^[^ ]+")
9580 (match-string 0))))
9581 (org-store-link-props :type "help"))
9583 ((eq major-mode 'w3-mode)
9584 (setq cpltxt (if (and (buffer-name)
9585 (not (string-match "Untitled" (buffer-name))))
9586 (buffer-name)
9587 (url-view-url t))
9588 link (url-view-url t))
9589 (org-store-link-props :type "w3" :url (url-view-url t)))
9591 ((eq major-mode 'image-mode)
9592 (setq cpltxt (concat "file:"
9593 (abbreviate-file-name buffer-file-name))
9594 link cpltxt)
9595 (org-store-link-props :type "image" :file buffer-file-name))
9597 ;; In dired, store a link to the file of the current line
9598 ((derived-mode-p 'dired-mode)
9599 (let ((file (dired-get-filename nil t)))
9600 (setq file (if file
9601 (abbreviate-file-name
9602 (expand-file-name (dired-get-filename nil t)))
9603 ;; otherwise, no file so use current directory.
9604 default-directory))
9605 (setq cpltxt (concat "file:" file)
9606 link cpltxt)))
9608 ((setq search (run-hook-with-args-until-success
9609 'org-create-file-search-functions))
9610 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9611 "::" search))
9612 (setq cpltxt (or description link)))
9614 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9615 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9616 (cond
9617 ;; Store a link using the target at point
9618 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9619 (setq cpltxt
9620 (concat "file:"
9621 (abbreviate-file-name
9622 (buffer-file-name (buffer-base-buffer)))
9623 "::" (match-string 1))
9624 link cpltxt))
9625 ((and (featurep 'org-id)
9626 (or (eq org-id-link-to-org-use-id t)
9627 (and (org-called-interactively-p 'any)
9628 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9629 (and (eq org-id-link-to-org-use-id
9630 'create-if-interactive-and-no-custom-id)
9631 (not custom-id))))
9632 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9633 ;; Store a link using the ID at point
9634 (setq link (condition-case nil
9635 (prog1 (org-id-store-link)
9636 (setq desc (or (plist-get org-store-link-plist
9637 :description)
9638 "")))
9639 (error
9640 ;; Probably before first headline, link only to file
9641 (concat "file:"
9642 (abbreviate-file-name
9643 (buffer-file-name (buffer-base-buffer))))))))
9645 ;; Just link to current headline
9646 (setq cpltxt (concat "file:"
9647 (abbreviate-file-name
9648 (buffer-file-name (buffer-base-buffer)))))
9649 ;; Add a context search string
9650 (when (org-xor org-context-in-file-links arg)
9651 (let* ((ee (org-element-at-point))
9652 (et (org-element-type ee))
9653 (ev (plist-get (cadr ee) :value))
9654 (ek (plist-get (cadr ee) :key))
9655 (eok (and (stringp ek) (string-match "name" ek))))
9656 (setq txt (cond
9657 ((org-at-heading-p) nil)
9658 ((and (eq et 'keyword) eok) ev)
9659 ((org-region-active-p)
9660 (buffer-substring (region-beginning) (region-end)))))
9661 (when (or (null txt) (string-match "\\S-" txt))
9662 (setq cpltxt
9663 (concat cpltxt "::"
9664 (condition-case nil
9665 (org-make-org-heading-search-string txt)
9666 (error "")))
9667 desc (or (and (eq et 'keyword) eok ev)
9668 (nth 4 (ignore-errors (org-heading-components)))
9669 "NONE")))))
9670 (if (string-match "::\\'" cpltxt)
9671 (setq cpltxt (substring cpltxt 0 -2)))
9672 (setq link cpltxt))))
9674 ((buffer-file-name (buffer-base-buffer))
9675 ;; Just link to this file here.
9676 (setq cpltxt (concat "file:"
9677 (abbreviate-file-name
9678 (buffer-file-name (buffer-base-buffer)))))
9679 ;; Add a context string.
9680 (when (org-xor org-context-in-file-links arg)
9681 (setq txt (if (org-region-active-p)
9682 (buffer-substring (region-beginning) (region-end))
9683 (buffer-substring (point-at-bol) (point-at-eol))))
9684 ;; Only use search option if there is some text.
9685 (when (string-match "\\S-" txt)
9686 (setq cpltxt
9687 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9688 desc "NONE")))
9689 (setq link cpltxt))
9691 ((org-called-interactively-p 'interactive)
9692 (user-error "No method for storing a link from this buffer"))
9694 (t (setq link nil)))
9696 ;; We're done setting link and desc, clean up
9697 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9698 (setq link (or link cpltxt)
9699 desc (or desc cpltxt))
9700 (cond ((equal desc "NONE") (setq desc nil))
9701 ((and desc (string-match org-bracket-link-analytic-regexp desc))
9702 (let ((d0 (match-string 3 desc))
9703 (p0 (match-string 5 desc)))
9704 (setq desc
9705 (replace-regexp-in-string
9706 org-bracket-link-regexp
9707 (concat (or p0 d0)
9708 (if (equal (length (match-string 0 desc))
9709 (length desc)) "*" "")) desc)))))
9711 ;; Return the link
9712 (if (not (and (or (org-called-interactively-p 'any)
9713 executing-kbd-macro) link))
9714 (or agenda-link (and link (org-make-link-string link desc)))
9715 (push (list link desc) org-stored-links)
9716 (message "Stored: %s" (or desc link))
9717 (when custom-id
9718 (setq link (concat "file:" (abbreviate-file-name
9719 (buffer-file-name)) "::#" custom-id))
9720 (push (list link desc) org-stored-links))
9721 (car org-stored-links))))))
9723 (defun org-store-link-props (&rest plist)
9724 "Store link properties, extract names and addresses."
9725 (let (x adr)
9726 (when (setq x (plist-get plist :from))
9727 (setq adr (mail-extract-address-components x))
9728 (setq plist (plist-put plist :fromname (car adr)))
9729 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9730 (when (setq x (plist-get plist :to))
9731 (setq adr (mail-extract-address-components x))
9732 (setq plist (plist-put plist :toname (car adr)))
9733 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9734 (let ((from (plist-get plist :from))
9735 (to (plist-get plist :to)))
9736 (when (and from to org-from-is-user-regexp)
9737 (setq plist
9738 (plist-put plist :fromto
9739 (if (string-match org-from-is-user-regexp from)
9740 (concat "to %t")
9741 (concat "from %f"))))))
9742 (setq org-store-link-plist plist))
9744 (defun org-add-link-props (&rest plist)
9745 "Add these properties to the link property list."
9746 (let (key value)
9747 (while plist
9748 (setq key (pop plist) value (pop plist))
9749 (setq org-store-link-plist
9750 (plist-put org-store-link-plist key value)))))
9752 (defun org-email-link-description (&optional fmt)
9753 "Return the description part of an email link.
9754 This takes information from `org-store-link-plist' and formats it
9755 according to FMT (default from `org-email-link-description-format')."
9756 (setq fmt (or fmt org-email-link-description-format))
9757 (let* ((p org-store-link-plist)
9758 (to (plist-get p :toaddress))
9759 (from (plist-get p :fromaddress))
9760 (table
9761 (list
9762 (cons "%c" (plist-get p :fromto))
9763 (cons "%F" (plist-get p :from))
9764 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9765 (cons "%T" (plist-get p :to))
9766 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9767 (cons "%s" (plist-get p :subject))
9768 (cons "%d" (plist-get p :date))
9769 (cons "%m" (plist-get p :message-id)))))
9770 (when (string-match "%c" fmt)
9771 ;; Check if the user wrote this message
9772 (if (and org-from-is-user-regexp from to
9773 (save-match-data (string-match org-from-is-user-regexp from)))
9774 (setq fmt (replace-match "to %t" t t fmt))
9775 (setq fmt (replace-match "from %f" t t fmt))))
9776 (org-replace-escapes fmt table)))
9778 (defun org-make-org-heading-search-string (&optional string)
9779 "Make search string for the current headline or STRING."
9780 (let ((s (or string
9781 (and (derived-mode-p 'org-mode)
9782 (save-excursion
9783 (org-back-to-heading t)
9784 (org-element-property :raw-value (org-element-at-point))))))
9785 (lines org-context-in-file-links))
9786 (or string (setq s (concat "*" s))) ; Add * for headlines
9787 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9788 (when (and string (integerp lines) (> lines 0))
9789 (let ((slines (org-split-string s "\n")))
9790 (when (< lines (length slines))
9791 (setq s (mapconcat
9792 'identity
9793 (reverse (nthcdr (- (length slines) lines)
9794 (reverse slines))) "\n")))))
9795 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9797 (defun org-make-link-string (link &optional description)
9798 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9799 (unless (string-match "\\S-" link)
9800 (error "Empty link"))
9801 (when (and description
9802 (stringp description)
9803 (not (string-match "\\S-" description)))
9804 (setq description nil))
9805 (when (stringp description)
9806 ;; Remove brackets from the description, they are fatal.
9807 (while (string-match "\\[" description)
9808 (setq description (replace-match "{" t t description)))
9809 (while (string-match "\\]" description)
9810 (setq description (replace-match "}" t t description))))
9811 (when (equal link description)
9812 ;; No description needed, it is identical
9813 (setq description nil))
9814 (when (and (not description)
9815 (not (string-match (org-image-file-name-regexp) link))
9816 (not (equal link (org-link-escape link))))
9817 (setq description (org-extract-attributes link)))
9818 (setq link
9819 (cond ((string-match (org-image-file-name-regexp) link) link)
9820 ((string-match org-link-types-re link)
9821 (concat (match-string 1 link)
9822 (org-link-escape (substring link (match-end 1)))))
9823 (t (org-link-escape link))))
9824 (concat "[[" link "]"
9825 (if description (concat "[" description "]") "")
9826 "]"))
9828 (defconst org-link-escape-chars
9829 ;;%20 %2B %3B %3D %5B %5D
9830 '(?\ ?\+ ?\; ?\= ?\[ ?\])
9831 "List of characters that should be escaped in a link when stored to Org.
9832 This is the list that is used for internal purposes.")
9834 (defconst org-link-escape-chars-browser
9835 ;;%20 %22
9836 '(?\ ?\")
9837 "List of characters to be escaped before handing over to the browser.
9838 If you consider using this constant then you probably want to use
9839 the function `org-link-escape-browser' instead. See there why
9840 this constant is a candidate to be removed once Org drops support
9841 for Emacs 24.1 and 24.2.")
9843 (defun org-link-escape (text &optional table merge)
9844 "Return percent escaped representation of TEXT.
9845 TEXT is a string with the text to escape.
9846 Optional argument TABLE is a list with characters that should be
9847 escaped. When nil, `org-link-escape-chars' is used.
9848 If optional argument MERGE is set, merge TABLE into
9849 `org-link-escape-chars'."
9850 (cond
9851 ((and table merge)
9852 (mapc (lambda (defchr)
9853 (unless (member defchr table)
9854 (setq table (cons defchr table)))) org-link-escape-chars))
9855 ((null table)
9856 (setq table org-link-escape-chars)))
9857 (mapconcat
9858 (lambda (char)
9859 (if (or (member char table)
9860 (and (or (< char 32) (= char ?\%) (> char 126))
9861 org-url-hexify-p))
9862 (mapconcat (lambda (sequence-element)
9863 (format "%%%.2X" sequence-element))
9864 (or (encode-coding-char char 'utf-8)
9865 (error "Unable to percent escape character: %s"
9866 (char-to-string char))) "")
9867 (char-to-string char))) text ""))
9869 (defun org-link-escape-browser (text)
9870 "Escape some characters before handing over to the browser.
9871 This function is a candidate to be removed together with the
9872 constant `org-link-escape-chars-browser' once Org drops support
9873 for Emacs 24.1 and 24.2. All calls to this function will have to
9874 be replaced with `url-encode-url' which is available since Emacs
9875 24.3.1."
9876 ;; Example with the Org link
9877 ;; [[http://lists.gnu.org/archive/cgi-bin/namazu.cgi?idxname=emacs-orgmode&query=%252Bsubject:"Release+8.2"]]
9878 ;; to open the browser with +subject:"Release 8.2" filled into the
9879 ;; query field: In this case the variable TEXT contains the
9880 ;; unescaped [...]=%2Bsubject:"Release+8.2". Then `url-encode-url'
9881 ;; converts correctly to [...]=%2Bsubject:%22Release+8.2%22 or
9882 ;; `org-link-escape' with `org-link-escape-chars-browser' converts
9883 ;; wrongly to [...]=%252Bsubject:%22Release+8.2%22.
9884 (if (fboundp 'url-encode-url)
9885 (url-encode-url text)
9886 (if (org-string-match-p
9887 (concat "[[:nonascii:]" org-link-escape-chars-browser "]")
9888 text)
9889 (org-link-escape text org-link-escape-chars-browser)
9890 text)))
9892 (defun org-link-unescape (str)
9893 "Unhex hexified Unicode strings as returned from the JavaScript function
9894 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9895 (unless (and (null str) (string= "" str))
9896 (let ((pos 0) (case-fold-search t) unhexed)
9897 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9898 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9899 (setq str (replace-match unhexed t t str))
9900 (setq pos (+ pos (length unhexed))))))
9901 str)
9903 (defun org-link-unescape-compound (hex)
9904 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9905 Note: this function also decodes single byte encodings like
9906 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9907 (save-match-data
9908 (let* ((bytes (cdr (split-string hex "%")))
9909 (ret "")
9910 (eat 0)
9911 (sum 0))
9912 (while bytes
9913 (let* ((val (string-to-number (pop bytes) 16))
9914 (shift-xor
9915 (if (= 0 eat)
9916 (cond
9917 ((>= val 252) (cons 6 252))
9918 ((>= val 248) (cons 5 248))
9919 ((>= val 240) (cons 4 240))
9920 ((>= val 224) (cons 3 224))
9921 ((>= val 192) (cons 2 192))
9922 (t (cons 0 0)))
9923 (cons 6 128))))
9924 (if (>= val 192) (setq eat (car shift-xor)))
9925 (setq val (logxor val (cdr shift-xor)))
9926 (setq sum (+ (lsh sum (car shift-xor)) val))
9927 (if (> eat 0) (setq eat (- eat 1)))
9928 (cond
9929 ((= 0 eat) ;multi byte
9930 (setq ret (concat ret (org-char-to-string sum)))
9931 (setq sum 0))
9932 ((not bytes) ; single byte(s)
9933 (setq ret (org-link-unescape-single-byte-sequence hex))))
9934 )) ;; end (while bytes
9935 ret )))
9937 (defun org-link-unescape-single-byte-sequence (hex)
9938 "Unhexify hex-encoded single byte character sequences."
9939 (mapconcat (lambda (byte)
9940 (char-to-string (string-to-number byte 16)))
9941 (cdr (split-string hex "%")) ""))
9943 (defun org-xor (a b)
9944 "Exclusive or."
9945 (if a (not b) b))
9947 (defun org-fixup-message-id-for-http (s)
9948 "Replace special characters in a message id, so it can be used in an http query."
9949 (when (string-match "%" s)
9950 (setq s (mapconcat (lambda (c)
9951 (if (eq c ?%)
9952 "%25"
9953 (char-to-string c)))
9954 s "")))
9955 (while (string-match "<" s)
9956 (setq s (replace-match "%3C" t t s)))
9957 (while (string-match ">" s)
9958 (setq s (replace-match "%3E" t t s)))
9959 (while (string-match "@" s)
9960 (setq s (replace-match "%40" t t s)))
9963 (defun org-link-prettify (link)
9964 "Return a human-readable representation of LINK.
9965 The car of LINK must be a raw link.
9966 The cdr of LINK must be either a link description or nil."
9967 (let ((desc (or (cadr link) "<no description>")))
9968 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9969 "<" (car link) ">")))
9971 ;;;###autoload
9972 (defun org-insert-link-global ()
9973 "Insert a link like Org-mode does.
9974 This command can be called in any mode to insert a link in Org-mode syntax."
9975 (interactive)
9976 (org-load-modules-maybe)
9977 (org-run-like-in-org-mode 'org-insert-link))
9979 (defun org-insert-all-links (arg &optional pre post)
9980 "Insert all links in `org-stored-links'.
9981 When a universal prefix, do not delete the links from `org-stored-links'.
9982 When `ARG' is a number, insert the last N link(s).
9983 `PRE' and `POST' are optional arguments to define a string to
9984 prepend or to append."
9985 (interactive "P")
9986 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
9987 (links (copy-seq org-stored-links))
9988 (pr (or pre "- "))
9989 (po (or post "\n"))
9990 (cnt 1) l)
9991 (if (null org-stored-links)
9992 (message "No link to insert")
9993 (while (and (or (listp arg) (>= arg cnt))
9994 (setq l (if (listp arg)
9995 (pop links)
9996 (pop org-stored-links))))
9997 (setq cnt (1+ cnt))
9998 (insert pr)
9999 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10000 (insert po)))))
10002 (defun org-insert-last-stored-link (arg)
10003 "Insert the last link stored in `org-stored-links'."
10004 (interactive "p")
10005 (org-insert-all-links arg "" "\n"))
10007 (defun org-link-fontify-links-to-this-file ()
10008 "Fontify links to the current file in `org-stored-links'."
10009 (let ((f (buffer-file-name)) a b)
10010 (setq a (mapcar (lambda(l)
10011 (let ((ll (car l)))
10012 (when (and (string-match "^file:\\(.+\\)::" ll)
10013 (equal f (expand-file-name (match-string 1 ll))))
10014 ll)))
10015 org-stored-links))
10016 (when (featurep 'org-id)
10017 (setq b (mapcar (lambda(l)
10018 (let ((ll (car l)))
10019 (when (and (string-match "^id:\\(.+\\)$" ll)
10020 (equal f (expand-file-name
10021 (or (org-id-find-id-file
10022 (match-string 1 ll)) ""))))
10023 ll)))
10024 org-stored-links)))
10025 (mapcar (lambda(l)
10026 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10027 (delq nil (append a b)))))
10029 (defvar org-link-links-in-this-file nil)
10030 (defun org-insert-link (&optional complete-file link-location default-description)
10031 "Insert a link. At the prompt, enter the link.
10033 Completion can be used to insert any of the link protocol prefixes like
10034 http or ftp in use.
10036 The history can be used to select a link previously stored with
10037 `org-store-link'. When the empty string is entered (i.e. if you just
10038 press RET at the prompt), the link defaults to the most recently
10039 stored link. As SPC triggers completion in the minibuffer, you need to
10040 use M-SPC or C-q SPC to force the insertion of a space character.
10042 You will also be prompted for a description, and if one is given, it will
10043 be displayed in the buffer instead of the link.
10045 If there is already a link at point, this command will allow you to edit link
10046 and description parts.
10048 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
10049 be selected using completion. The path to the file will be relative to the
10050 current directory if the file is in the current directory or a subdirectory.
10051 Otherwise, the link will be the absolute path as completed in the minibuffer
10052 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10053 option `org-link-file-path-type'.
10055 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
10056 the current directory or below.
10058 With three \\[universal-argument] prefixes, negate the meaning of
10059 `org-keep-stored-link-after-insertion'.
10061 If `org-make-link-description-function' is non-nil, this function will be
10062 called with the link target, and the result will be the default
10063 link description.
10065 If the LINK-LOCATION parameter is non-nil, this value will be
10066 used as the link location instead of reading one interactively.
10068 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10069 be used as the default description."
10070 (interactive "P")
10071 (let* ((wcf (current-window-configuration))
10072 (origbuf (current-buffer))
10073 (region (if (org-region-active-p)
10074 (buffer-substring (region-beginning) (region-end))))
10075 (remove (and region (list (region-beginning) (region-end))))
10076 (desc region)
10077 tmphist ; byte-compile incorrectly complains about this
10078 (link link-location)
10079 (abbrevs org-link-abbrev-alist-local)
10080 entry file all-prefixes auto-desc)
10081 (cond
10082 (link-location) ; specified by arg, just use it.
10083 ((org-in-regexp org-bracket-link-regexp 1)
10084 ;; We do have a link at point, and we are going to edit it.
10085 (setq remove (list (match-beginning 0) (match-end 0)))
10086 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
10087 (setq link (read-string "Link: "
10088 (org-link-unescape
10089 (org-match-string-no-properties 1)))))
10090 ((or (org-in-regexp org-angle-link-re)
10091 (org-in-regexp org-plain-link-re))
10092 ;; Convert to bracket link
10093 (setq remove (list (match-beginning 0) (match-end 0))
10094 link (read-string "Link: "
10095 (org-remove-angle-brackets (match-string 0)))))
10096 ((member complete-file '((4) (16)))
10097 ;; Completing read for file names.
10098 (setq link (org-file-complete-link complete-file)))
10100 ;; Read link, with completion for stored links.
10101 (org-link-fontify-links-to-this-file)
10102 (org-switch-to-buffer-other-window "*Org Links*")
10103 (with-current-buffer "*Org Links*"
10104 (erase-buffer)
10105 (insert "Insert a link.
10106 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10107 (when org-stored-links
10108 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10109 (insert (mapconcat 'org-link-prettify
10110 (reverse org-stored-links) "\n")))
10111 (goto-char (point-min)))
10112 (let ((cw (selected-window)))
10113 (select-window (get-buffer-window "*Org Links*" 'visible))
10114 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10115 (unless (pos-visible-in-window-p (point-max))
10116 (org-fit-window-to-buffer))
10117 (and (window-live-p cw) (select-window cw)))
10118 ;; Fake a link history, containing the stored links.
10119 (setq tmphist (append (mapcar 'car org-stored-links)
10120 org-insert-link-history))
10121 (setq all-prefixes (append (mapcar 'car abbrevs)
10122 (mapcar 'car org-link-abbrev-alist)
10123 org-link-types))
10124 (unwind-protect
10125 (progn
10126 (setq link
10127 (org-completing-read
10128 "Link: "
10129 (append
10130 (mapcar (lambda (x) (concat x ":"))
10131 all-prefixes)
10132 (mapcar 'car org-stored-links))
10133 nil nil nil
10134 'tmphist
10135 (caar org-stored-links)))
10136 (if (not (string-match "\\S-" link))
10137 (user-error "No link selected"))
10138 (mapc (lambda(l)
10139 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
10140 org-stored-links)
10141 (if (or (member link all-prefixes)
10142 (and (equal ":" (substring link -1))
10143 (member (substring link 0 -1) all-prefixes)
10144 (setq link (substring link 0 -1))))
10145 (setq link (with-current-buffer origbuf
10146 (org-link-try-special-completion link)))))
10147 (set-window-configuration wcf)
10148 (kill-buffer "*Org Links*"))
10149 (setq entry (assoc link org-stored-links))
10150 (or entry (push link org-insert-link-history))
10151 (setq desc (or desc (nth 1 entry)))))
10153 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10154 (not org-keep-stored-link-after-insertion))
10155 (setq org-stored-links (delq (assoc link org-stored-links)
10156 org-stored-links)))
10158 (if (and (string-match org-plain-link-re link)
10159 (not (string-match org-ts-regexp link)))
10160 ;; URL-like link, normalize the use of angular brackets.
10161 (setq link (org-remove-angle-brackets link)))
10163 ;; Check if we are linking to the current file with a search
10164 ;; option If yes, simplify the link by using only the search
10165 ;; option.
10166 (when (and buffer-file-name
10167 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10168 (let* ((path (match-string 1 link))
10169 (case-fold-search nil)
10170 (search (match-string 2 link)))
10171 (save-match-data
10172 (if (equal (file-truename buffer-file-name) (file-truename path))
10173 ;; We are linking to this same file, with a search option
10174 (setq link search)))))
10176 ;; Check if we can/should use a relative path. If yes, simplify the link
10177 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10178 (let* ((type (match-string 1 link))
10179 (path (match-string 2 link))
10180 (origpath path)
10181 (case-fold-search nil))
10182 (cond
10183 ((or (eq org-link-file-path-type 'absolute)
10184 (equal complete-file '(16)))
10185 (setq path (abbreviate-file-name (expand-file-name path))))
10186 ((eq org-link-file-path-type 'noabbrev)
10187 (setq path (expand-file-name path)))
10188 ((eq org-link-file-path-type 'relative)
10189 (setq path (file-relative-name path)))
10191 (save-match-data
10192 (if (string-match (concat "^" (regexp-quote
10193 (expand-file-name
10194 (file-name-as-directory
10195 default-directory))))
10196 (expand-file-name path))
10197 ;; We are linking a file with relative path name.
10198 (setq path (substring (expand-file-name path)
10199 (match-end 0)))
10200 (setq path (abbreviate-file-name (expand-file-name path)))))))
10201 (setq link (concat type path))
10202 (if (equal desc origpath)
10203 (setq desc path))))
10205 (if org-make-link-description-function
10206 (setq desc
10207 (or (condition-case nil
10208 (funcall org-make-link-description-function link desc)
10209 (error (progn (message "Can't get link description from `%s'"
10210 (symbol-name org-make-link-description-function))
10211 (sit-for 2) nil)))
10212 (read-string "Description: " default-description)))
10213 (if default-description (setq desc default-description)
10214 (setq desc (or (and auto-desc desc)
10215 (read-string "Description: " desc)))))
10217 (unless (string-match "\\S-" desc) (setq desc nil))
10218 (if remove (apply 'delete-region remove))
10219 (insert (org-make-link-string link desc))))
10221 (defun org-link-try-special-completion (type)
10222 "If there is completion support for link type TYPE, offer it."
10223 (let ((fun (intern (concat "org-" type "-complete-link"))))
10224 (if (functionp fun)
10225 (funcall fun)
10226 (read-string "Link (no completion support): " (concat type ":")))))
10228 (defun org-file-complete-link (&optional arg)
10229 "Create a file link using completion."
10230 (let (file link)
10231 (setq file (org-iread-file-name "File: "))
10232 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10233 (pwd1 (file-name-as-directory (abbreviate-file-name
10234 (expand-file-name ".")))))
10235 (cond
10236 ((equal arg '(16))
10237 (setq link (concat
10238 "file:"
10239 (abbreviate-file-name (expand-file-name file)))))
10240 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10241 (setq link (concat "file:" (match-string 1 file))))
10242 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10243 (expand-file-name file))
10244 (setq link (concat
10245 "file:" (match-string 1 (expand-file-name file)))))
10246 (t (setq link (concat "file:" file)))))
10247 link))
10249 (defun org-iread-file-name (&rest args)
10250 "Read-file-name using `ido-mode' speedup if available.
10251 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10252 See `read-file-name' for a description of parameters."
10253 (org-without-partial-completion
10254 (if (and org-completion-use-ido
10255 (fboundp 'ido-read-file-name)
10256 (boundp 'ido-mode) ido-mode
10257 (listp (second args)))
10258 (let ((ido-enter-matching-directory nil))
10259 (apply 'ido-read-file-name args))
10260 (apply 'read-file-name args))))
10262 (defun org-completing-read (&rest args)
10263 "Completing-read with SPACE being a normal character."
10264 (let ((enable-recursive-minibuffers t)
10265 (minibuffer-local-completion-map
10266 (copy-keymap minibuffer-local-completion-map)))
10267 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10268 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10269 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10270 (apply 'org-icompleting-read args)))
10272 (defun org-completing-read-no-i (&rest args)
10273 (let (org-completion-use-ido org-completion-use-iswitchb)
10274 (apply 'org-completing-read args)))
10276 (defun org-iswitchb-completing-read (prompt choices &rest args)
10277 "Use iswitch as a completing-read replacement to choose from choices.
10278 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10279 from."
10280 (let* ((iswitchb-use-virtual-buffers nil)
10281 (iswitchb-make-buflist-hook
10282 (lambda ()
10283 (setq iswitchb-temp-buflist choices))))
10284 (iswitchb-read-buffer prompt)))
10286 (defun org-icompleting-read (&rest args)
10287 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10288 (org-without-partial-completion
10289 (if (and org-completion-use-ido
10290 (fboundp 'ido-completing-read)
10291 (boundp 'ido-mode) ido-mode
10292 (listp (second args)))
10293 (let ((ido-enter-matching-directory nil))
10294 (apply 'ido-completing-read (concat (car args))
10295 (if (consp (car (nth 1 args)))
10296 (mapcar 'car (nth 1 args))
10297 (nth 1 args))
10298 (cddr args)))
10299 (if (and org-completion-use-iswitchb
10300 (boundp 'iswitchb-mode) iswitchb-mode
10301 (listp (second args)))
10302 (apply 'org-iswitchb-completing-read (concat (car args))
10303 (if (consp (car (nth 1 args)))
10304 (mapcar 'car (nth 1 args))
10305 (nth 1 args))
10306 (cddr args))
10307 (apply 'completing-read args)))))
10309 (defun org-extract-attributes (s)
10310 "Extract the attributes cookie from a string and set as text property."
10311 (let (a attr (start 0) key value)
10312 (save-match-data
10313 (when (string-match "{{\\([^}]+\\)}}$" s)
10314 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10315 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10316 (setq key (match-string 1 a) value (match-string 2 a)
10317 start (match-end 0)
10318 attr (plist-put attr (intern key) value))))
10319 (org-add-props s nil 'org-attr attr))
10322 ;;; Opening/following a link
10324 (defvar org-link-search-failed nil)
10326 (defvar org-open-link-functions nil
10327 "Hook for functions finding a plain text link.
10328 These functions must take a single argument, the link content.
10329 They will be called for links that look like [[link text][description]]
10330 when LINK TEXT does not have a protocol like \"http:\" and does not look
10331 like a filename (e.g. \"./blue.png\").
10333 These functions will be called *before* Org attempts to resolve the
10334 link by doing text searches in the current buffer - so if you want a
10335 link \"[[target]]\" to still find \"<<target>>\", your function should
10336 handle this as a special case.
10338 When the function does handle the link, it must return a non-nil value.
10339 If it decides that it is not responsible for this link, it must return
10340 nil to indicate that that Org-mode can continue with other options
10341 like exact and fuzzy text search.")
10343 (defun org-next-link (&optional search-backward)
10344 "Move forward to the next link.
10345 If the link is in hidden text, expose it."
10346 (interactive "P")
10347 (when (and org-link-search-failed (eq this-command last-command))
10348 (goto-char (point-min))
10349 (message "Link search wrapped back to beginning of buffer"))
10350 (setq org-link-search-failed nil)
10351 (let* ((pos (point))
10352 (ct (org-context))
10353 (a (assoc :link ct))
10354 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10355 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10356 ((looking-at org-any-link-re)
10357 ;; Don't stay stuck at link without an org-link face
10358 (forward-char (if search-backward -1 1))))
10359 (if (funcall srch-fun org-any-link-re nil t)
10360 (progn
10361 (goto-char (match-beginning 0))
10362 (if (outline-invisible-p) (org-show-context)))
10363 (goto-char pos)
10364 (setq org-link-search-failed t)
10365 (message "No further link found"))))
10367 (defun org-previous-link ()
10368 "Move backward to the previous link.
10369 If the link is in hidden text, expose it."
10370 (interactive)
10371 (funcall 'org-next-link t))
10373 (defun org-translate-link (s)
10374 "Translate a link string if a translation function has been defined."
10375 (if (and org-link-translation-function
10376 (fboundp org-link-translation-function)
10377 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10378 (progn
10379 (setq s (funcall org-link-translation-function
10380 (match-string 1 s) (match-string 2 s)))
10381 (concat (car s) ":" (cdr s)))
10384 (defun org-translate-link-from-planner (type path)
10385 "Translate a link from Emacs Planner syntax so that Org can follow it.
10386 This is still an experimental function, your mileage may vary."
10387 (cond
10388 ((member type '("http" "https" "news" "ftp"))
10389 ;; standard Internet links are the same.
10390 nil)
10391 ((and (equal type "irc") (string-match "^//" path))
10392 ;; Planner has two / at the beginning of an irc link, we have 1.
10393 ;; We should have zero, actually....
10394 (setq path (substring path 1)))
10395 ((and (equal type "lisp") (string-match "^/" path))
10396 ;; Planner has a slash, we do not.
10397 (setq type "elisp" path (substring path 1)))
10398 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10399 ;; A typical message link. Planner has the id after the final slash,
10400 ;; we separate it with a hash mark
10401 (setq path (concat (match-string 1 path) "#"
10402 (org-remove-angle-brackets (match-string 2 path))))))
10403 (cons type path))
10405 (defun org-find-file-at-mouse (ev)
10406 "Open file link or URL at mouse."
10407 (interactive "e")
10408 (mouse-set-point ev)
10409 (org-open-at-point 'in-emacs))
10411 (defun org-open-at-mouse (ev)
10412 "Open file link or URL at mouse.
10413 See the docstring of `org-open-file' for details."
10414 (interactive "e")
10415 (mouse-set-point ev)
10416 (if (eq major-mode 'org-agenda-mode)
10417 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10418 (org-open-at-point))
10420 (defvar org-window-config-before-follow-link nil
10421 "The window configuration before following a link.
10422 This is saved in case the need arises to restore it.")
10424 (defvar org-open-link-marker (make-marker)
10425 "Marker pointing to the location where `org-open-at-point' was called.")
10427 ;;;###autoload
10428 (defun org-open-at-point-global ()
10429 "Follow a link like Org-mode does.
10430 This command can be called in any mode to follow a link that has
10431 Org-mode syntax."
10432 (interactive)
10433 (org-run-like-in-org-mode 'org-open-at-point))
10435 ;;;###autoload
10436 (defun org-open-link-from-string (s &optional arg reference-buffer)
10437 "Open a link in the string S, as if it was in Org-mode."
10438 (interactive "sLink: \nP")
10439 (let ((reference-buffer (or reference-buffer (current-buffer))))
10440 (with-temp-buffer
10441 (let ((org-inhibit-startup (not reference-buffer)))
10442 (org-mode)
10443 (insert s)
10444 (goto-char (point-min))
10445 (when reference-buffer
10446 (setq org-link-abbrev-alist-local
10447 (with-current-buffer reference-buffer
10448 org-link-abbrev-alist-local)))
10449 (org-open-at-point arg reference-buffer)))))
10451 (defvar org-open-at-point-functions nil
10452 "Hook that is run when following a link at point.
10454 Functions in this hook must return t if they identify and follow
10455 a link at point. If they don't find anything interesting at point,
10456 they must return nil.")
10458 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10459 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10460 (defun org-open-at-point (&optional arg reference-buffer)
10461 "Open link, timestamp, footnote or tags at point.
10463 When point is on a link, follow it. Normally, files will be
10464 opened by an appropriate application. If the optional prefix
10465 argument ARG is non-nil, Emacs will visit the file. With
10466 a double prefix argument, try to open outside of Emacs, in the
10467 application the system uses for this file type.
10469 When point is on a timestamp, open the agenda at the day
10470 specified.
10472 When point is a footnote definition, move to the first reference
10473 found. If it is on a reference, move to the associated
10474 definition.
10476 When point is on a headline, display a list of every link in the
10477 entry, so it is possible to pick one, or all, of them. If point
10478 is on a tag, call `org-tags-view' instead.
10480 When optional argument REFERENCE-BUFFER is non-nil, it should
10481 specify a buffer from where the link search should happen. This
10482 is used internally by `org-open-link-from-string'."
10483 (interactive "P")
10484 ;; On a code block, open block's results.
10485 (unless (call-interactively #'org-babel-open-src-block-result)
10486 (org-load-modules-maybe)
10487 (move-marker org-open-link-marker (point))
10488 (setq org-window-config-before-follow-link (current-window-configuration))
10489 (org-remove-occur-highlights nil nil t)
10490 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10491 (let* ((context (org-element-context)) type)
10492 ;; On an unsupported type, check if point is contained within
10493 ;; a support one.
10494 (while (and (not (memq (setq type (org-element-type context))
10495 '(headline inlinetask link footnote-definition
10496 footnote-reference timestamp)))
10497 (setq context (org-element-property :parent context))))
10498 (cond
10499 ;; Unsupported context: return an error.
10500 ((not context) (user-error "No link found"))
10501 ;; On a headline or an inlinetask, but not on a timestamp,
10502 ;; a link, a footnote reference or on tags.
10503 ((and (memq type '(headline inlinetask))
10504 ;; Not on tags.
10505 (progn (save-excursion (beginning-of-line)
10506 (looking-at org-complex-heading-regexp))
10507 (or (not (match-beginning 5))
10508 (< (point) (match-beginning 5)))))
10509 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10510 (links (car data))
10511 (links-end (cdr data)))
10512 (if links
10513 (dolist (link (if (stringp links) (list links) links))
10514 (search-forward link nil links-end)
10515 (goto-char (match-beginning 0))
10516 (org-open-at-point))
10517 (require 'org-attach)
10518 (org-attach-reveal 'if-exists))))
10519 ;; Do nothing on white spaces after an object, unless point
10520 ;; is right after it.
10521 ((> (point)
10522 (save-excursion
10523 (goto-char (org-element-property :end context))
10524 (skip-chars-backward " \t")
10525 (point)))
10526 (user-error "No link found"))
10527 ((eq type 'timestamp) (org-follow-timestamp-link))
10528 ;; On tags within a headline or an inlinetask.
10529 ((and (memq type '(headline inlinetask))
10530 (progn (save-excursion (beginning-of-line)
10531 (looking-at org-complex-heading-regexp))
10532 (and (match-beginning 5)
10533 (>= (point) (match-beginning 5)))))
10534 (org-tags-view arg (substring (match-string 5) 0 -1)))
10535 ((eq type 'link)
10536 (let ((type (org-element-property :type context))
10537 (path (org-link-unescape (org-element-property :path context))))
10538 ;; Switch back to REFERENCE-BUFFER needed when called in
10539 ;; a temporary buffer through `org-open-link-from-string'.
10540 (with-current-buffer (or reference-buffer (current-buffer))
10541 (cond
10542 ((equal type "file")
10543 (if (string-match "[*?{]" (file-name-nondirectory path))
10544 (dired path)
10545 ;; Look into `org-link-protocols' in order to find
10546 ;; a DEDICATED-FUNCTION to open file. The function
10547 ;; will be applied on raw link instead of parsed
10548 ;; link due to the limitation in `org-add-link-type'
10549 ;; ("open" function called with a single argument).
10550 ;; If no such function is found, fallback to
10551 ;; `org-open-file'.
10553 ;; Note : "file+emacs" and "file+sys" types are
10554 ;; hard-coded in order to escape the previous
10555 ;; limitation.
10556 (let* ((option (org-element-property :search-option context))
10557 (app (org-element-property :application context))
10558 (dedicated-function
10559 (nth 1 (assoc app org-link-protocols))))
10560 (if dedicated-function
10561 (funcall dedicated-function
10562 (concat path
10563 (and option (concat "::" option))))
10564 (apply #'org-open-file
10565 path
10566 (cond (arg)
10567 ((equal app "emacs") 'emacs)
10568 ((equal app "sys") 'system))
10569 (cond ((not option) nil)
10570 ((org-string-match-p "\\`[0-9]+\\'" option)
10571 (list (string-to-number option)))
10572 (t (list nil
10573 (org-link-unescape option)))))))))
10574 ((assoc type org-link-protocols)
10575 (funcall (nth 1 (assoc type org-link-protocols)) path))
10576 ((equal type "help")
10577 (let ((f-or-v (intern path)))
10578 (cond ((fboundp f-or-v) (describe-function f-or-v))
10579 ((boundp f-or-v) (describe-variable f-or-v))
10580 (t (error "Not a known function or variable")))))
10581 ((equal type "mailto")
10582 (let ((cmd (car org-link-mailto-program))
10583 (args (cdr org-link-mailto-program))
10584 (spec
10585 (format-spec-make
10586 ?a path ; %a is address.
10587 ?s (let ((option ; %s is subject.
10588 (org-element-property
10589 :search-option context)))
10590 (if (not option) "" (org-link-escape option)))))
10591 final-args)
10592 (apply cmd
10593 (dolist (arg args (nreverse final-args))
10594 (if (not (stringp arg)) (push arg final-args)
10595 (push (format-spec arg spec) final-args))))))
10596 ((member type '("http" "https" "ftp" "news"))
10597 (browse-url (org-link-escape-browser (concat type ":" path))))
10598 ((equal type "doi")
10599 (browse-url
10600 (org-link-escape-browser (concat org-doi-server-url path))))
10601 ((equal type "message") (browse-url (concat type ":" path)))
10602 ((equal type "shell")
10603 (let ((buf (generate-new-buffer "*Org Shell Output"))
10604 (cmd path))
10605 (if (or (and (org-string-nw-p
10606 org-confirm-shell-link-not-regexp)
10607 (string-match
10608 org-confirm-shell-link-not-regexp cmd))
10609 (not org-confirm-shell-link-function)
10610 (funcall org-confirm-shell-link-function
10611 (format "Execute \"%s\" in shell? "
10612 (org-add-props cmd nil
10613 'face 'org-warning))))
10614 (progn
10615 (message "Executing %s" cmd)
10616 (shell-command cmd buf)
10617 (when (featurep 'midnight)
10618 (setq clean-buffer-list-kill-buffer-names
10619 (cons buf
10620 clean-buffer-list-kill-buffer-names))))
10621 (error "Abort"))))
10622 ((equal type "elisp")
10623 (let ((cmd path))
10624 (if (or (and (org-string-nw-p
10625 org-confirm-elisp-link-not-regexp)
10626 (org-string-match-p
10627 org-confirm-elisp-link-not-regexp cmd))
10628 (not org-confirm-elisp-link-function)
10629 (funcall org-confirm-elisp-link-function
10630 (format "Execute \"%s\" as elisp? "
10631 (org-add-props cmd nil
10632 'face 'org-warning))))
10633 (message "%s => %s" cmd
10634 (if (eq (string-to-char cmd) ?\()
10635 (eval (read cmd))
10636 (call-interactively (read cmd))))
10637 (error "Abort"))))
10638 ((equal type "id")
10639 (require 'ord-id)
10640 (funcall (nth 1 (assoc "id" org-link-protocols)) path))
10641 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10642 (unless (run-hook-with-args-until-success
10643 'org-open-link-functions path)
10644 (if (not arg) (org-mark-ring-push)
10645 (switch-to-buffer-other-window
10646 (org-get-buffer-for-internal-link (current-buffer))))
10647 (let ((cmd `(org-link-search
10648 ,(if (member type '("custom-id" "coderef"))
10649 (org-element-property :raw-link context)
10650 path)
10651 ,(cond ((equal arg '(4)) 'occur)
10652 ((equal arg '(16)) 'org-occur))
10653 ,(org-element-property :begin context))))
10654 (condition-case nil
10655 (let ((org-link-search-inhibit-query t))
10656 (eval cmd))
10657 (error (progn (widen) (eval cmd)))))))
10658 (t (browse-url-at-point))))))
10659 ;; On a footnote reference or at a footnote definition's label.
10660 ((or (eq type 'footnote-reference)
10661 (and (eq type 'footnote-definition)
10662 (save-excursion
10663 ;; Do not validate action when point is on the
10664 ;; spaces right after the footnote label, in
10665 ;; order to be on par with behaviour on links.
10666 (skip-chars-forward " \t")
10667 (let ((begin
10668 (org-element-property :contents-begin context)))
10669 (if begin (< (point) begin)
10670 (= (org-element-property :post-affiliated context)
10671 (line-beginning-position)))))))
10672 (org-footnote-action))
10673 (t (user-error "No link found")))))
10674 (move-marker org-open-link-marker nil)
10675 (run-hook-with-args 'org-follow-link-hook)))
10677 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10678 "Offer links in the current entry and return the selected link.
10679 If there is only one link, return it.
10680 If NTH is an integer, return the NTH link found.
10681 If ZERO is a string, check also this string for a link, and if
10682 there is one, return it."
10683 (with-current-buffer buffer
10684 (save-excursion
10685 (save-restriction
10686 (widen)
10687 (goto-char marker)
10688 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10689 "\\(" org-angle-link-re "\\)\\|"
10690 "\\(" org-plain-link-re "\\)"))
10691 (cnt ?0)
10692 (in-emacs (if (integerp nth) nil nth))
10693 have-zero end links link c)
10694 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10695 (push (match-string 0 zero) links)
10696 (setq cnt (1- cnt) have-zero t))
10697 (save-excursion
10698 (org-back-to-heading t)
10699 (setq end (save-excursion (outline-next-heading) (point)))
10700 (while (re-search-forward re end t)
10701 (push (match-string 0) links))
10702 (setq links (org-uniquify (reverse links))))
10703 (cond
10704 ((null links)
10705 (message "No links"))
10706 ((equal (length links) 1)
10707 (setq link (car links)))
10708 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10709 (setq link (nth (if have-zero nth (1- nth)) links)))
10710 (t ; we have to select a link
10711 (save-excursion
10712 (save-window-excursion
10713 (delete-other-windows)
10714 (with-output-to-temp-buffer "*Select Link*"
10715 (mapc (lambda (l)
10716 (if (not (string-match org-bracket-link-regexp l))
10717 (princ (format "[%c] %s\n" (incf cnt)
10718 (org-remove-angle-brackets l)))
10719 (if (match-end 3)
10720 (princ (format "[%c] %s (%s)\n" (incf cnt)
10721 (match-string 3 l) (match-string 1 l)))
10722 (princ (format "[%c] %s\n" (incf cnt)
10723 (match-string 1 l))))))
10724 links))
10725 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10726 (message "Select link to open, RET to open all:")
10727 (setq c (read-char-exclusive))
10728 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10729 (when (equal c ?q) (error "Abort"))
10730 (if (equal c ?\C-m)
10731 (setq link links)
10732 (setq nth (- c ?0))
10733 (if have-zero (setq nth (1+ nth)))
10734 (unless (and (integerp nth) (>= (length links) nth))
10735 (user-error "Invalid link selection"))
10736 (setq link (nth (1- nth) links)))))
10737 (cons link end))))))
10739 ;; TODO: These functions are deprecated since `org-open-at-point'
10740 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10741 (defun org-open-file-with-system (path)
10742 "Open file at PATH using the system way of opening it."
10743 (org-open-file path 'system))
10744 (defun org-open-file-with-emacs (path)
10745 "Open file at PATH in Emacs."
10746 (org-open-file path 'emacs))
10749 ;;; File search
10751 (defvar org-create-file-search-functions nil
10752 "List of functions to construct the right search string for a file link.
10753 These functions are called in turn with point at the location to
10754 which the link should point.
10756 A function in the hook should first test if it would like to
10757 handle this file type, for example by checking the `major-mode'
10758 or the file extension. If it decides not to handle this file, it
10759 should just return nil to give other functions a chance. If it
10760 does handle the file, it must return the search string to be used
10761 when following the link. The search string will be part of the
10762 file link, given after a double colon, and `org-open-at-point'
10763 will automatically search for it. If special measures must be
10764 taken to make the search successful, another function should be
10765 added to the companion hook `org-execute-file-search-functions',
10766 which see.
10768 A function in this hook may also use `setq' to set the variable
10769 `description' to provide a suggestion for the descriptive text to
10770 be used for this link when it gets inserted into an Org-mode
10771 buffer with \\[org-insert-link].")
10773 (defvar org-execute-file-search-functions nil
10774 "List of functions to execute a file search triggered by a link.
10776 Functions added to this hook must accept a single argument, the
10777 search string that was part of the file link, the part after the
10778 double colon. The function must first check if it would like to
10779 handle this search, for example by checking the `major-mode' or
10780 the file extension. If it decides not to handle this search, it
10781 should just return nil to give other functions a chance. If it
10782 does handle the search, it must return a non-nil value to keep
10783 other functions from trying.
10785 Each function can access the current prefix argument through the
10786 variable `current-prefix-arg'. Note that a single prefix is used
10787 to force opening a link in Emacs, so it may be good to only use a
10788 numeric or double prefix to guide the search function.
10790 In case this is needed, a function in this hook can also restore
10791 the window configuration before `org-open-at-point' was called using:
10793 (set-window-configuration org-window-config-before-follow-link)")
10795 (defun org-link-search (s &optional type avoid-pos stealth)
10796 "Search for a link search option.
10797 If S is surrounded by forward slashes, it is interpreted as a
10798 regular expression. In org-mode files, this will create an `org-occur'
10799 sparse tree. In ordinary files, `occur' will be used to list matches.
10800 If the current buffer is in `dired-mode', grep will be used to search
10801 in all files. If AVOID-POS is given, ignore matches near that position.
10803 When optional argument STEALTH is non-nil, do not modify
10804 visibility around point, thus ignoring
10805 `org-show-hierarchy-above', `org-show-following-heading' and
10806 `org-show-siblings' variables."
10807 (let ((case-fold-search t)
10808 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10809 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10810 (append '(("") (" ") ("\t") ("\n"))
10811 org-emphasis-alist)
10812 "\\|") "\\)"))
10813 (pos (point))
10814 (pre nil) (post nil)
10815 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10816 (cond
10817 ;; First check if there are any special search functions
10818 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10819 ;; Now try the builtin stuff
10820 ((and (equal (string-to-char s0) ?#)
10821 (> (length s0) 1)
10822 (save-excursion
10823 (goto-char (point-min))
10824 (and
10825 (re-search-forward
10826 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10827 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10828 (setq type 'dedicated
10829 pos (match-beginning 0))))
10830 ;; There is an exact target for this
10831 (goto-char pos)
10832 (org-back-to-heading t)))
10833 ((save-excursion
10834 (goto-char (point-min))
10835 (and
10836 (re-search-forward
10837 (concat "<<" (regexp-quote s0) ">>") nil t)
10838 (setq type 'dedicated
10839 pos (match-beginning 0))))
10840 ;; There is an exact target for this
10841 (goto-char pos))
10842 ((save-excursion
10843 (goto-char (point-min))
10844 (and
10845 (re-search-forward
10846 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10847 (setq type 'dedicated pos (match-beginning 0))))
10848 ;; Found an element with a matching #+name affiliated keyword.
10849 (goto-char pos))
10850 ((and (string-match "^(\\(.*\\))$" s0)
10851 (save-excursion
10852 (goto-char (point-min))
10853 (and
10854 (re-search-forward
10855 (concat "[^[]" (regexp-quote
10856 (format org-coderef-label-format
10857 (match-string 1 s0))))
10858 nil t)
10859 (setq type 'dedicated
10860 pos (1+ (match-beginning 0))))))
10861 ;; There is a coderef target for this
10862 (goto-char pos))
10863 ((string-match "^/\\(.*\\)/$" s)
10864 ;; A regular expression
10865 (cond
10866 ((derived-mode-p 'org-mode)
10867 (org-occur (match-string 1 s)))
10868 (t (org-do-occur (match-string 1 s)))))
10869 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10870 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10871 (goto-char (point-min))
10872 (cond
10873 ((let (case-fold-search)
10874 (re-search-forward (format org-complex-heading-regexp-format
10875 (regexp-quote s))
10876 nil t))
10877 ;; OK, found a match
10878 (setq type 'dedicated)
10879 (goto-char (match-beginning 0)))
10880 ((and (not org-link-search-inhibit-query)
10881 (eq org-link-search-must-match-exact-headline 'query-to-create)
10882 (y-or-n-p "No match - create this as a new heading? "))
10883 (goto-char (point-max))
10884 (or (bolp) (newline))
10885 (insert "* " s "\n")
10886 (beginning-of-line 0))
10888 (goto-char pos)
10889 (error "No match"))))
10891 ;; A normal search string
10892 (when (equal (string-to-char s) ?*)
10893 ;; Anchor on headlines, post may include tags.
10894 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10895 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10896 s (substring s 1)))
10897 (remove-text-properties
10898 0 (length s)
10899 '(face nil mouse-face nil keymap nil fontified nil) s)
10900 ;; Make a series of regular expressions to find a match
10901 (setq words (org-split-string s "[ \n\r\t]+")
10903 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10904 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10905 "\\)" markers)
10906 re2a_ (concat "\\(" (mapconcat 'downcase words
10907 "[ \t\r\n]+") "\\)[ \t\r\n]")
10908 re2a (concat "[ \t\r\n]" re2a_)
10909 re4_ (concat "\\(" (mapconcat 'downcase words
10910 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10911 re4 (concat "[^a-zA-Z_]" re4_)
10913 re1 (concat pre re2 post)
10914 re3 (concat pre (if pre re4_ re4) post)
10915 re5 (concat pre ".*" re4)
10916 re2 (concat pre re2)
10917 re2a (concat pre (if pre re2a_ re2a))
10918 re4 (concat pre (if pre re4_ re4))
10919 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10920 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10921 re5 "\\)"))
10922 (cond
10923 ((eq type 'org-occur) (org-occur reall))
10924 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10925 (t (goto-char (point-min))
10926 (setq type 'fuzzy)
10927 (if (or (and (org-search-not-self 1 re0 nil t)
10928 (setq type 'dedicated))
10929 (org-search-not-self 1 re1 nil t)
10930 (org-search-not-self 1 re2 nil t)
10931 (org-search-not-self 1 re2a nil t)
10932 (org-search-not-self 1 re3 nil t)
10933 (org-search-not-self 1 re4 nil t)
10934 (org-search-not-self 1 re5 nil t))
10935 (goto-char (match-beginning 1))
10936 (goto-char pos)
10937 (error "No match"))))))
10938 (and (derived-mode-p 'org-mode)
10939 (not stealth)
10940 (org-show-context 'link-search))
10941 type))
10943 (defun org-search-not-self (group &rest args)
10944 "Execute `re-search-forward', but only accept matches that do not
10945 enclose the position of `org-open-link-marker'."
10946 (let ((m org-open-link-marker))
10947 (catch 'exit
10948 (while (apply 're-search-forward args)
10949 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10950 (goto-char (match-end group))
10951 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10952 (> (match-beginning 0) (marker-position m))
10953 (< (match-end 0) (marker-position m)))
10954 (save-match-data
10955 (or (not (org-in-regexp
10956 org-bracket-link-analytic-regexp 1))
10957 (not (match-end 4)) ; no description
10958 (and (<= (match-beginning 4) (point))
10959 (>= (match-end 4) (point))))))
10960 (throw 'exit (point))))))))
10962 (defun org-get-buffer-for-internal-link (buffer)
10963 "Return a buffer to be used for displaying the link target of internal links."
10964 (cond
10965 ((not org-display-internal-link-with-indirect-buffer)
10966 buffer)
10967 ((string-match "(Clone)$" (buffer-name buffer))
10968 (message "Buffer is already a clone, not making another one")
10969 ;; we also do not modify visibility in this case
10970 buffer)
10971 (t ; make a new indirect buffer for displaying the link
10972 (let* ((bn (buffer-name buffer))
10973 (ibn (concat bn "(Clone)"))
10974 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10975 (with-current-buffer ib (org-overview))
10976 ib))))
10978 (defun org-do-occur (regexp &optional cleanup)
10979 "Call the Emacs command `occur'.
10980 If CLEANUP is non-nil, remove the printout of the regular expression
10981 in the *Occur* buffer. This is useful if the regex is long and not useful
10982 to read."
10983 (occur regexp)
10984 (when cleanup
10985 (let ((cwin (selected-window)) win beg end)
10986 (when (setq win (get-buffer-window "*Occur*"))
10987 (select-window win))
10988 (goto-char (point-min))
10989 (when (re-search-forward "match[a-z]+" nil t)
10990 (setq beg (match-end 0))
10991 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10992 (setq end (1- (match-beginning 0)))))
10993 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10994 (goto-char (point-min))
10995 (select-window cwin))))
10997 ;;; The mark ring for links jumps
10999 (defvar org-mark-ring nil
11000 "Mark ring for positions before jumps in Org-mode.")
11001 (defvar org-mark-ring-last-goto nil
11002 "Last position in the mark ring used to go back.")
11003 ;; Fill and close the ring
11004 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11005 (loop for i from 1 to org-mark-ring-length do
11006 (push (make-marker) org-mark-ring))
11007 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11008 org-mark-ring)
11010 (defun org-mark-ring-push (&optional pos buffer)
11011 "Put the current position or POS into the mark ring and rotate it."
11012 (interactive)
11013 (setq pos (or pos (point)))
11014 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11015 (move-marker (car org-mark-ring)
11016 (or pos (point))
11017 (or buffer (current-buffer)))
11018 (message "%s"
11019 (substitute-command-keys
11020 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
11022 (defun org-mark-ring-goto (&optional n)
11023 "Jump to the previous position in the mark ring.
11024 With prefix arg N, jump back that many stored positions. When
11025 called several times in succession, walk through the entire ring.
11026 Org-mode commands jumping to a different position in the current file,
11027 or to another Org-mode file, automatically push the old position
11028 onto the ring."
11029 (interactive "p")
11030 (let (p m)
11031 (if (eq last-command this-command)
11032 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11033 (setq p org-mark-ring))
11034 (setq org-mark-ring-last-goto p)
11035 (setq m (car p))
11036 (org-pop-to-buffer-same-window (marker-buffer m))
11037 (goto-char m)
11038 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11040 (defun org-remove-angle-brackets (s)
11041 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
11042 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
11044 (defun org-add-angle-brackets (s)
11045 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
11046 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
11048 (defun org-remove-double-quotes (s)
11049 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
11050 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
11053 ;;; Following specific links
11055 (defun org-follow-timestamp-link ()
11056 "Open an agenda view for the time-stamp date/range at point."
11057 (cond
11058 ((org-at-date-range-p t)
11059 (let ((org-agenda-start-on-weekday)
11060 (t1 (match-string 1))
11061 (t2 (match-string 2)) tt1 tt2)
11062 (setq tt1 (time-to-days (org-time-string-to-time t1))
11063 tt2 (time-to-days (org-time-string-to-time t2)))
11064 (let ((org-agenda-buffer-tmp-name
11065 (format "*Org Agenda(a:%s)"
11066 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11067 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11068 ((org-at-timestamp-p t)
11069 (let ((org-agenda-buffer-tmp-name
11070 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11071 (org-agenda-list nil (time-to-days (org-time-string-to-time
11072 (substring (match-string 1) 0 10)))
11073 1)))
11074 (t (error "This should not happen"))))
11077 ;;; Following file links
11078 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11079 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11080 (declare-function mailcap-mime-info
11081 "mailcap" (string &optional request no-decode))
11082 (defvar org-wait nil)
11083 (defun org-open-file (path &optional in-emacs line search)
11084 "Open the file at PATH.
11085 First, this expands any special file name abbreviations. Then the
11086 configuration variable `org-file-apps' is checked if it contains an
11087 entry for this file type, and if yes, the corresponding command is launched.
11089 If no application is found, Emacs simply visits the file.
11091 With optional prefix argument IN-EMACS, Emacs will visit the file.
11092 With a double \\[universal-argument] \\[universal-argument] \
11093 prefix arg, Org tries to avoid opening in Emacs
11094 and to use an external application to visit the file.
11096 Optional LINE specifies a line to go to, optional SEARCH a string
11097 to search for. If LINE or SEARCH is given, the file will be
11098 opened in Emacs, unless an entry from org-file-apps that makes
11099 use of groups in a regexp matches.
11101 If you want to change the way frames are used when following a
11102 link, please customize `org-link-frame-setup'.
11104 If the file does not exist, an error is thrown."
11105 (let* ((file (if (equal path "")
11106 buffer-file-name
11107 (substitute-in-file-name (expand-file-name path))))
11108 (file-apps (append org-file-apps (org-default-apps)))
11109 (apps (org-remove-if
11110 'org-file-apps-entry-match-against-dlink-p file-apps))
11111 (apps-dlink (org-remove-if-not
11112 'org-file-apps-entry-match-against-dlink-p file-apps))
11113 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11114 (dirp (if remp nil (file-directory-p file)))
11115 (file (if (and dirp org-open-directory-means-index-dot-org)
11116 (concat (file-name-as-directory file) "index.org")
11117 file))
11118 (a-m-a-p (assq 'auto-mode apps))
11119 (dfile (downcase file))
11120 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
11121 (link (cond ((and (eq line nil)
11122 (eq search nil))
11123 file)
11124 (line
11125 (concat file "::" (number-to-string line)))
11126 (search
11127 (concat file "::" search))))
11128 (dlink (downcase link))
11129 (old-buffer (current-buffer))
11130 (old-pos (point))
11131 (old-mode major-mode)
11132 ext cmd link-match-data)
11133 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11134 (setq ext (match-string 1 dfile))
11135 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11136 (setq ext (match-string 1 dfile))))
11137 (cond
11138 ((member in-emacs '((16) system))
11139 (setq cmd (cdr (assoc 'system apps))))
11140 (in-emacs (setq cmd 'emacs))
11142 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11143 (and dirp (cdr (assoc 'directory apps)))
11144 ; first, try matching against apps-dlink
11145 ; if we get a match here, store the match data for later
11146 (let ((match (assoc-default dlink apps-dlink
11147 'string-match)))
11148 (if match
11149 (progn (setq link-match-data (match-data))
11150 match)
11151 (progn (setq in-emacs (or in-emacs line search))
11152 nil))) ; if we have no match in apps-dlink,
11153 ; always open the file in emacs if line or search
11154 ; is given (for backwards compatibility)
11155 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11156 'string-match)
11157 (cdr (assoc ext apps))
11158 (cdr (assoc t apps))))))
11159 (when (eq cmd 'system)
11160 (setq cmd (cdr (assoc 'system apps))))
11161 (when (eq cmd 'default)
11162 (setq cmd (cdr (assoc t apps))))
11163 (when (eq cmd 'mailcap)
11164 (require 'mailcap)
11165 (mailcap-parse-mailcaps)
11166 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11167 (command (mailcap-mime-info mime-type)))
11168 (if (stringp command)
11169 (setq cmd command)
11170 (setq cmd 'emacs))))
11171 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11172 (not (file-exists-p file))
11173 (not org-open-non-existing-files))
11174 (user-error "No such file: %s" file))
11175 (cond
11176 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11177 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11178 (while (string-match "['\"]%s['\"]" cmd)
11179 (setq cmd (replace-match "%s" t t cmd)))
11180 (while (string-match "%s" cmd)
11181 (setq cmd (replace-match
11182 (save-match-data
11183 (shell-quote-argument
11184 (convert-standard-filename file)))
11185 t t cmd)))
11187 ;; Replace "%1", "%2" etc. in command with group matches from regex
11188 (save-match-data
11189 (let ((match-index 1)
11190 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11191 (set-match-data link-match-data)
11192 (while (<= match-index number-of-groups)
11193 (let ((regex (concat "%" (number-to-string match-index)))
11194 (replace-with (match-string match-index dlink)))
11195 (while (string-match regex cmd)
11196 (setq cmd (replace-match replace-with t t cmd))))
11197 (setq match-index (+ match-index 1)))))
11199 (save-window-excursion
11200 (message "Running %s...done" cmd)
11201 (start-process-shell-command cmd nil cmd)
11202 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11203 ((or (stringp cmd)
11204 (eq cmd 'emacs))
11205 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11206 (widen)
11207 (if line (progn (org-goto-line line)
11208 (if (derived-mode-p 'org-mode)
11209 (org-reveal)))
11210 (if search (org-link-search search))))
11211 ((consp cmd)
11212 (let ((file (convert-standard-filename file)))
11213 (save-match-data
11214 (set-match-data link-match-data)
11215 (eval cmd))))
11216 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11217 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11218 (or (not (equal old-buffer (current-buffer)))
11219 (not (equal old-pos (point))))
11220 (org-mark-ring-push old-pos old-buffer))))
11222 (defun org-file-apps-entry-match-against-dlink-p (entry)
11223 "This function returns non-nil if `entry' uses a regular
11224 expression which should be matched against the whole link by
11225 org-open-file.
11227 It assumes that is the case when the entry uses a regular
11228 expression which has at least one grouping construct and the
11229 action is either a lisp form or a command string containing
11230 '%1', i.e. using at least one subexpression match as a
11231 parameter."
11232 (let ((selector (car entry))
11233 (action (cdr entry)))
11234 (if (stringp selector)
11235 (and (> (regexp-opt-depth selector) 0)
11236 (or (and (stringp action)
11237 (string-match "%[0-9]" action))
11238 (consp action)))
11239 nil)))
11241 (defun org-default-apps ()
11242 "Return the default applications for this operating system."
11243 (cond
11244 ((eq system-type 'darwin)
11245 org-file-apps-defaults-macosx)
11246 ((eq system-type 'windows-nt)
11247 org-file-apps-defaults-windowsnt)
11248 (t org-file-apps-defaults-gnu)))
11250 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11251 "Convert extensions to regular expressions in the cars of LIST.
11252 Also, weed out any non-string entries, because the return value is used
11253 only for regexp matching.
11254 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11255 point to the symbol `emacs', indicating that the file should
11256 be opened in Emacs."
11257 (append
11258 (delq nil
11259 (mapcar (lambda (x)
11260 (if (not (stringp (car x)))
11262 (if (string-match "\\W" (car x))
11264 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11265 list))
11266 (if add-auto-mode
11267 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11269 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11270 (defun org-file-remote-p (file)
11271 "Test whether FILE specifies a location on a remote system.
11272 Return non-nil if the location is indeed remote.
11274 For example, the filename \"/user@host:/foo\" specifies a location
11275 on the system \"/user@host:\"."
11276 (cond ((fboundp 'file-remote-p)
11277 (file-remote-p file))
11278 ((fboundp 'tramp-handle-file-remote-p)
11279 (tramp-handle-file-remote-p file))
11280 ((and (boundp 'ange-ftp-name-format)
11281 (string-match (car ange-ftp-name-format) file))
11282 t)))
11285 ;;;; Refiling
11287 (defun org-get-org-file ()
11288 "Read a filename, with default directory `org-directory'."
11289 (let ((default (or org-default-notes-file remember-data-file)))
11290 (read-file-name (format "File name [%s]: " default)
11291 (file-name-as-directory org-directory)
11292 default)))
11294 (defun org-notes-order-reversed-p ()
11295 "Check if the current file should receive notes in reversed order."
11296 (cond
11297 ((not org-reverse-note-order) nil)
11298 ((eq t org-reverse-note-order) t)
11299 ((not (listp org-reverse-note-order)) nil)
11300 (t (catch 'exit
11301 (let ((all org-reverse-note-order)
11302 entry)
11303 (while (setq entry (pop all))
11304 (if (string-match (car entry) buffer-file-name)
11305 (throw 'exit (cdr entry))))
11306 nil)))))
11308 (defvar org-refile-target-table nil
11309 "The list of refile targets, created by `org-refile'.")
11311 (defvar org-agenda-new-buffers nil
11312 "Buffers created to visit agenda files.")
11314 (defvar org-refile-cache nil
11315 "Cache for refile targets.")
11317 (defvar org-refile-markers nil
11318 "All the markers used for caching refile locations.")
11320 (defun org-refile-marker (pos)
11321 "Get a new refile marker, but only if caching is in use."
11322 (if (not org-refile-use-cache)
11324 (let ((m (make-marker)))
11325 (move-marker m pos)
11326 (push m org-refile-markers)
11327 m)))
11329 (defun org-refile-cache-clear ()
11330 "Clear the refile cache and disable all the markers."
11331 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11332 (setq org-refile-markers nil)
11333 (setq org-refile-cache nil)
11334 (message "Refile cache has been cleared"))
11336 (defun org-refile-cache-check-set (set)
11337 "Check if all the markers in the cache still have live buffers."
11338 (let (marker)
11339 (catch 'exit
11340 (while (and set (setq marker (nth 3 (pop set))))
11341 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11342 (when (and marker (null (marker-buffer marker)))
11343 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11344 (sit-for 3)
11345 (throw 'exit nil)))
11346 t)))
11348 (defun org-refile-cache-put (set &rest identifiers)
11349 "Push the refile targets SET into the cache, under IDENTIFIERS."
11350 (let* ((key (sha1 (prin1-to-string identifiers)))
11351 (entry (assoc key org-refile-cache)))
11352 (if entry
11353 (setcdr entry set)
11354 (push (cons key set) org-refile-cache))))
11356 (defun org-refile-cache-get (&rest identifiers)
11357 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11358 (cond
11359 ((not org-refile-cache) nil)
11360 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11362 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11363 org-refile-cache))))
11364 (and set (org-refile-cache-check-set set) set)))))
11366 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11367 "Produce a table with refile targets."
11368 (let ((case-fold-search nil)
11369 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11370 (entries (or org-refile-targets '((nil . (:level . 1)))))
11371 targets tgs txt re files f desc descre fast-path-p level pos0)
11372 (message "Getting targets...")
11373 (with-current-buffer (or default-buffer (current-buffer))
11374 (while (setq entry (pop entries))
11375 (setq files (car entry) desc (cdr entry))
11376 (setq fast-path-p nil)
11377 (cond
11378 ((null files) (setq files (list (current-buffer))))
11379 ((eq files 'org-agenda-files)
11380 (setq files (org-agenda-files 'unrestricted)))
11381 ((and (symbolp files) (fboundp files))
11382 (setq files (funcall files)))
11383 ((and (symbolp files) (boundp files))
11384 (setq files (symbol-value files))))
11385 (if (stringp files) (setq files (list files)))
11386 (cond
11387 ((eq (car desc) :tag)
11388 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11389 ((eq (car desc) :todo)
11390 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11391 ((eq (car desc) :regexp)
11392 (setq descre (cdr desc)))
11393 ((eq (car desc) :level)
11394 (setq descre (concat "^\\*\\{" (number-to-string
11395 (if org-odd-levels-only
11396 (1- (* 2 (cdr desc)))
11397 (cdr desc)))
11398 "\\}[ \t]")))
11399 ((eq (car desc) :maxlevel)
11400 (setq fast-path-p t)
11401 (setq descre (concat "^\\*\\{1," (number-to-string
11402 (if org-odd-levels-only
11403 (1- (* 2 (cdr desc)))
11404 (cdr desc)))
11405 "\\}[ \t]")))
11406 (t (error "Bad refiling target description %s" desc)))
11407 (while (setq f (pop files))
11408 (with-current-buffer
11409 (if (bufferp f) f (org-get-agenda-file-buffer f))
11411 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11412 (progn
11413 (if (bufferp f) (setq f (buffer-file-name
11414 (buffer-base-buffer f))))
11415 (setq f (and f (expand-file-name f)))
11416 (if (eq org-refile-use-outline-path 'file)
11417 (push (list (file-name-nondirectory f) f nil nil) tgs))
11418 (save-excursion
11419 (save-restriction
11420 (widen)
11421 (goto-char (point-min))
11422 (while (re-search-forward descre nil t)
11423 (goto-char (setq pos0 (point-at-bol)))
11424 (catch 'next
11425 (when org-refile-target-verify-function
11426 (save-match-data
11427 (or (funcall org-refile-target-verify-function)
11428 (throw 'next t))))
11429 (when (and (looking-at org-complex-heading-regexp)
11430 (not (member (match-string 4) excluded-entries))
11431 (match-string 4))
11432 (setq level (org-reduced-level
11433 (- (match-end 1) (match-beginning 1)))
11434 txt (org-link-display-format (match-string 4))
11435 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11436 re (format org-complex-heading-regexp-format
11437 (regexp-quote (match-string 4))))
11438 (when org-refile-use-outline-path
11439 (setq txt (mapconcat
11440 'org-protect-slash
11441 (append
11442 (if (eq org-refile-use-outline-path
11443 'file)
11444 (list (file-name-nondirectory
11445 (buffer-file-name
11446 (buffer-base-buffer))))
11447 (if (eq org-refile-use-outline-path
11448 'full-file-path)
11449 (list (buffer-file-name
11450 (buffer-base-buffer)))))
11451 (org-get-outline-path fast-path-p
11452 level txt)
11453 (list txt))
11454 "/")))
11455 (push (list txt f re (org-refile-marker (point)))
11456 tgs)))
11457 (when (= (point) pos0)
11458 ;; verification function has not moved point
11459 (goto-char (point-at-eol))))))))
11460 (when org-refile-use-cache
11461 (org-refile-cache-put tgs (buffer-file-name) descre))
11462 (setq targets (append tgs targets))))))
11463 (message "Getting targets...done")
11464 (nreverse targets)))
11466 (defun org-protect-slash (s)
11467 (while (string-match "/" s)
11468 (setq s (replace-match "\\" t t s)))
11471 (defvar org-olpa (make-vector 20 nil))
11473 (defun org-get-outline-path (&optional fastp level heading)
11474 "Return the outline path to the current entry, as a list.
11476 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11477 routine which makes outline path derivations for an entire file,
11478 avoiding backtracing. Refile target collection makes use of that."
11479 (if fastp
11480 (progn
11481 (if (> level 19)
11482 (error "Outline path failure, more than 19 levels"))
11483 (loop for i from level upto 19 do
11484 (aset org-olpa i nil))
11485 (prog1
11486 (delq nil (append org-olpa nil))
11487 (aset org-olpa level heading)))
11488 (let (rtn case-fold-search)
11489 (save-excursion
11490 (save-restriction
11491 (widen)
11492 (while (org-up-heading-safe)
11493 (when (looking-at org-complex-heading-regexp)
11494 (push (org-trim
11495 (replace-regexp-in-string
11496 ;; Remove statistical/checkboxes cookies
11497 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11498 (org-match-string-no-properties 4)))
11499 rtn)))
11500 rtn)))))
11502 (defun org-format-outline-path (path &optional width prefix separator)
11503 "Format the outline path PATH for display.
11504 WIDTH is the maximum number of characters that is available.
11505 PREFIX is a prefix to be included in the returned string,
11506 such as the file name.
11507 SEPARATOR is inserted between the different parts of the path,
11508 the default is \"/\"."
11509 (setq width (or width 79))
11510 (if prefix (setq width (- width (length prefix))))
11511 (if (not path)
11512 (or prefix "")
11513 (let* ((nsteps (length path))
11514 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11515 (maxwidth (if (<= total-width width)
11516 10000 ;; everything fits
11517 ;; we need to shorten the level headings
11518 (/ (- width nsteps) nsteps)))
11519 (org-odd-levels-only nil)
11520 (n 0)
11521 (total (1+ (length prefix))))
11522 (setq maxwidth (max maxwidth 10))
11523 (concat prefix
11524 (if prefix (or separator "/"))
11525 (mapconcat
11526 (lambda (h)
11527 (setq n (1+ n))
11528 (if (and (= n nsteps) (< maxwidth 10000))
11529 (setq maxwidth (- total-width total)))
11530 (if (< (length h) maxwidth)
11531 (progn (setq total (+ total (length h) 1)) h)
11532 (setq h (substring h 0 (- maxwidth 2))
11533 total (+ total maxwidth 1))
11534 (if (string-match "[ \t]+\\'" h)
11535 (setq h (substring h 0 (match-beginning 0))))
11536 (setq h (concat h "..")))
11537 (org-add-props h nil 'face
11538 (nth (% (1- n) org-n-level-faces)
11539 org-level-faces))
11541 path (or separator "/"))))))
11543 (defun org-display-outline-path (&optional file current separator just-return-string)
11544 "Display the current outline path in the echo area.
11546 If FILE is non-nil, prepend the output with the file name.
11547 If CURRENT is non-nil, append the current heading to the output.
11548 SEPARATOR is passed through to `org-format-outline-path'. It separates
11549 the different parts of the path and defaults to \"/\".
11550 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11551 (interactive "P")
11552 (let* (case-fold-search
11553 (bfn (buffer-file-name (buffer-base-buffer)))
11554 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11555 res)
11556 (if current (setq path (append path
11557 (save-excursion
11558 (org-back-to-heading t)
11559 (if (looking-at org-complex-heading-regexp)
11560 (list (match-string 4)))))))
11561 (setq res
11562 (org-format-outline-path
11563 path
11564 (1- (frame-width))
11565 (and file bfn (concat (file-name-nondirectory bfn) separator))
11566 separator))
11567 (if just-return-string
11568 (org-no-properties res)
11569 (org-unlogged-message "%s" res))))
11571 (defvar org-refile-history nil
11572 "History for refiling operations.")
11574 (defvar org-after-refile-insert-hook nil
11575 "Hook run after `org-refile' has inserted its stuff at the new location.
11576 Note that this is still *before* the stuff will be removed from
11577 the *old* location.")
11579 (defvar org-capture-last-stored-marker)
11580 (defvar org-refile-keep nil
11581 "Non-nil means `org-refile' will copy instead of refile.")
11583 (defun org-copy ()
11584 "Like `org-refile', but copy."
11585 (interactive)
11586 (let ((org-refile-keep t))
11587 (funcall 'org-refile nil nil nil "Copy")))
11589 (defun org-refile (&optional arg default-buffer rfloc msg)
11590 "Move the entry or entries at point to another heading.
11591 The list of target headings is compiled using the information in
11592 `org-refile-targets', which see.
11594 At the target location, the entry is filed as a subitem of the
11595 target heading. Depending on `org-reverse-note-order', the new
11596 subitem will either be the first or the last subitem.
11598 If there is an active region, all entries in that region will be
11599 refiled. However, the region must fulfill the requirement that
11600 the first heading sets the top-level of the moved text.
11602 With prefix arg ARG, the command will only visit the target
11603 location and not actually move anything.
11605 With a double prefix arg \\[universal-argument] \\[universal-argument], go to the location where the last
11606 refiling operation has put the subtree.
11608 With a numeric prefix argument of `2', refile to the running clock.
11610 With a numeric prefix argument of `3', emulate `org-refile-keep'
11611 being set to `t' and copy to the target location, don't move it.
11612 Beware that keeping refiled entries may result in duplicated ID
11613 properties.
11615 RFLOC can be a refile location obtained in a different way.
11617 MSG is a string to replace \"Refile\" in the default prompt with
11618 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11620 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11622 If you are using target caching (see `org-refile-use-cache'), you
11623 have to clear the target cache in order to find new targets.
11624 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11625 prefix argument (`C-u C-u C-u C-c C-w')."
11626 (interactive "P")
11627 (if (member arg '(0 (64)))
11628 (org-refile-cache-clear)
11629 (let* ((actionmsg (cond (msg msg)
11630 ((equal arg 3) "Refile (and keep)")
11631 (t "Refile")))
11632 (cbuf (current-buffer))
11633 (regionp (org-region-active-p))
11634 (region-start (and regionp (region-beginning)))
11635 (region-end (and regionp (region-end)))
11636 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11637 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11638 pos it nbuf file re level reversed)
11639 (setq last-command nil)
11640 (when regionp
11641 (goto-char region-start)
11642 (or (bolp) (goto-char (point-at-bol)))
11643 (setq region-start (point))
11644 (unless (or (org-kill-is-subtree-p
11645 (buffer-substring region-start region-end))
11646 (prog1 org-refile-active-region-within-subtree
11647 (let ((s (point-at-eol)))
11648 (org-toggle-heading)
11649 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11650 (user-error "The region is not a (sequence of) subtree(s)")))
11651 (if (equal arg '(16))
11652 (org-refile-goto-last-stored)
11653 (when (or
11654 (and (equal arg 2)
11655 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11656 (prog1
11657 (setq it (list (or org-clock-heading "running clock")
11658 (buffer-file-name
11659 (marker-buffer org-clock-hd-marker))
11661 (marker-position org-clock-hd-marker)))
11662 (setq arg nil)))
11663 (setq it (or rfloc
11664 (let (heading-text)
11665 (save-excursion
11666 (unless (and arg (listp arg))
11667 (org-back-to-heading t)
11668 (setq heading-text
11669 (replace-regexp-in-string
11670 org-bracket-link-regexp
11671 "\\3"
11672 (nth 4 (org-heading-components)))))
11673 (org-refile-get-location
11674 (cond ((and arg (listp arg)) "Goto")
11675 (regionp (concat actionmsg " region to"))
11676 (t (concat actionmsg " subtree \""
11677 heading-text "\" to")))
11678 default-buffer
11679 (and (not (equal '(4) arg))
11680 org-refile-allow-creating-parent-nodes)
11681 arg))))))
11682 (setq file (nth 1 it)
11683 re (nth 2 it)
11684 pos (nth 3 it))
11685 (if (and (not arg)
11687 (equal (buffer-file-name) file)
11688 (if regionp
11689 (and (>= pos region-start)
11690 (<= pos region-end))
11691 (and (>= pos (point))
11692 (< pos (save-excursion
11693 (org-end-of-subtree t t))))))
11694 (error "Cannot refile to position inside the tree or region"))
11695 (setq nbuf (or (find-buffer-visiting file)
11696 (find-file-noselect file)))
11697 (if (and arg (not (equal arg 3)))
11698 (progn
11699 (org-pop-to-buffer-same-window nbuf)
11700 (goto-char pos)
11701 (org-show-context 'org-goto))
11702 (if regionp
11703 (progn
11704 (org-kill-new (buffer-substring region-start region-end))
11705 (org-save-markers-in-region region-start region-end))
11706 (org-copy-subtree 1 nil t))
11707 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11708 (find-file-noselect file)))
11709 (setq reversed (org-notes-order-reversed-p))
11710 (save-excursion
11711 (save-restriction
11712 (widen)
11713 (if pos
11714 (progn
11715 (goto-char pos)
11716 (looking-at org-outline-regexp)
11717 (setq level (org-get-valid-level (funcall outline-level) 1))
11718 (goto-char
11719 (if reversed
11720 (or (outline-next-heading) (point-max))
11721 (or (save-excursion (org-get-next-sibling))
11722 (org-end-of-subtree t t)
11723 (point-max)))))
11724 (setq level 1)
11725 (if (not reversed)
11726 (goto-char (point-max))
11727 (goto-char (point-min))
11728 (or (outline-next-heading) (goto-char (point-max)))))
11729 (if (not (bolp)) (newline))
11730 (org-paste-subtree level)
11731 (when org-log-refile
11732 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11733 (unless (eq org-log-refile 'note)
11734 (save-excursion (org-add-log-note))))
11735 (and org-auto-align-tags
11736 (let ((org-loop-over-headlines-in-active-region nil))
11737 (org-set-tags nil t)))
11738 (let ((bookmark-name (plist-get org-bookmark-names-plist
11739 :last-refile)))
11740 (when bookmark-name
11741 (with-demoted-errors
11742 (bookmark-set bookmark-name))))
11743 ;; If we are refiling for capture, make sure that the
11744 ;; last-capture pointers point here
11745 (when (org-bound-and-true-p org-refile-for-capture)
11746 (let ((bookmark-name (plist-get org-bookmark-names-plist
11747 :last-capture-marker)))
11748 (when bookmark-name
11749 (with-demoted-errors
11750 (bookmark-set bookmark-name))))
11751 (move-marker org-capture-last-stored-marker (point)))
11752 (if (fboundp 'deactivate-mark) (deactivate-mark))
11753 (run-hooks 'org-after-refile-insert-hook))))
11754 (unless org-refile-keep
11755 (if regionp
11756 (delete-region (point) (+ (point) (- region-end region-start)))
11757 (delete-region
11758 (and (org-back-to-heading t) (point))
11759 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11760 (when (featurep 'org-inlinetask)
11761 (org-inlinetask-remove-END-maybe))
11762 (setq org-markers-to-move nil)
11763 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11765 (defun org-refile-goto-last-stored ()
11766 "Go to the location where the last refile was stored."
11767 (interactive)
11768 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11769 (message "This is the location of the last refile"))
11771 (defun org-refile--get-location (refloc tbl)
11772 "When user refile to REFLOC, find the associated target in TBL.
11773 Also check `org-refile-target-table'."
11774 (car (delq
11776 (mapcar
11777 (lambda (r) (or (assoc r tbl)
11778 (assoc r org-refile-target-table)))
11779 (list (replace-regexp-in-string "/$" "" refloc)
11780 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11782 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11783 no-exclude)
11784 "Prompt the user for a refile location, using PROMPT.
11785 PROMPT should not be suffixed with a colon and a space, because
11786 this function appends the default value from
11787 `org-refile-history' automatically, if that is not empty.
11788 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11789 this is used for the GOTO interface."
11790 (let ((org-refile-targets org-refile-targets)
11791 (org-refile-use-outline-path org-refile-use-outline-path)
11792 excluded-entries)
11793 (when (and (derived-mode-p 'org-mode)
11794 (not org-refile-use-cache)
11795 (not no-exclude))
11796 (org-map-tree
11797 (lambda()
11798 (setq excluded-entries
11799 (append excluded-entries (list (org-get-heading t t)))))))
11800 (setq org-refile-target-table
11801 (org-refile-get-targets default-buffer excluded-entries)))
11802 (unless org-refile-target-table
11803 (user-error "No refile targets"))
11804 (let* ((cbuf (current-buffer))
11805 (partial-completion-mode nil)
11806 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11807 (cfunc (if (and org-refile-use-outline-path
11808 org-outline-path-complete-in-steps)
11809 'org-olpath-completing-read
11810 'org-icompleting-read))
11811 (extra (if org-refile-use-outline-path "/" ""))
11812 (cbnex (concat (buffer-name) extra))
11813 (filename (and cfn (expand-file-name cfn)))
11814 (tbl (mapcar
11815 (lambda (x)
11816 (if (and (not (member org-refile-use-outline-path
11817 '(file full-file-path)))
11818 (not (equal filename (nth 1 x))))
11819 (cons (concat (car x) extra " ("
11820 (file-name-nondirectory (nth 1 x)) ")")
11821 (cdr x))
11822 (cons (concat (car x) extra) (cdr x))))
11823 org-refile-target-table))
11824 (completion-ignore-case t)
11825 cdef
11826 (prompt (concat prompt
11827 (or (and (car org-refile-history)
11828 (concat " (default " (car org-refile-history) ")"))
11829 (and (assoc cbnex tbl) (setq cdef cbnex)
11830 (concat " (default " cbnex ")"))) ": "))
11831 pa answ parent-target child parent old-hist)
11832 (setq old-hist org-refile-history)
11833 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11834 nil 'org-refile-history (or cdef (car org-refile-history))))
11835 (if (setq pa (org-refile--get-location answ tbl))
11836 (progn
11837 (org-refile-check-position pa)
11838 (when (or (not org-refile-history)
11839 (not (eq old-hist org-refile-history))
11840 (not (equal (car pa) (car org-refile-history))))
11841 (setq org-refile-history
11842 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11843 org-refile-history
11844 (cdr org-refile-history))))
11845 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11846 (pop org-refile-history)))
11848 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11849 (progn
11850 (setq parent (match-string 1 answ)
11851 child (match-string 2 answ))
11852 (setq parent-target (org-refile--get-location parent tbl))
11853 (when (and parent-target
11854 (or (eq new-nodes t)
11855 (and (eq new-nodes 'confirm)
11856 (y-or-n-p (format "Create new node \"%s\"? "
11857 child)))))
11858 (org-refile-new-child parent-target child)))
11859 (user-error "Invalid target location")))))
11861 (declare-function org-string-nw-p "org-macs" (s))
11862 (defun org-refile-check-position (refile-pointer)
11863 "Check if the refile pointer matches the headline to which it points."
11864 (let* ((file (nth 1 refile-pointer))
11865 (re (nth 2 refile-pointer))
11866 (pos (nth 3 refile-pointer))
11867 buffer)
11868 (if (and (not (markerp pos)) (not file))
11869 (if file
11870 (user-error "Please save the buffer to a file before refiling")
11871 (user-error "Please indicate a target file in the refile path"))
11872 (when (org-string-nw-p re)
11873 (setq buffer (if (markerp pos)
11874 (marker-buffer pos)
11875 (or (find-buffer-visiting file)
11876 (find-file-noselect file))))
11877 (with-current-buffer buffer
11878 (save-excursion
11879 (save-restriction
11880 (widen)
11881 (goto-char pos)
11882 (beginning-of-line 1)
11883 (unless (org-looking-at-p re)
11884 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11886 (defun org-refile-new-child (parent-target child)
11887 "Use refile target PARENT-TARGET to add new CHILD below it."
11888 (unless parent-target
11889 (error "Cannot find parent for new node"))
11890 (let ((file (nth 1 parent-target))
11891 (pos (nth 3 parent-target))
11892 level)
11893 (with-current-buffer (or (find-buffer-visiting file)
11894 (find-file-noselect file))
11895 (save-excursion
11896 (save-restriction
11897 (widen)
11898 (if pos
11899 (goto-char pos)
11900 (goto-char (point-max))
11901 (if (not (bolp)) (newline)))
11902 (when (looking-at org-outline-regexp)
11903 (setq level (funcall outline-level))
11904 (org-end-of-subtree t t))
11905 (org-back-over-empty-lines)
11906 (insert "\n" (make-string
11907 (if pos (org-get-valid-level level 1) 1) ?*)
11908 " " child "\n")
11909 (beginning-of-line 0)
11910 (list (concat (car parent-target) "/" child) file "" (point)))))))
11912 (defun org-olpath-completing-read (prompt collection &rest args)
11913 "Read an outline path like a file name."
11914 (let ((thetable collection)
11915 (org-completion-use-ido nil) ; does not work with ido.
11916 (org-completion-use-iswitchb nil)) ; or iswitchb
11917 (apply
11918 'org-icompleting-read prompt
11919 (lambda (string predicate &optional flag)
11920 (let (rtn r f (l (length string)))
11921 (cond
11922 ((eq flag nil)
11923 ;; try completion
11924 (try-completion string thetable))
11925 ((eq flag t)
11926 ;; all-completions
11927 (setq rtn (all-completions string thetable predicate))
11928 (mapcar
11929 (lambda (x)
11930 (setq r (substring x l))
11931 (if (string-match " ([^)]*)$" x)
11932 (setq f (match-string 0 x))
11933 (setq f ""))
11934 (if (string-match "/" r)
11935 (concat string (substring r 0 (match-end 0)) f)
11937 rtn))
11938 ((eq flag 'lambda)
11939 ;; exact match?
11940 (assoc string thetable)))))
11941 args)))
11943 ;;;; Dynamic blocks
11945 (defun org-find-dblock (name)
11946 "Find the first dynamic block with name NAME in the buffer.
11947 If not found, stay at current position and return nil."
11948 (let ((case-fold-search t) pos)
11949 (save-excursion
11950 (goto-char (point-min))
11951 (setq pos (and (re-search-forward
11952 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11953 (match-beginning 0))))
11954 (if pos (goto-char pos))
11955 pos))
11957 (defun org-create-dblock (plist)
11958 "Create a dynamic block section, with parameters taken from PLIST.
11959 PLIST must contain a :name entry which is used as name of the block."
11960 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11961 (end-of-line 1)
11962 (newline))
11963 (let ((col (current-column))
11964 (name (plist-get plist :name)))
11965 (insert "#+BEGIN: " name)
11966 (while plist
11967 (if (eq (car plist) :name)
11968 (setq plist (cddr plist))
11969 (insert " " (prin1-to-string (pop plist)))))
11970 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11971 (beginning-of-line -2)))
11973 (defun org-prepare-dblock ()
11974 "Prepare dynamic block for refresh.
11975 This empties the block, puts the cursor at the insert position and returns
11976 the property list including an extra property :name with the block name."
11977 (unless (looking-at org-dblock-start-re)
11978 (user-error "Not at a dynamic block"))
11979 (let* ((begdel (1+ (match-end 0)))
11980 (name (org-no-properties (match-string 1)))
11981 (params (append (list :name name)
11982 (read (concat "(" (match-string 3) ")")))))
11983 (save-excursion
11984 (beginning-of-line 1)
11985 (skip-chars-forward " \t")
11986 (setq params (plist-put params :indentation-column (current-column))))
11987 (unless (re-search-forward org-dblock-end-re nil t)
11988 (error "Dynamic block not terminated"))
11989 (setq params
11990 (append params
11991 (list :content (buffer-substring
11992 begdel (match-beginning 0)))))
11993 (delete-region begdel (match-beginning 0))
11994 (goto-char begdel)
11995 (open-line 1)
11996 params))
11998 (defun org-map-dblocks (&optional command)
11999 "Apply COMMAND to all dynamic blocks in the current buffer.
12000 If COMMAND is not given, use `org-update-dblock'."
12001 (let ((cmd (or command 'org-update-dblock)))
12002 (save-excursion
12003 (goto-char (point-min))
12004 (while (re-search-forward org-dblock-start-re nil t)
12005 (goto-char (match-beginning 0))
12006 (save-excursion
12007 (condition-case nil
12008 (funcall cmd)
12009 (error (message "Error during update of dynamic block"))))
12010 (unless (re-search-forward org-dblock-end-re nil t)
12011 (error "Dynamic block not terminated"))))))
12013 (defun org-dblock-update (&optional arg)
12014 "User command for updating dynamic blocks.
12015 Update the dynamic block at point. With prefix ARG, update all dynamic
12016 blocks in the buffer."
12017 (interactive "P")
12018 (if arg
12019 (org-update-all-dblocks)
12020 (or (looking-at org-dblock-start-re)
12021 (org-beginning-of-dblock))
12022 (org-update-dblock)))
12024 (defun org-update-dblock ()
12025 "Update the dynamic block at point.
12026 This means to empty the block, parse for parameters and then call
12027 the correct writing function."
12028 (interactive)
12029 (save-window-excursion
12030 (let* ((pos (point))
12031 (line (org-current-line))
12032 (params (org-prepare-dblock))
12033 (name (plist-get params :name))
12034 (indent (plist-get params :indentation-column))
12035 (cmd (intern (concat "org-dblock-write:" name))))
12036 (message "Updating dynamic block `%s' at line %d..." name line)
12037 (funcall cmd params)
12038 (message "Updating dynamic block `%s' at line %d...done" name line)
12039 (goto-char pos)
12040 (when (and indent (> indent 0))
12041 (setq indent (make-string indent ?\ ))
12042 (save-excursion
12043 (org-beginning-of-dblock)
12044 (forward-line 1)
12045 (while (not (looking-at org-dblock-end-re))
12046 (insert indent)
12047 (beginning-of-line 2))
12048 (when (looking-at org-dblock-end-re)
12049 (and (looking-at "[ \t]+")
12050 (replace-match ""))
12051 (insert indent)))))))
12053 (defun org-beginning-of-dblock ()
12054 "Find the beginning of the dynamic block at point.
12055 Error if there is no such block at point."
12056 (let ((pos (point))
12057 beg)
12058 (end-of-line 1)
12059 (if (and (re-search-backward org-dblock-start-re nil t)
12060 (setq beg (match-beginning 0))
12061 (re-search-forward org-dblock-end-re nil t)
12062 (> (match-end 0) pos))
12063 (goto-char beg)
12064 (goto-char pos)
12065 (error "Not in a dynamic block"))))
12067 (defun org-update-all-dblocks ()
12068 "Update all dynamic blocks in the buffer.
12069 This function can be used in a hook."
12070 (interactive)
12071 (when (derived-mode-p 'org-mode)
12072 (org-map-dblocks 'org-update-dblock)))
12075 ;;;; Completion
12077 (declare-function org-export-backend-name "org-export" (cl-x))
12078 (declare-function org-export-backend-options "org-export" (cl-x))
12079 (defun org-get-export-keywords ()
12080 "Return a list of all currently understood export keywords.
12081 Export keywords include options, block names, attributes and
12082 keywords relative to each registered export back-end."
12083 (let (keywords)
12084 (dolist (backend
12085 (org-bound-and-true-p org-export--registered-backends)
12086 (delq nil keywords))
12087 ;; Back-end name (for keywords, like #+LATEX:)
12088 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12089 (dolist (option-entry (org-export-backend-options backend))
12090 ;; Back-end options.
12091 (push (nth 1 option-entry) keywords)))))
12093 (defconst org-options-keywords
12094 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12095 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12096 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12097 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12098 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12100 (defcustom org-structure-template-alist
12101 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC" "<src lang=\"?\">\n\n</src>")
12102 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE" "<example>\n?\n</example>")
12103 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE" "<quote>\n?\n</quote>")
12104 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE" "<verse>\n?\n</verse>")
12105 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM" "<verbatim>\n?\n</verbatim>")
12106 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER" "<center>\n?\n</center>")
12107 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
12108 "<literal style=\"latex\">\n?\n</literal>")
12109 ("L" "#+LaTeX: " "<literal style=\"latex\">?</literal>")
12110 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
12111 "<literal style=\"html\">\n?\n</literal>")
12112 ("H" "#+HTML: " "<literal style=\"html\">?</literal>")
12113 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII" "")
12114 ("A" "#+ASCII: " "")
12115 ("i" "#+INDEX: ?" "#+INDEX: ?")
12116 ("I" "#+INCLUDE: %file ?"
12117 "<include file=%file markup=\"?\">"))
12118 "Structure completion elements.
12119 This is a list of abbreviation keys and values. The value gets inserted
12120 if you type `<' followed by the key and then press the completion key,
12121 usually `M-TAB'. %file will be replaced by a file name after prompting
12122 for the file using completion. The cursor will be placed at the position
12123 of the `?` in the template.
12124 There are two templates for each key, the first uses the original Org syntax,
12125 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12126 the default when the /org-mtags.el/ module has been loaded. See also the
12127 variable `org-mtags-prefer-muse-templates'."
12128 :group 'org-completion
12129 :type '(repeat
12130 (list
12131 (string :tag "Key")
12132 (string :tag "Template")
12133 (string :tag "Muse Template"))))
12135 (defun org-try-structure-completion ()
12136 "Try to complete a structure template before point.
12137 This looks for strings like \"<e\" on an otherwise empty line and
12138 expands them."
12139 (let ((l (buffer-substring (point-at-bol) (point)))
12141 (when (and (looking-at "[ \t]*$")
12142 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12143 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12144 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12145 (match-beginning 1)) a)
12146 t)))
12148 (defun org-complete-expand-structure-template (start cell)
12149 "Expand a structure template."
12150 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
12151 (rpl (nth (if musep 2 1) cell))
12152 (ind ""))
12153 (delete-region start (point))
12154 (when (string-match "\\`[ \t]*#\\+" rpl)
12155 (cond
12156 ((bolp))
12157 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12158 (setq ind (buffer-substring (point-at-bol) (point))))
12159 (t (newline))))
12160 (setq start (point))
12161 (if (string-match "%file" rpl)
12162 (setq rpl (replace-match
12163 (concat
12164 "\""
12165 (save-match-data
12166 (abbreviate-file-name (read-file-name "Include file: ")))
12167 "\"")
12168 t t rpl)))
12169 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12170 (concat "\n" ind)))
12171 (insert rpl)
12172 (if (re-search-backward "\\?" start t) (delete-char 1))))
12174 ;;;; TODO, DEADLINE, Comments
12176 (defun org-toggle-comment ()
12177 "Change the COMMENT state of an entry."
12178 (interactive)
12179 (save-excursion
12180 (org-back-to-heading)
12181 (let (case-fold-search)
12182 (cond
12183 ((looking-at (format org-heading-keyword-regexp-format
12184 org-comment-string))
12185 (goto-char (match-end 1))
12186 (looking-at (concat " +" org-comment-string))
12187 (replace-match "" t t)
12188 (when (eolp) (insert " ")))
12189 ((looking-at org-outline-regexp)
12190 (goto-char (match-end 0))
12191 (insert org-comment-string " "))))))
12193 (defvar org-last-todo-state-is-todo nil
12194 "This is non-nil when the last TODO state change led to a TODO state.
12195 If the last change removed the TODO tag or switched to DONE, then
12196 this is nil.")
12198 (defvar org-setting-tags nil) ; dynamically skipped
12200 (defvar org-todo-setup-filter-hook nil
12201 "Hook for functions that pre-filter todo specs.
12202 Each function takes a todo spec and returns either nil or the spec
12203 transformed into canonical form." )
12205 (defvar org-todo-get-default-hook nil
12206 "Hook for functions that get a default item for todo.
12207 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12208 nil or a string to be used for the todo mark." )
12210 (defvar org-agenda-headline-snapshot-before-repeat)
12212 (defun org-current-effective-time ()
12213 "Return current time adjusted for `org-extend-today-until' variable."
12214 (let* ((ct (org-current-time))
12215 (dct (decode-time ct))
12216 (ct1
12217 (cond
12218 (org-use-last-clock-out-time-as-effective-time
12219 (or (org-clock-get-last-clock-out-time) ct))
12220 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12221 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12222 (t ct))))
12223 ct1))
12225 (defun org-todo-yesterday (&optional arg)
12226 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12227 (interactive "P")
12228 (if (eq major-mode 'org-agenda-mode)
12229 (apply 'org-agenda-todo-yesterday arg)
12230 (let* ((hour (third (decode-time
12231 (org-current-time))))
12232 (org-extend-today-until (1+ hour)))
12233 (org-todo arg))))
12235 (defvar org-block-entry-blocking ""
12236 "First entry preventing the TODO state change.")
12238 (defun org-cancel-repeater ()
12239 "Cancel a repeater by setting its numeric value to zero."
12240 (interactive)
12241 (save-excursion
12242 (org-back-to-heading t)
12243 (let ((bound1 (point))
12244 (bound0 (save-excursion (outline-next-heading) (point))))
12245 (when (re-search-forward
12246 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12247 org-deadline-time-regexp "\\)\\|\\("
12248 org-ts-regexp "\\)")
12249 bound0 t)
12250 (if (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]" bound1 t)
12251 (replace-match "0" t nil nil 1))))))
12253 (defun org-todo (&optional arg)
12254 "Change the TODO state of an item.
12255 The state of an item is given by a keyword at the start of the heading,
12256 like
12257 *** TODO Write paper
12258 *** DONE Call mom
12260 The different keywords are specified in the variable `org-todo-keywords'.
12261 By default the available states are \"TODO\" and \"DONE\".
12262 So for this example: when the item starts with TODO, it is changed to DONE.
12263 When it starts with DONE, the DONE is removed. And when neither TODO nor
12264 DONE are present, add TODO at the beginning of the heading.
12266 With \\[universal-argument] prefix arg, use completion to determine the new \
12267 state.
12268 With numeric prefix arg, switch to that state.
12269 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12270 keywords (nextset).
12271 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12272 With a numeric prefix arg of 0, inhibit note taking for the change.
12273 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12275 When called through ELisp, arg is also interpreted in the following way:
12276 'none -> empty state
12277 \"\"(empty string) -> switch to empty state
12278 'done -> switch to DONE
12279 'nextset -> switch to the next set of keywords
12280 'previousset -> switch to the previous set of keywords
12281 \"WAITING\" -> switch to the specified keyword, but only if it
12282 really is a member of `org-todo-keywords'."
12283 (interactive "P")
12284 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12285 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12286 'region-start-level 'region))
12287 org-loop-over-headlines-in-active-region)
12288 (org-map-entries
12289 `(org-todo ,arg)
12290 org-loop-over-headlines-in-active-region
12291 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12292 (if (equal arg '(16)) (setq arg 'nextset))
12293 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12294 (let ((org-blocker-hook org-blocker-hook)
12295 commentp
12296 case-fold-search)
12297 (when (equal arg '(64))
12298 (setq arg nil org-blocker-hook nil))
12299 (when (and org-blocker-hook
12300 (or org-inhibit-blocking
12301 (org-entry-get nil "NOBLOCKING")))
12302 (setq org-blocker-hook nil))
12303 (save-excursion
12304 (catch 'exit
12305 (org-back-to-heading t)
12306 (when (looking-at (concat "^\\*+ " org-comment-string))
12307 (org-toggle-comment)
12308 (setq commentp t))
12309 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12310 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12311 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12312 (let* ((match-data (match-data))
12313 (startpos (point-at-bol))
12314 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12315 (org-log-done org-log-done)
12316 (org-log-repeat org-log-repeat)
12317 (org-todo-log-states org-todo-log-states)
12318 (org-inhibit-logging
12319 (if (equal arg 0)
12320 (progn (setq arg nil) 'note) org-inhibit-logging))
12321 (this (match-string 1))
12322 (hl-pos (match-beginning 0))
12323 (head (org-get-todo-sequence-head this))
12324 (ass (assoc head org-todo-kwd-alist))
12325 (interpret (nth 1 ass))
12326 (done-word (nth 3 ass))
12327 (final-done-word (nth 4 ass))
12328 (org-last-state (or this ""))
12329 (completion-ignore-case t)
12330 (member (member this org-todo-keywords-1))
12331 (tail (cdr member))
12332 (org-state (cond
12333 ((and org-todo-key-trigger
12334 (or (and (equal arg '(4))
12335 (eq org-use-fast-todo-selection 'prefix))
12336 (and (not arg) org-use-fast-todo-selection
12337 (not (eq org-use-fast-todo-selection
12338 'prefix)))))
12339 ;; Use fast selection
12340 (org-fast-todo-selection))
12341 ((and (equal arg '(4))
12342 (or (not org-use-fast-todo-selection)
12343 (not org-todo-key-trigger)))
12344 ;; Read a state with completion
12345 (org-icompleting-read
12346 "State: " (mapcar 'list org-todo-keywords-1)
12347 nil t))
12348 ((eq arg 'right)
12349 (if this
12350 (if tail (car tail) nil)
12351 (car org-todo-keywords-1)))
12352 ((eq arg 'left)
12353 (if (equal member org-todo-keywords-1)
12355 (if this
12356 (nth (- (length org-todo-keywords-1)
12357 (length tail) 2)
12358 org-todo-keywords-1)
12359 (org-last org-todo-keywords-1))))
12360 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12361 (setq arg nil))) ; hack to fall back to cycling
12362 (arg
12363 ;; user or caller requests a specific state
12364 (cond
12365 ((equal arg "") nil)
12366 ((eq arg 'none) nil)
12367 ((eq arg 'done) (or done-word (car org-done-keywords)))
12368 ((eq arg 'nextset)
12369 (or (car (cdr (member head org-todo-heads)))
12370 (car org-todo-heads)))
12371 ((eq arg 'previousset)
12372 (let ((org-todo-heads (reverse org-todo-heads)))
12373 (or (car (cdr (member head org-todo-heads)))
12374 (car org-todo-heads))))
12375 ((car (member arg org-todo-keywords-1)))
12376 ((stringp arg)
12377 (user-error "State `%s' not valid in this file" arg))
12378 ((nth (1- (prefix-numeric-value arg))
12379 org-todo-keywords-1))))
12380 ((null member) (or head (car org-todo-keywords-1)))
12381 ((equal this final-done-word) nil) ;; -> make empty
12382 ((null tail) nil) ;; -> first entry
12383 ((memq interpret '(type priority))
12384 (if (eq this-command last-command)
12385 (car tail)
12386 (if (> (length tail) 0)
12387 (or done-word (car org-done-keywords))
12388 nil)))
12390 (car tail))))
12391 (org-state (or
12392 (run-hook-with-args-until-success
12393 'org-todo-get-default-hook org-state org-last-state)
12394 org-state))
12395 (next (if org-state (concat " " org-state " ") " "))
12396 (change-plist (list :type 'todo-state-change :from this :to org-state
12397 :position startpos))
12398 dolog now-done-p)
12399 (when org-blocker-hook
12400 (setq org-last-todo-state-is-todo
12401 (not (member this org-done-keywords)))
12402 (unless (save-excursion
12403 (save-match-data
12404 (org-with-wide-buffer
12405 (run-hook-with-args-until-failure
12406 'org-blocker-hook change-plist))))
12407 (if (org-called-interactively-p 'interactive)
12408 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12409 this org-state org-block-entry-blocking)
12410 ;; fail silently
12411 (message "TODO state change from %s to %s blocked (by \"%s\")"
12412 this org-state org-block-entry-blocking)
12413 (throw 'exit nil))))
12414 (store-match-data match-data)
12415 (replace-match next t t)
12416 (unless (pos-visible-in-window-p hl-pos)
12417 (message "TODO state changed to %s" (org-trim next)))
12418 (unless head
12419 (setq head (org-get-todo-sequence-head org-state)
12420 ass (assoc head org-todo-kwd-alist)
12421 interpret (nth 1 ass)
12422 done-word (nth 3 ass)
12423 final-done-word (nth 4 ass)))
12424 (when (memq arg '(nextset previousset))
12425 (message "Keyword-Set %d/%d: %s"
12426 (- (length org-todo-sets) -1
12427 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12428 (length org-todo-sets)
12429 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12430 (setq org-last-todo-state-is-todo
12431 (not (member org-state org-done-keywords)))
12432 (setq now-done-p (and (member org-state org-done-keywords)
12433 (not (member this org-done-keywords))))
12434 (and logging (org-local-logging logging))
12435 (when (and (or org-todo-log-states org-log-done)
12436 (not (eq org-inhibit-logging t))
12437 (not (memq arg '(nextset previousset))))
12438 ;; we need to look at recording a time and note
12439 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12440 (nth 2 (assoc this org-todo-log-states))))
12441 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12442 (setq dolog 'time))
12443 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12444 (and org-state
12445 (member org-state org-not-done-keywords)
12446 (not (member this org-not-done-keywords))))
12447 ;; This is now a todo state and was not one before
12448 ;; If there was a CLOSED time stamp, get rid of it.
12449 (org-add-planning-info nil nil 'closed))
12450 (when (and now-done-p org-log-done)
12451 ;; It is now done, and it was not done before
12452 (org-add-planning-info 'closed (org-current-effective-time))
12453 (if (and (not dolog) (eq 'note org-log-done))
12454 (org-add-log-setup 'done org-state this 'findpos 'note)))
12455 (when (and org-state dolog)
12456 ;; This is a non-nil state, and we need to log it
12457 (org-add-log-setup 'state org-state this 'findpos dolog)))
12458 ;; Fixup tag positioning
12459 (org-todo-trigger-tag-changes org-state)
12460 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12461 (when org-provide-todo-statistics
12462 (org-update-parent-todo-statistics))
12463 (run-hooks 'org-after-todo-state-change-hook)
12464 (if (and arg (not (member org-state org-done-keywords)))
12465 (setq head (org-get-todo-sequence-head org-state)))
12466 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12467 ;; Do we need to trigger a repeat?
12468 (when now-done-p
12469 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12470 ;; This is for the agenda, take a snapshot of the headline.
12471 (save-match-data
12472 (setq org-agenda-headline-snapshot-before-repeat
12473 (org-get-heading))))
12474 (org-auto-repeat-maybe org-state))
12475 ;; Fixup cursor location if close to the keyword
12476 (if (and (outline-on-heading-p)
12477 (not (bolp))
12478 (save-excursion (beginning-of-line 1)
12479 (looking-at org-todo-line-regexp))
12480 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12481 (progn
12482 (goto-char (or (match-end 2) (match-end 1)))
12483 (and (looking-at " ") (just-one-space))))
12484 (when org-trigger-hook
12485 (save-excursion
12486 (run-hook-with-args 'org-trigger-hook change-plist)))
12487 (when commentp (org-toggle-comment))))))))
12489 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12490 "Block turning an entry into a TODO, using the hierarchy.
12491 This checks whether the current task should be blocked from state
12492 changes. Such blocking occurs when:
12494 1. The task has children which are not all in a completed state.
12496 2. A task has a parent with the property :ORDERED:, and there
12497 are siblings prior to the current task with incomplete
12498 status.
12500 3. The parent of the task is blocked because it has siblings that should
12501 be done first, or is child of a block grandparent TODO entry."
12503 (if (not org-enforce-todo-dependencies)
12504 t ; if locally turned off don't block
12505 (catch 'dont-block
12506 ;; If this is not a todo state change, or if this entry is already DONE,
12507 ;; do not block
12508 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12509 (member (plist-get change-plist :from)
12510 (cons 'done org-done-keywords))
12511 (member (plist-get change-plist :to)
12512 (cons 'todo org-not-done-keywords))
12513 (not (plist-get change-plist :to)))
12514 (throw 'dont-block t))
12515 ;; If this task has children, and any are undone, it's blocked
12516 (save-excursion
12517 (org-back-to-heading t)
12518 (let ((this-level (funcall outline-level)))
12519 (outline-next-heading)
12520 (let ((child-level (funcall outline-level)))
12521 (while (and (not (eobp))
12522 (> child-level this-level))
12523 ;; this todo has children, check whether they are all
12524 ;; completed
12525 (if (and (not (org-entry-is-done-p))
12526 (org-entry-is-todo-p))
12527 (progn (setq org-block-entry-blocking (org-get-heading))
12528 (throw 'dont-block nil)))
12529 (outline-next-heading)
12530 (setq child-level (funcall outline-level))))))
12531 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12532 ;; any previous siblings are undone, it's blocked
12533 (save-excursion
12534 (org-back-to-heading t)
12535 (let* ((pos (point))
12536 (parent-pos (and (org-up-heading-safe) (point))))
12537 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12538 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12539 (forward-line 1)
12540 (re-search-forward org-not-done-heading-regexp pos t))
12541 (setq org-block-entry-blocking (match-string 0))
12542 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12543 ;; Search further up the hierarchy, to see if an ancestor is blocked
12544 (while t
12545 (goto-char parent-pos)
12546 (if (not (looking-at org-not-done-heading-regexp))
12547 (throw 'dont-block t)) ; do not block, parent is not a TODO
12548 (setq pos (point))
12549 (setq parent-pos (and (org-up-heading-safe) (point)))
12550 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12551 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12552 (forward-line 1)
12553 (re-search-forward org-not-done-heading-regexp pos t)
12554 (setq org-block-entry-blocking (org-get-heading)))
12555 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12557 (defcustom org-track-ordered-property-with-tag nil
12558 "Should the ORDERED property also be shown as a tag?
12559 The ORDERED property decides if an entry should require subtasks to be
12560 completed in sequence. Since a property is not very visible, setting
12561 this option means that toggling the ORDERED property with the command
12562 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12563 not relevant for the behavior, but it makes things more visible.
12565 Note that toggling the tag with tags commands will not change the property
12566 and therefore not influence behavior!
12568 This can be t, meaning the tag ORDERED should be used, It can also be a
12569 string to select a different tag for this task."
12570 :group 'org-todo
12571 :type '(choice
12572 (const :tag "No tracking" nil)
12573 (const :tag "Track with ORDERED tag" t)
12574 (string :tag "Use other tag")))
12576 (defun org-toggle-ordered-property ()
12577 "Toggle the ORDERED property of the current entry.
12578 For better visibility, you can track the value of this property with a tag.
12579 See variable `org-track-ordered-property-with-tag'."
12580 (interactive)
12581 (let* ((t1 org-track-ordered-property-with-tag)
12582 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12583 (save-excursion
12584 (org-back-to-heading)
12585 (if (org-entry-get nil "ORDERED")
12586 (progn
12587 (org-delete-property "ORDERED")
12588 (and tag (org-toggle-tag tag 'off))
12589 (message "Subtasks can be completed in arbitrary order"))
12590 (org-entry-put nil "ORDERED" "t")
12591 (and tag (org-toggle-tag tag 'on))
12592 (message "Subtasks must be completed in sequence")))))
12594 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12595 (defun org-block-todo-from-checkboxes (change-plist)
12596 "Block turning an entry into a TODO, using checkboxes.
12597 This checks whether the current task should be blocked from state
12598 changes because there are unchecked boxes in this entry."
12599 (if (not org-enforce-todo-checkbox-dependencies)
12600 t ; if locally turned off don't block
12601 (catch 'dont-block
12602 ;; If this is not a todo state change, or if this entry is already DONE,
12603 ;; do not block
12604 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12605 (member (plist-get change-plist :from)
12606 (cons 'done org-done-keywords))
12607 (member (plist-get change-plist :to)
12608 (cons 'todo org-not-done-keywords))
12609 (not (plist-get change-plist :to)))
12610 (throw 'dont-block t))
12611 ;; If this task has checkboxes that are not checked, it's blocked
12612 (save-excursion
12613 (org-back-to-heading t)
12614 (let ((beg (point)) end)
12615 (outline-next-heading)
12616 (setq end (point))
12617 (goto-char beg)
12618 (if (org-list-search-forward
12619 (concat (org-item-beginning-re)
12620 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12621 "\\[[- ]\\]")
12622 end t)
12623 (progn
12624 (if (boundp 'org-blocked-by-checkboxes)
12625 (setq org-blocked-by-checkboxes t))
12626 (throw 'dont-block nil)))))
12627 t))) ; do not block
12629 (defun org-entry-blocked-p ()
12630 "Is the current entry blocked?"
12631 (org-with-silent-modifications
12632 (if (org-entry-get nil "NOBLOCKING")
12633 nil ;; Never block this entry
12634 (not (run-hook-with-args-until-failure
12635 'org-blocker-hook
12636 (list :type 'todo-state-change
12637 :position (point)
12638 :from 'todo
12639 :to 'done))))))
12641 (defun org-update-statistics-cookies (all)
12642 "Update the statistics cookie, either from TODO or from checkboxes.
12643 This should be called with the cursor in a line with a statistics cookie."
12644 (interactive "P")
12645 (if all
12646 (progn
12647 (org-update-checkbox-count 'all)
12648 (org-map-entries 'org-update-parent-todo-statistics))
12649 (if (not (org-at-heading-p))
12650 (org-update-checkbox-count)
12651 (let ((pos (point-marker))
12652 end l1 l2)
12653 (ignore-errors (org-back-to-heading t))
12654 (if (not (org-at-heading-p))
12655 (org-update-checkbox-count)
12656 (setq l1 (org-outline-level))
12657 (setq end (save-excursion
12658 (outline-next-heading)
12659 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12660 (point)))
12661 (if (and (save-excursion
12662 (re-search-forward
12663 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12664 (not (save-excursion (re-search-forward
12665 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12666 (org-update-checkbox-count)
12667 (if (and l2 (> l2 l1))
12668 (progn
12669 (goto-char end)
12670 (org-update-parent-todo-statistics))
12671 (goto-char pos)
12672 (beginning-of-line 1)
12673 (while (re-search-forward
12674 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12675 (point-at-eol) t)
12676 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12677 (goto-char pos)
12678 (move-marker pos nil)))))
12680 (defvar org-entry-property-inherited-from) ;; defined below
12681 (defun org-update-parent-todo-statistics ()
12682 "Update any statistics cookie in the parent of the current headline.
12683 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12684 the entire subtree and this will travel up the hierarchy and update
12685 statistics everywhere."
12686 (let* ((prop (save-excursion (org-up-heading-safe)
12687 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12688 (recursive (or (not org-hierarchical-todo-statistics)
12689 (and prop (string-match "\\<recursive\\>" prop))))
12690 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12692 (first t)
12693 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12694 level ltoggle l1 new ndel
12695 (cnt-all 0) (cnt-done 0) is-percent kwd
12696 checkbox-beg ov ovs ove cookie-present)
12697 (catch 'exit
12698 (save-excursion
12699 (beginning-of-line 1)
12700 (setq ltoggle (funcall outline-level))
12701 ;; Three situations are to consider:
12703 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12704 ;; to the top-level ancestor on the headline;
12706 ;; 2. If parent has "recursive" property, repeat up to the
12707 ;; headline setting that property, taking inheritance into
12708 ;; account;
12710 ;; 3. Else, move up to direct parent and proceed only once.
12711 (while (and (setq level (org-up-heading-safe))
12712 (or recursive first)
12713 (>= (point) lim))
12714 (setq first nil cookie-present nil)
12715 (unless (and level
12716 (not (string-match
12717 "\\<checkbox\\>"
12718 (downcase (or (org-entry-get nil "COOKIE_DATA")
12719 "")))))
12720 (throw 'exit nil))
12721 (while (re-search-forward box-re (point-at-eol) t)
12722 (setq cnt-all 0 cnt-done 0 cookie-present t)
12723 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12724 (save-match-data
12725 (unless (outline-next-heading) (throw 'exit nil))
12726 (while (and (looking-at org-complex-heading-regexp)
12727 (> (setq l1 (length (match-string 1))) level))
12728 (setq kwd (and (or recursive (= l1 ltoggle))
12729 (match-string 2)))
12730 (if (or (eq org-provide-todo-statistics 'all-headlines)
12731 (and (eq org-provide-todo-statistics t)
12732 (or (member kwd org-done-keywords)))
12733 (and (listp org-provide-todo-statistics)
12734 (stringp (car org-provide-todo-statistics))
12735 (or (member kwd org-provide-todo-statistics)
12736 (member kwd org-done-keywords)))
12737 (and (listp org-provide-todo-statistics)
12738 (listp (car org-provide-todo-statistics))
12739 (or (member kwd (car org-provide-todo-statistics))
12740 (and (member kwd org-done-keywords)
12741 (member kwd (cadr org-provide-todo-statistics))))))
12742 (setq cnt-all (1+ cnt-all))
12743 (if (eq org-provide-todo-statistics t)
12744 (and kwd (setq cnt-all (1+ cnt-all)))))
12745 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12746 (member kwd org-done-keywords))
12747 (and (listp org-provide-todo-statistics)
12748 (listp (car org-provide-todo-statistics))
12749 (member kwd org-done-keywords)
12750 (member kwd (cadr org-provide-todo-statistics)))
12751 (and (listp org-provide-todo-statistics)
12752 (stringp (car org-provide-todo-statistics))
12753 (member kwd org-done-keywords)))
12754 (setq cnt-done (1+ cnt-done)))
12755 (outline-next-heading)))
12756 (setq new
12757 (if is-percent
12758 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12759 (format "[%d/%d]" cnt-done cnt-all))
12760 ndel (- (match-end 0) checkbox-beg))
12761 ;; handle overlays when updating cookie from column view
12762 (when (setq ov (car (overlays-at checkbox-beg)))
12763 (setq ovs (overlay-start ov) ove (overlay-end ov))
12764 (delete-overlay ov))
12765 (goto-char checkbox-beg)
12766 (insert new)
12767 (delete-region (point) (+ (point) ndel))
12768 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12769 (when ov (move-overlay ov ovs ove)))
12770 (when cookie-present
12771 (run-hook-with-args 'org-after-todo-statistics-hook
12772 cnt-done (- cnt-all cnt-done))))))
12773 (run-hooks 'org-todo-statistics-hook)))
12775 (defvar org-after-todo-statistics-hook nil
12776 "Hook that is called after a TODO statistics cookie has been updated.
12777 Each function is called with two arguments: the number of not-done entries
12778 and the number of done entries.
12780 For example, the following function, when added to this hook, will switch
12781 an entry to DONE when all children are done, and back to TODO when new
12782 entries are set to a TODO status. Note that this hook is only called
12783 when there is a statistics cookie in the headline!
12785 (defun org-summary-todo (n-done n-not-done)
12786 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12787 (let (org-log-done org-log-states) ; turn off logging
12788 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12791 (defvar org-todo-statistics-hook nil
12792 "Hook that is run whenever Org thinks TODO statistics should be updated.
12793 This hook runs even if there is no statistics cookie present, in which case
12794 `org-after-todo-statistics-hook' would not run.")
12796 (defun org-todo-trigger-tag-changes (state)
12797 "Apply the changes defined in `org-todo-state-tags-triggers'."
12798 (let ((l org-todo-state-tags-triggers)
12799 changes)
12800 (when (or (not state) (equal state ""))
12801 (setq changes (append changes (cdr (assoc "" l)))))
12802 (when (and (stringp state) (> (length state) 0))
12803 (setq changes (append changes (cdr (assoc state l)))))
12804 (when (member state org-not-done-keywords)
12805 (setq changes (append changes (cdr (assoc 'todo l)))))
12806 (when (member state org-done-keywords)
12807 (setq changes (append changes (cdr (assoc 'done l)))))
12808 (dolist (c changes)
12809 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12811 (defun org-local-logging (value)
12812 "Get logging settings from a property VALUE."
12813 (let* (words w a)
12814 ;; directly set the variables, they are already local.
12815 (setq org-log-done nil
12816 org-log-repeat nil
12817 org-todo-log-states nil)
12818 (setq words (org-split-string value))
12819 (while (setq w (pop words))
12820 (cond
12821 ((setq a (assoc w org-startup-options))
12822 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12823 (set (nth 1 a) (nth 2 a))))
12824 ((setq a (org-extract-log-state-settings w))
12825 (and (member (car a) org-todo-keywords-1)
12826 (push a org-todo-log-states)))))))
12828 (defun org-get-todo-sequence-head (kwd)
12829 "Return the head of the TODO sequence to which KWD belongs.
12830 If KWD is not set, check if there is a text property remembering the
12831 right sequence."
12832 (let (p)
12833 (cond
12834 ((not kwd)
12835 (or (get-text-property (point-at-bol) 'org-todo-head)
12836 (progn
12837 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12838 nil (point-at-eol)))
12839 (get-text-property p 'org-todo-head))))
12840 ((not (member kwd org-todo-keywords-1))
12841 (car org-todo-keywords-1))
12842 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12844 (defun org-fast-todo-selection ()
12845 "Fast TODO keyword selection with single keys.
12846 Returns the new TODO keyword, or nil if no state change should occur."
12847 (let* ((fulltable org-todo-key-alist)
12848 (done-keywords org-done-keywords) ;; needed for the faces.
12849 (maxlen (apply 'max (mapcar
12850 (lambda (x)
12851 (if (stringp (car x)) (string-width (car x)) 0))
12852 fulltable)))
12853 (expert nil)
12854 (fwidth (+ maxlen 3 1 3))
12855 (ncol (/ (- (window-width) 4) fwidth))
12856 tg cnt e c tbl
12857 groups ingroup)
12858 (save-excursion
12859 (save-window-excursion
12860 (if expert
12861 (set-buffer (get-buffer-create " *Org todo*"))
12862 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12863 (erase-buffer)
12864 (org-set-local 'org-done-keywords done-keywords)
12865 (setq tbl fulltable cnt 0)
12866 (while (setq e (pop tbl))
12867 (cond
12868 ((equal e '(:startgroup))
12869 (push '() groups) (setq ingroup t)
12870 (when (not (= cnt 0))
12871 (setq cnt 0)
12872 (insert "\n"))
12873 (insert "{ "))
12874 ((equal e '(:endgroup))
12875 (setq ingroup nil cnt 0)
12876 (insert "}\n"))
12877 ((equal e '(:newline))
12878 (when (not (= cnt 0))
12879 (setq cnt 0)
12880 (insert "\n")
12881 (setq e (car tbl))
12882 (while (equal (car tbl) '(:newline))
12883 (insert "\n")
12884 (setq tbl (cdr tbl)))))
12886 (setq tg (car e) c (cdr e))
12887 (if ingroup (push tg (car groups)))
12888 (setq tg (org-add-props tg nil 'face
12889 (org-get-todo-face tg)))
12890 (if (and (= cnt 0) (not ingroup)) (insert " "))
12891 (insert "[" c "] " tg (make-string
12892 (- fwidth 4 (length tg)) ?\ ))
12893 (when (= (setq cnt (1+ cnt)) ncol)
12894 (insert "\n")
12895 (if ingroup (insert " "))
12896 (setq cnt 0)))))
12897 (insert "\n")
12898 (goto-char (point-min))
12899 (if (not expert) (org-fit-window-to-buffer))
12900 (message "[a-z..]:Set [SPC]:clear")
12901 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12902 (cond
12903 ((or (= c ?\C-g)
12904 (and (= c ?q) (not (rassoc c fulltable))))
12905 (setq quit-flag t))
12906 ((= c ?\ ) nil)
12907 ((setq e (rassoc c fulltable) tg (car e))
12909 (t (setq quit-flag t)))))))
12911 (defun org-entry-is-todo-p ()
12912 (member (org-get-todo-state) org-not-done-keywords))
12914 (defun org-entry-is-done-p ()
12915 (member (org-get-todo-state) org-done-keywords))
12917 (defun org-get-todo-state ()
12918 "Return the TODO keyword of the current subtree."
12919 (save-excursion
12920 (org-back-to-heading t)
12921 (and (looking-at org-todo-line-regexp)
12922 (match-end 2)
12923 (match-string 2))))
12925 (defun org-at-date-range-p (&optional inactive-ok)
12926 "Is the cursor inside a date range?"
12927 (interactive)
12928 (save-excursion
12929 (catch 'exit
12930 (let ((pos (point)))
12931 (skip-chars-backward "^[<\r\n")
12932 (skip-chars-backward "<[")
12933 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12934 (>= (match-end 0) pos)
12935 (throw 'exit t))
12936 (skip-chars-backward "^<[\r\n")
12937 (skip-chars-backward "<[")
12938 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12939 (>= (match-end 0) pos)
12940 (throw 'exit t)))
12941 nil)))
12943 (defun org-get-repeat (&optional tagline)
12944 "Check if there is a deadline/schedule with repeater in this entry."
12945 (save-match-data
12946 (save-excursion
12947 (org-back-to-heading t)
12948 (and (re-search-forward (if tagline
12949 (concat tagline "\\s-*" org-repeat-re)
12950 org-repeat-re)
12951 (org-entry-end-position) t)
12952 (match-string-no-properties 1)))))
12954 (defvar org-last-changed-timestamp)
12955 (defvar org-last-inserted-timestamp)
12956 (defvar org-log-post-message)
12957 (defvar org-log-note-purpose)
12958 (defvar org-log-note-how)
12959 (defvar org-log-note-extra)
12960 (defun org-auto-repeat-maybe (done-word)
12961 "Check if the current headline contains a repeated deadline/schedule.
12962 If yes, set TODO state back to what it was and change the base date
12963 of repeating deadline/scheduled time stamps to new date.
12964 This function is run automatically after each state change to a DONE state."
12965 ;; last-state is dynamically scoped into this function
12966 (let* ((repeat (org-get-repeat))
12967 (aa (assoc org-last-state org-todo-kwd-alist))
12968 (interpret (nth 1 aa))
12969 (head (nth 2 aa))
12970 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12971 (msg "Entry repeats: ")
12972 (org-log-done nil)
12973 (org-todo-log-states nil)
12974 re type n what ts time to-state)
12975 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
12976 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12977 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12978 org-todo-repeat-to-state))
12979 (unless (and to-state (member to-state org-todo-keywords-1))
12980 (setq to-state (if (eq interpret 'type) org-last-state head)))
12981 (org-todo to-state)
12982 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12983 (org-entry-put nil "LAST_REPEAT" (format-time-string
12984 (org-time-stamp-format t t))))
12985 (when org-log-repeat
12986 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12987 (memq 'org-add-log-note post-command-hook))
12988 ;; OK, we are already setup for some record
12989 (if (eq org-log-repeat 'note)
12990 ;; make sure we take a note, not only a time stamp
12991 (setq org-log-note-how 'note))
12992 ;; Set up for taking a record
12993 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12994 org-last-state
12995 'findpos org-log-repeat)))
12996 (org-back-to-heading t)
12997 (org-add-planning-info nil nil 'closed)
12998 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12999 org-deadline-time-regexp "\\)\\|\\("
13000 org-ts-regexp "\\)"))
13001 (while (re-search-forward
13002 re (save-excursion (outline-next-heading) (point)) t)
13003 (setq type (if (match-end 1) org-scheduled-string
13004 (if (match-end 3) org-deadline-string "Plain:"))
13005 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
13006 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
13007 (setq n (string-to-number (match-string 2 ts))
13008 what (match-string 3 ts))
13009 (if (equal what "w") (setq n (* n 7) what "d"))
13010 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
13011 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
13012 ;; Preparation, see if we need to modify the start date for the change
13013 (when (match-end 1)
13014 (setq time (save-match-data (org-time-string-to-time ts)))
13015 (cond
13016 ((equal (match-string 1 ts) ".")
13017 ;; Shift starting date to today
13018 (org-timestamp-change
13019 (- (org-today) (time-to-days time))
13020 'day))
13021 ((equal (match-string 1 ts) "+")
13022 (let ((nshiftmax 10) (nshift 0))
13023 (while (or (= nshift 0)
13024 (<= (time-to-days time)
13025 (time-to-days (current-time))))
13026 (when (= (incf nshift) nshiftmax)
13027 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
13028 (error "Abort")))
13029 (org-timestamp-change n (cdr (assoc what whata)))
13030 (org-at-timestamp-p t)
13031 (setq ts (match-string 1))
13032 (setq time (save-match-data (org-time-string-to-time ts)))))
13033 (org-timestamp-change (- n) (cdr (assoc what whata)))
13034 ;; rematch, so that we have everything in place for the real shift
13035 (org-at-timestamp-p t)
13036 (setq ts (match-string 1))
13037 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
13038 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
13039 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
13040 (setq org-log-post-message msg)
13041 (message "%s" msg))))
13043 (defun org-show-todo-tree (arg)
13044 "Make a compact tree which shows all headlines marked with TODO.
13045 The tree will show the lines where the regexp matches, and all higher
13046 headlines above the match.
13047 With a \\[universal-argument] prefix, prompt for a regexp to match.
13048 With a numeric prefix N, construct a sparse tree for the Nth element
13049 of `org-todo-keywords-1'."
13050 (interactive "P")
13051 (let ((case-fold-search nil)
13052 (kwd-re
13053 (cond ((null arg) org-not-done-regexp)
13054 ((equal arg '(4))
13055 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
13056 (mapcar 'list org-todo-keywords-1))))
13057 (concat "\\("
13058 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13059 "\\)\\>")))
13060 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13061 (regexp-quote (nth (1- (prefix-numeric-value arg))
13062 org-todo-keywords-1)))
13063 (t (user-error "Invalid prefix argument: %s" arg)))))
13064 (message "%d TODO entries found"
13065 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13067 (defun org-deadline (arg &optional time)
13068 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13069 With one universal prefix argument, remove any deadline from the item.
13070 With two universal prefix arguments, prompt for a warning delay.
13071 With argument TIME, set the deadline at the corresponding date. TIME
13072 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13073 (interactive "P")
13074 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13075 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13076 'region-start-level 'region))
13077 org-loop-over-headlines-in-active-region)
13078 (org-map-entries
13079 `(org-deadline ',arg ,time)
13080 org-loop-over-headlines-in-active-region
13081 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13082 (let* ((old-date (org-entry-get nil "DEADLINE"))
13083 (old-date-time (if old-date (org-time-string-to-time old-date)))
13084 (repeater (and old-date
13085 (string-match
13086 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13087 old-date)
13088 (match-string 1 old-date))))
13089 (cond
13090 ((equal arg '(4))
13091 (when (and old-date org-log-redeadline)
13092 (org-add-log-setup 'deldeadline nil old-date 'findpos
13093 org-log-redeadline))
13094 (org-remove-timestamp-with-keyword org-deadline-string)
13095 (message "Item no longer has a deadline."))
13096 ((equal arg '(16))
13097 (save-excursion
13098 (org-back-to-heading t)
13099 (if (re-search-forward
13100 org-deadline-time-regexp
13101 (save-excursion (outline-next-heading) (point)) t)
13102 (let* ((rpl0 (match-string 1))
13103 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13104 (replace-match
13105 (concat org-deadline-string
13106 " <" rpl
13107 (format " -%dd"
13108 (abs
13109 (- (time-to-days
13110 (save-match-data
13111 (org-read-date nil t nil "Warn starting from" old-date-time)))
13112 (time-to-days old-date-time))))
13113 ">") t t))
13114 (user-error "No deadline information to update"))))
13116 (org-add-planning-info 'deadline time 'closed)
13117 (when (and old-date org-log-redeadline
13118 (not (equal old-date
13119 (substring org-last-inserted-timestamp 1 -1))))
13120 (org-add-log-setup 'redeadline nil old-date 'findpos
13121 org-log-redeadline))
13122 (when repeater
13123 (save-excursion
13124 (org-back-to-heading t)
13125 (when (re-search-forward (concat org-deadline-string " "
13126 org-last-inserted-timestamp)
13127 (save-excursion
13128 (outline-next-heading) (point)) t)
13129 (goto-char (1- (match-end 0)))
13130 (insert " " repeater)
13131 (setq org-last-inserted-timestamp
13132 (concat (substring org-last-inserted-timestamp 0 -1)
13133 " " repeater
13134 (substring org-last-inserted-timestamp -1))))))
13135 (message "Deadline on %s" org-last-inserted-timestamp))))))
13137 (defun org-schedule (arg &optional time)
13138 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13139 With one universal prefix argument, remove any scheduling date from the item.
13140 With two universal prefix arguments, prompt for a delay cookie.
13141 With argument TIME, scheduled at the corresponding date. TIME can
13142 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13143 (interactive "P")
13144 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13145 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13146 'region-start-level 'region))
13147 org-loop-over-headlines-in-active-region)
13148 (org-map-entries
13149 `(org-schedule ',arg ,time)
13150 org-loop-over-headlines-in-active-region
13151 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13152 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13153 (old-date-time (if old-date (org-time-string-to-time old-date)))
13154 (repeater (and old-date
13155 (string-match
13156 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13157 old-date)
13158 (match-string 1 old-date))))
13159 (cond
13160 ((equal arg '(4))
13161 (progn
13162 (when (and old-date org-log-reschedule)
13163 (org-add-log-setup 'delschedule nil old-date 'findpos
13164 org-log-reschedule))
13165 (org-remove-timestamp-with-keyword org-scheduled-string)
13166 (message "Item is no longer scheduled.")))
13167 ((equal arg '(16))
13168 (save-excursion
13169 (org-back-to-heading t)
13170 (if (re-search-forward
13171 org-scheduled-time-regexp
13172 (save-excursion (outline-next-heading) (point)) t)
13173 (let* ((rpl0 (match-string 1))
13174 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13175 (replace-match
13176 (concat org-scheduled-string
13177 " <" rpl
13178 (format " -%dd"
13179 (abs
13180 (- (time-to-days
13181 (save-match-data
13182 (org-read-date nil t nil "Delay until" old-date-time)))
13183 (time-to-days old-date-time))))
13184 ">") t t))
13185 (user-error "No scheduled information to update"))))
13187 (org-add-planning-info 'scheduled time 'closed)
13188 (when (and old-date org-log-reschedule
13189 (not (equal old-date
13190 (substring org-last-inserted-timestamp 1 -1))))
13191 (org-add-log-setup 'reschedule nil old-date 'findpos
13192 org-log-reschedule))
13193 (when repeater
13194 (save-excursion
13195 (org-back-to-heading t)
13196 (when (re-search-forward (concat org-scheduled-string " "
13197 org-last-inserted-timestamp)
13198 (save-excursion
13199 (outline-next-heading) (point)) t)
13200 (goto-char (1- (match-end 0)))
13201 (insert " " repeater)
13202 (setq org-last-inserted-timestamp
13203 (concat (substring org-last-inserted-timestamp 0 -1)
13204 " " repeater
13205 (substring org-last-inserted-timestamp -1))))))
13206 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13208 (defun org-get-scheduled-time (pom &optional inherit)
13209 "Get the scheduled time as a time tuple, of a format suitable
13210 for calling org-schedule with, or if there is no scheduling,
13211 returns nil."
13212 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13213 (when time
13214 (apply 'encode-time (org-parse-time-string time)))))
13216 (defun org-get-deadline-time (pom &optional inherit)
13217 "Get the deadline as a time tuple, of a format suitable for
13218 calling org-deadline with, or if there is no scheduling, returns
13219 nil."
13220 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13221 (when time
13222 (apply 'encode-time (org-parse-time-string time)))))
13224 (defun org-remove-timestamp-with-keyword (keyword)
13225 "Remove all time stamps with KEYWORD in the current entry."
13226 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13227 beg)
13228 (save-excursion
13229 (org-back-to-heading t)
13230 (setq beg (point))
13231 (outline-next-heading)
13232 (while (re-search-backward re beg t)
13233 (replace-match "")
13234 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13235 (equal (char-before) ?\ ))
13236 (backward-delete-char 1)
13237 (if (string-match "^[ \t]*$" (buffer-substring
13238 (point-at-bol) (point-at-eol)))
13239 (delete-region (point-at-bol)
13240 (min (point-max) (1+ (point-at-eol))))))))))
13242 (defvar org-time-was-given) ; dynamically scoped parameter
13243 (defvar org-end-time-was-given) ; dynamically scoped parameter
13245 (defun org-add-planning-info (what &optional time &rest remove)
13246 "Insert new timestamp with keyword in the line directly after the headline.
13247 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13248 If non is given, the user is prompted for a date.
13249 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13250 be removed."
13251 (interactive)
13252 (let (org-time-was-given org-end-time-was-given ts
13253 end default-time default-input)
13255 (catch 'exit
13256 (when (and (memq what '(scheduled deadline))
13257 (or (not time)
13258 (and (stringp time)
13259 (string-match "^[-+]+[0-9]" time))))
13260 ;; Try to get a default date/time from existing timestamp
13261 (save-excursion
13262 (org-back-to-heading t)
13263 (setq end (save-excursion (outline-next-heading) (point)))
13264 (when (re-search-forward (if (eq what 'scheduled)
13265 org-scheduled-time-regexp
13266 org-deadline-time-regexp)
13267 end t)
13268 (setq ts (match-string 1)
13269 default-time
13270 (apply 'encode-time (org-parse-time-string ts))
13271 default-input (and ts (org-get-compact-tod ts))))))
13272 (when what
13273 (setq time
13274 (if (stringp time)
13275 ;; This is a string (relative or absolute), set proper date
13276 (apply 'encode-time
13277 (org-read-date-analyze
13278 time default-time (decode-time default-time)))
13279 ;; If necessary, get the time from the user
13280 (or time (org-read-date nil 'to-time nil nil
13281 default-time default-input)))))
13283 (when (and org-insert-labeled-timestamps-at-point
13284 (member what '(scheduled deadline)))
13285 (insert
13286 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13287 (org-insert-time-stamp time org-time-was-given
13288 nil nil nil (list org-end-time-was-given))
13289 (setq what nil))
13290 (save-excursion
13291 (save-restriction
13292 (let (col list elt ts buffer-invisibility-spec)
13293 (org-back-to-heading t)
13294 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13295 (goto-char (match-end 1))
13296 (setq col (current-column))
13297 (goto-char (match-end 0))
13298 (if (eobp) (insert "\n") (forward-char 1))
13299 (when (and (not what)
13300 (not (looking-at
13301 (concat "[ \t]*"
13302 org-keyword-time-not-clock-regexp))))
13303 ;; Nothing to add, nothing to remove...... :-)
13304 (throw 'exit nil))
13305 (if (and (not (looking-at org-outline-regexp))
13306 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13307 "[^\r\n]*"))
13308 (not (equal (match-string 1) org-clock-string)))
13309 (narrow-to-region (match-beginning 0) (match-end 0))
13310 (insert-before-markers "\n")
13311 (backward-char 1)
13312 (narrow-to-region (point) (point))
13313 (and org-adapt-indentation (org-indent-to-column col)))
13314 ;; Check if we have to remove something.
13315 (setq list (cons what remove))
13316 (while list
13317 (setq elt (pop list))
13318 (when (or (and (eq elt 'scheduled)
13319 (re-search-forward org-scheduled-time-regexp nil t))
13320 (and (eq elt 'deadline)
13321 (re-search-forward org-deadline-time-regexp nil t))
13322 (and (eq elt 'closed)
13323 (re-search-forward org-closed-time-regexp nil t)))
13324 (replace-match "")
13325 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13326 (and (looking-at "[ \t]+") (replace-match ""))
13327 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13328 (when what
13329 (insert
13330 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13331 (cond ((eq what 'scheduled) org-scheduled-string)
13332 ((eq what 'deadline) org-deadline-string)
13333 ((eq what 'closed) org-closed-string))
13334 " ")
13335 (setq ts (org-insert-time-stamp
13336 time
13337 (or org-time-was-given
13338 (and (eq what 'closed) org-log-done-with-time))
13339 (eq what 'closed)
13340 nil nil (list org-end-time-was-given)))
13341 (insert
13342 (if (not (or (bolp) (eq (char-before) ?\ )
13343 (memq (char-after) '(32 10))
13344 (eobp))) " " ""))
13345 (end-of-line 1))
13346 (goto-char (point-min))
13347 (widen)
13348 (if (and (looking-at "[ \t]*\n")
13349 (equal (char-before) ?\n))
13350 (delete-region (1- (point)) (point-at-eol)))
13351 ts))))))
13353 (defvar org-log-note-marker (make-marker))
13354 (defvar org-log-note-purpose nil)
13355 (defvar org-log-note-state nil)
13356 (defvar org-log-note-previous-state nil)
13357 (defvar org-log-note-how nil)
13358 (defvar org-log-note-extra nil)
13359 (defvar org-log-note-window-configuration nil)
13360 (defvar org-log-note-return-to (make-marker))
13361 (defvar org-log-note-effective-time nil
13362 "Remembered current time so that dynamically scoped
13363 `org-extend-today-until' affects tha timestamps in state change
13364 log")
13366 (defvar org-log-post-message nil
13367 "Message to be displayed after a log note has been stored.
13368 The auto-repeater uses this.")
13370 (defun org-add-note ()
13371 "Add a note to the current entry.
13372 This is done in the same way as adding a state change note."
13373 (interactive)
13374 (org-add-log-setup 'note nil nil 'findpos nil))
13376 (defvar org-property-end-re)
13377 (defun org-add-log-setup (&optional purpose state prev-state
13378 findpos how extra)
13379 "Set up the post command hook to take a note.
13380 If this is about to TODO state change, the new state is expected in STATE.
13381 When FINDPOS is non-nil, find the correct position for the note in
13382 the current entry. If not, assume that it can be inserted at point.
13383 HOW is an indicator what kind of note should be created.
13384 EXTRA is additional text that will be inserted into the notes buffer."
13385 (let* ((org-log-into-drawer (org-log-into-drawer))
13386 (drawer (cond ((stringp org-log-into-drawer)
13387 org-log-into-drawer)
13388 (org-log-into-drawer "LOGBOOK"))))
13389 (save-restriction
13390 (save-excursion
13391 (when findpos
13392 (org-back-to-heading t)
13393 (narrow-to-region (point) (save-excursion
13394 (outline-next-heading) (point)))
13395 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13396 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13397 "[^\r\n]*\\)?"))
13398 (goto-char (match-end 0))
13399 (cond
13400 (drawer
13401 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13402 nil t)
13403 (progn
13404 (goto-char (match-end 0))
13405 (or org-log-states-order-reversed
13406 (and (re-search-forward org-property-end-re nil t)
13407 (goto-char (1- (match-beginning 0))))))
13408 (insert "\n:" drawer ":\n:END:")
13409 (beginning-of-line 0)
13410 (org-indent-line)
13411 (beginning-of-line 2)
13412 (org-indent-line)
13413 (end-of-line 0)))
13414 ((and org-log-state-notes-insert-after-drawers
13415 (save-excursion
13416 (forward-line) (looking-at org-drawer-regexp)))
13417 (forward-line)
13418 (while (looking-at org-drawer-regexp)
13419 (goto-char (match-end 0))
13420 (re-search-forward org-property-end-re (point-max) t)
13421 (forward-line))
13422 (forward-line -1)))
13423 (unless org-log-states-order-reversed
13424 (and (= (char-after) ?\n) (forward-char 1))
13425 (org-skip-over-state-notes)
13426 (skip-chars-backward " \t\n\r")))
13427 (move-marker org-log-note-marker (point))
13428 (setq org-log-note-purpose purpose
13429 org-log-note-state state
13430 org-log-note-previous-state prev-state
13431 org-log-note-how how
13432 org-log-note-extra extra
13433 org-log-note-effective-time (org-current-effective-time))
13434 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13436 (defun org-skip-over-state-notes ()
13437 "Skip past the list of State notes in an entry."
13438 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13439 (when (ignore-errors (goto-char (org-in-item-p)))
13440 (let* ((struct (org-list-struct))
13441 (prevs (org-list-prevs-alist struct)))
13442 (while (looking-at "[ \t]*- State")
13443 (goto-char (or (org-list-get-next-item (point) struct prevs)
13444 (org-list-get-item-end (point) struct)))))))
13446 (defun org-add-log-note (&optional purpose)
13447 "Pop up a window for taking a note, and add this note later at point."
13448 (remove-hook 'post-command-hook 'org-add-log-note)
13449 (setq org-log-note-window-configuration (current-window-configuration))
13450 (delete-other-windows)
13451 (move-marker org-log-note-return-to (point))
13452 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13453 (goto-char org-log-note-marker)
13454 (org-switch-to-buffer-other-window "*Org Note*")
13455 (erase-buffer)
13456 (if (memq org-log-note-how '(time state))
13457 (let (current-prefix-arg) (org-store-log-note))
13458 (let ((org-inhibit-startup t)) (org-mode))
13459 (insert (format "# Insert note for %s.
13460 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13461 (cond
13462 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13463 ((eq org-log-note-purpose 'done) "closed todo item")
13464 ((eq org-log-note-purpose 'state)
13465 (format "state change from \"%s\" to \"%s\""
13466 (or org-log-note-previous-state "")
13467 (or org-log-note-state "")))
13468 ((eq org-log-note-purpose 'reschedule)
13469 "rescheduling")
13470 ((eq org-log-note-purpose 'delschedule)
13471 "no longer scheduled")
13472 ((eq org-log-note-purpose 'redeadline)
13473 "changing deadline")
13474 ((eq org-log-note-purpose 'deldeadline)
13475 "removing deadline")
13476 ((eq org-log-note-purpose 'refile)
13477 "refiling")
13478 ((eq org-log-note-purpose 'note)
13479 "this entry")
13480 (t (error "This should not happen")))))
13481 (if org-log-note-extra (insert org-log-note-extra))
13482 (org-set-local 'org-finish-function 'org-store-log-note)
13483 (run-hooks 'org-log-buffer-setup-hook)))
13485 (defvar org-note-abort nil) ; dynamically scoped
13486 (defun org-store-log-note ()
13487 "Finish taking a log note, and insert it to where it belongs."
13488 (let ((txt (buffer-string)))
13489 (kill-buffer (current-buffer))
13490 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13491 lines ind bul)
13492 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13493 (setq txt (replace-match "" t t txt)))
13494 (if (string-match "\\s-+\\'" txt)
13495 (setq txt (replace-match "" t t txt)))
13496 (setq lines (org-split-string txt "\n"))
13497 (when (and note (string-match "\\S-" note))
13498 (setq note
13499 (org-replace-escapes
13500 note
13501 (list (cons "%u" (user-login-name))
13502 (cons "%U" user-full-name)
13503 (cons "%t" (format-time-string
13504 (org-time-stamp-format 'long 'inactive)
13505 org-log-note-effective-time))
13506 (cons "%T" (format-time-string
13507 (org-time-stamp-format 'long nil)
13508 org-log-note-effective-time))
13509 (cons "%d" (format-time-string
13510 (org-time-stamp-format nil 'inactive)
13511 org-log-note-effective-time))
13512 (cons "%D" (format-time-string
13513 (org-time-stamp-format nil nil)
13514 org-log-note-effective-time))
13515 (cons "%s" (if org-log-note-state
13516 (concat "\"" org-log-note-state "\"")
13517 ""))
13518 (cons "%S" (if org-log-note-previous-state
13519 (concat "\"" org-log-note-previous-state "\"")
13520 "\"\"")))))
13521 (if lines (setq note (concat note " \\\\")))
13522 (push note lines))
13523 (when (or current-prefix-arg org-note-abort)
13524 (when org-log-into-drawer
13525 (org-remove-empty-drawer-at org-log-note-marker))
13526 (setq lines nil))
13527 (when lines
13528 (with-current-buffer (marker-buffer org-log-note-marker)
13529 (save-excursion
13530 (goto-char org-log-note-marker)
13531 (move-marker org-log-note-marker nil)
13532 (end-of-line 1)
13533 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13534 (setq ind (save-excursion
13535 (if (ignore-errors (goto-char (org-in-item-p)))
13536 (let ((struct (org-list-struct)))
13537 (org-list-get-ind
13538 (org-list-get-top-point struct) struct))
13539 (skip-chars-backward " \r\t\n")
13540 (cond
13541 ((and (org-at-heading-p)
13542 org-adapt-indentation)
13543 (1+ (org-current-level)))
13544 ((org-at-heading-p) 0)
13545 (t (org-get-indentation))))))
13546 (setq bul (org-list-bullet-string "-"))
13547 (org-indent-line-to ind)
13548 (insert bul (pop lines))
13549 (let ((ind-body (+ (length bul) ind)))
13550 (while lines
13551 (insert "\n")
13552 (org-indent-line-to ind-body)
13553 (insert (pop lines))))
13554 (message "Note stored")
13555 (org-back-to-heading t)
13556 (org-cycle-hide-drawers 'children))
13557 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13558 ;; from within `org-add-log-note' because `buffer-undo-list'
13559 ;; is then modified outside of `org-with-remote-undo'.
13560 (when (eq this-command 'org-agenda-todo)
13561 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13562 ;; Don't add undo information when called from `org-agenda-todo'
13563 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13564 (set-window-configuration org-log-note-window-configuration)
13565 (with-current-buffer (marker-buffer org-log-note-return-to)
13566 (goto-char org-log-note-return-to))
13567 (move-marker org-log-note-return-to nil)
13568 (and org-log-post-message (message "%s" org-log-post-message))))
13570 (defun org-remove-empty-drawer-at (pos)
13571 "Remove an empty drawer at position POS.
13572 POS may also be a marker."
13573 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13574 (org-with-wide-buffer
13575 (goto-char pos)
13576 (let ((drawer (org-element-at-point)))
13577 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13578 (not (org-element-property :contents-begin drawer)))
13579 (delete-region (org-element-property :begin drawer)
13580 (progn (goto-char (org-element-property :end drawer))
13581 (skip-chars-backward " \r\t\n")
13582 (forward-line)
13583 (point))))))))
13585 (defvar org-ts-type nil)
13586 (defun org-sparse-tree (&optional arg type)
13587 "Create a sparse tree, prompt for the details.
13588 This command can create sparse trees. You first need to select the type
13589 of match used to create the tree:
13591 t Show all TODO entries.
13592 T Show entries with a specific TODO keyword.
13593 m Show entries selected by a tags/property match.
13594 p Enter a property name and its value (both with completion on existing
13595 names/values) and show entries with that property.
13596 r Show entries matching a regular expression (`/' can be used as well).
13597 b Show deadlines and scheduled items before a date.
13598 a Show deadlines and scheduled items after a date.
13599 d Show deadlines due within `org-deadline-warning-days'.
13600 D Show deadlines and scheduled items between a date range."
13601 (interactive "P")
13602 (let (ans kwd value ts-type)
13603 (setq type (or type org-sparse-tree-default-date-type))
13604 (setq org-ts-type type)
13605 (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"
13606 (cond ((eq type 'all) "all timestamps")
13607 ((eq type 'scheduled) "only scheduled")
13608 ((eq type 'deadline) "only deadline")
13609 ((eq type 'active) "only active timestamps")
13610 ((eq type 'inactive) "only inactive timestamps")
13611 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13612 ((eq type 'closed) "with a closed time-stamp")
13613 (t "scheduled/deadline")))
13614 (setq ans (read-char-exclusive))
13615 (cond
13616 ((equal ans ?c)
13617 (org-sparse-tree
13618 arg (cadr (member type '(scheduled-or-deadline
13619 all scheduled deadline active inactive closed)))))
13620 ((equal ans ?d)
13621 (call-interactively 'org-check-deadlines))
13622 ((equal ans ?b)
13623 (call-interactively 'org-check-before-date))
13624 ((equal ans ?a)
13625 (call-interactively 'org-check-after-date))
13626 ((equal ans ?D)
13627 (call-interactively 'org-check-dates-range))
13628 ((equal ans ?t)
13629 (call-interactively 'org-show-todo-tree))
13630 ((equal ans ?T)
13631 (org-show-todo-tree '(4)))
13632 ((member ans '(?T ?m))
13633 (call-interactively 'org-match-sparse-tree))
13634 ((member ans '(?p ?P))
13635 (setq kwd (org-icompleting-read "Property: "
13636 (mapcar 'list (org-buffer-property-keys))))
13637 (setq value (org-icompleting-read "Value: "
13638 (mapcar 'list (org-property-values kwd))))
13639 (unless (string-match "\\`{.*}\\'" value)
13640 (setq value (concat "\"" value "\"")))
13641 (org-match-sparse-tree arg (concat kwd "=" value)))
13642 ((member ans '(?r ?R ?/))
13643 (call-interactively 'org-occur))
13644 (t (user-error "No such sparse tree command \"%c\"" ans)))))
13646 (defvar org-occur-highlights nil
13647 "List of overlays used for occur matches.")
13648 (make-variable-buffer-local 'org-occur-highlights)
13649 (defvar org-occur-parameters nil
13650 "Parameters of the active org-occur calls.
13651 This is a list, each call to org-occur pushes as cons cell,
13652 containing the regular expression and the callback, onto the list.
13653 The list can contain several entries if `org-occur' has been called
13654 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13655 will only contain one set of parameters. When the highlights are
13656 removed (for example with `C-c C-c', or with the next edit (depending
13657 on `org-remove-highlights-with-change'), this variable is emptied
13658 as well.")
13659 (make-variable-buffer-local 'org-occur-parameters)
13661 (defun org-occur (regexp &optional keep-previous callback)
13662 "Make a compact tree which shows all matches of REGEXP.
13663 The tree will show the lines where the regexp matches, and all higher
13664 headlines above the match. It will also show the heading after the match,
13665 to make sure editing the matching entry is easy.
13666 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13667 call to `org-occur' will be kept, to allow stacking of calls to this
13668 command.
13669 If CALLBACK is non-nil, it is a function which is called to confirm
13670 that the match should indeed be shown."
13671 (interactive "sRegexp: \nP")
13672 (when (equal regexp "")
13673 (user-error "Regexp cannot be empty"))
13674 (unless keep-previous
13675 (org-remove-occur-highlights nil nil t))
13676 (push (cons regexp callback) org-occur-parameters)
13677 (let ((cnt 0))
13678 (save-excursion
13679 (goto-char (point-min))
13680 (if (or (not keep-previous) ; do not want to keep
13681 (not org-occur-highlights)) ; no previous matches
13682 ;; hide everything
13683 (org-overview))
13684 (while (re-search-forward regexp nil t)
13685 (when (or (not callback)
13686 (save-match-data (funcall callback)))
13687 (setq cnt (1+ cnt))
13688 (when org-highlight-sparse-tree-matches
13689 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13690 (org-show-context 'occur-tree))))
13691 (when org-remove-highlights-with-change
13692 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13693 nil 'local))
13694 (unless org-sparse-tree-open-archived-trees
13695 (org-hide-archived-subtrees (point-min) (point-max)))
13696 (run-hooks 'org-occur-hook)
13697 (if (org-called-interactively-p 'interactive)
13698 (message "%d match(es) for regexp %s" cnt regexp))
13699 cnt))
13701 (defun org-occur-next-match (&optional n reset)
13702 "Function for `next-error-function' to find sparse tree matches.
13703 N is the number of matches to move, when negative move backwards.
13704 RESET is entirely ignored - this function always goes back to the
13705 starting point when no match is found."
13706 (let* ((limit (if (< n 0) (point-min) (point-max)))
13707 (search-func (if (< n 0)
13708 'previous-single-char-property-change
13709 'next-single-char-property-change))
13710 (n (abs n))
13711 (pos (point))
13713 (catch 'exit
13714 (while (setq p1 (funcall search-func (point) 'org-type))
13715 (when (equal p1 limit)
13716 (goto-char pos)
13717 (error "No more matches"))
13718 (when (equal (get-char-property p1 'org-type) 'org-occur)
13719 (setq n (1- n))
13720 (when (= n 0)
13721 (goto-char p1)
13722 (throw 'exit (point))))
13723 (goto-char p1))
13724 (goto-char p1)
13725 (error "No more matches"))))
13727 (defun org-show-context (&optional key)
13728 "Make sure point and context are visible.
13729 How much context is shown depends upon the variables
13730 `org-show-hierarchy-above', `org-show-following-heading',
13731 `org-show-entry-below' and `org-show-siblings'."
13732 (let ((heading-p (org-at-heading-p t))
13733 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13734 (following-p (org-get-alist-option org-show-following-heading key))
13735 (entry-p (org-get-alist-option org-show-entry-below key))
13736 (siblings-p (org-get-alist-option org-show-siblings key)))
13737 ;; Show heading or entry text
13738 (if (and heading-p (not entry-p))
13739 (org-flag-heading nil) ; only show the heading
13740 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13741 (org-show-hidden-entry))) ; show entire entry
13742 (when following-p
13743 ;; Show next sibling, or heading below text
13744 (save-excursion
13745 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13746 (org-flag-heading nil))))
13747 (when siblings-p (org-show-siblings))
13748 (when hierarchy-p
13749 ;; show all higher headings, possibly with siblings
13750 (save-excursion
13751 (while (and (condition-case nil
13752 (progn (org-up-heading-all 1) t)
13753 (error nil))
13754 (not (bobp)))
13755 (org-flag-heading nil)
13756 (when siblings-p (org-show-siblings)))))
13757 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13759 (defvar org-reveal-start-hook nil
13760 "Hook run before revealing a location.")
13762 (defun org-reveal (&optional siblings)
13763 "Show current entry, hierarchy above it, and the following headline.
13764 This can be used to show a consistent set of context around locations
13765 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13766 not t for the search context.
13768 With optional argument SIBLINGS, on each level of the hierarchy all
13769 siblings are shown. This repairs the tree structure to what it would
13770 look like when opened with hierarchical calls to `org-cycle'.
13771 With double optional argument \\[universal-argument] \\[universal-argument], \
13772 go to the parent and show the
13773 entire tree."
13774 (interactive "P")
13775 (run-hooks 'org-reveal-start-hook)
13776 (let ((org-show-hierarchy-above t)
13777 (org-show-following-heading t)
13778 (org-show-siblings (if siblings t org-show-siblings)))
13779 (org-show-context nil))
13780 (when (equal siblings '(16))
13781 (save-excursion
13782 (when (org-up-heading-safe)
13783 (org-show-subtree)
13784 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13786 (defun org-highlight-new-match (beg end)
13787 "Highlight from BEG to END and mark the highlight is an occur headline."
13788 (let ((ov (make-overlay beg end)))
13789 (overlay-put ov 'face 'secondary-selection)
13790 (overlay-put ov 'org-type 'org-occur)
13791 (push ov org-occur-highlights)))
13793 (defun org-remove-occur-highlights (&optional beg end noremove)
13794 "Remove the occur highlights from the buffer.
13795 BEG and END are ignored. If NOREMOVE is nil, remove this function
13796 from the `before-change-functions' in the current buffer."
13797 (interactive)
13798 (unless org-inhibit-highlight-removal
13799 (mapc 'delete-overlay org-occur-highlights)
13800 (setq org-occur-highlights nil)
13801 (setq org-occur-parameters nil)
13802 (unless noremove
13803 (remove-hook 'before-change-functions
13804 'org-remove-occur-highlights 'local))))
13806 ;;;; Priorities
13808 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13809 "Regular expression matching the priority indicator.")
13811 (defvar org-remove-priority-next-time nil)
13813 (defun org-priority-up ()
13814 "Increase the priority of the current item."
13815 (interactive)
13816 (org-priority 'up))
13818 (defun org-priority-down ()
13819 "Decrease the priority of the current item."
13820 (interactive)
13821 (org-priority 'down))
13823 (defun org-priority (&optional action show)
13824 "Change the priority of an item.
13825 ACTION can be `set', `up', `down', or a character."
13826 (interactive "P")
13827 (if (equal action '(4))
13828 (org-show-priority)
13829 (unless org-enable-priority-commands
13830 (user-error "Priority commands are disabled"))
13831 (setq action (or action 'set))
13832 (let (current new news have remove)
13833 (save-excursion
13834 (org-back-to-heading t)
13835 (if (looking-at org-priority-regexp)
13836 (setq current (string-to-char (match-string 2))
13837 have t))
13838 (cond
13839 ((eq action 'remove)
13840 (setq remove t new ?\ ))
13841 ((or (eq action 'set)
13842 (if (featurep 'xemacs) (characterp action) (integerp action)))
13843 (if (not (eq action 'set))
13844 (setq new action)
13845 (message "Priority %c-%c, SPC to remove: "
13846 org-highest-priority org-lowest-priority)
13847 (save-match-data
13848 (setq new (read-char-exclusive))))
13849 (if (and (= (upcase org-highest-priority) org-highest-priority)
13850 (= (upcase org-lowest-priority) org-lowest-priority))
13851 (setq new (upcase new)))
13852 (cond ((equal new ?\ ) (setq remove t))
13853 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13854 (user-error "Priority must be between `%c' and `%c'"
13855 org-highest-priority org-lowest-priority))))
13856 ((eq action 'up)
13857 (setq new (if have
13858 (1- current) ; normal cycling
13859 ;; last priority was empty
13860 (if (eq last-command this-command)
13861 org-lowest-priority ; wrap around empty to lowest
13862 ;; default
13863 (if org-priority-start-cycle-with-default
13864 org-default-priority
13865 (1- org-default-priority))))))
13866 ((eq action 'down)
13867 (setq new (if have
13868 (1+ current) ; normal cycling
13869 ;; last priority was empty
13870 (if (eq last-command this-command)
13871 org-highest-priority ; wrap around empty to highest
13872 ;; default
13873 (if org-priority-start-cycle-with-default
13874 org-default-priority
13875 (1+ org-default-priority))))))
13876 (t (user-error "Invalid action")))
13877 (if (or (< (upcase new) org-highest-priority)
13878 (> (upcase new) org-lowest-priority))
13879 (if (and (memq action '(up down))
13880 (not have) (not (eq last-command this-command)))
13881 ;; `new' is from default priority
13882 (error
13883 "The default can not be set, see `org-default-priority' why")
13884 ;; normal cycling: `new' is beyond highest/lowest priority
13885 ;; and is wrapped around to the empty priority
13886 (setq remove t)))
13887 (setq news (format "%c" new))
13888 (if have
13889 (if remove
13890 (replace-match "" t t nil 1)
13891 (replace-match news t t nil 2))
13892 (if remove
13893 (user-error "No priority cookie found in line")
13894 (let ((case-fold-search nil))
13895 (looking-at org-todo-line-regexp))
13896 (if (match-end 2)
13897 (progn
13898 (goto-char (match-end 2))
13899 (insert " [#" news "]"))
13900 (goto-char (match-beginning 3))
13901 (insert "[#" news "] "))))
13902 (org-set-tags nil 'align))
13903 (if remove
13904 (message "Priority removed")
13905 (message "Priority of current item set to %s" news)))))
13907 (defun org-show-priority ()
13908 "Show the priority of the current item.
13909 This priority is composed of the main priority given with the [#A] cookies,
13910 and by additional input from the age of a schedules or deadline entry."
13911 (interactive)
13912 (let ((pri (if (eq major-mode 'org-agenda-mode)
13913 (org-get-at-bol 'priority)
13914 (save-excursion
13915 (save-match-data
13916 (beginning-of-line)
13917 (and (looking-at org-heading-regexp)
13918 (org-get-priority (match-string 0))))))))
13919 (message "Priority is %d" (if pri pri -1000))))
13921 (defun org-get-priority (s)
13922 "Find priority cookie and return priority."
13923 (save-match-data
13924 (if (functionp org-get-priority-function)
13925 (funcall org-get-priority-function)
13926 (if (not (string-match org-priority-regexp s))
13927 (* 1000 (- org-lowest-priority org-default-priority))
13928 (* 1000 (- org-lowest-priority
13929 (string-to-char (match-string 2 s))))))))
13931 ;;;; Tags
13933 (defvar org-agenda-archives-mode)
13934 (defvar org-map-continue-from nil
13935 "Position from where mapping should continue.
13936 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13938 (defvar org-scanner-tags nil
13939 "The current tag list while the tags scanner is running.")
13940 (defvar org-trust-scanner-tags nil
13941 "Should `org-get-tags-at' use the tags for the scanner.
13942 This is for internal dynamical scoping only.
13943 When this is non-nil, the function `org-get-tags-at' will return the value
13944 of `org-scanner-tags' instead of building the list by itself. This
13945 can lead to large speed-ups when the tags scanner is used in a file with
13946 many entries, and when the list of tags is retrieved, for example to
13947 obtain a list of properties. Building the tags list for each entry in such
13948 a file becomes an N^2 operation - but with this variable set, it scales
13949 as N.")
13951 (defun org-scan-tags (action matcher todo-only &optional start-level)
13952 "Sca headline tags with inheritance and produce output ACTION.
13954 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13955 or `agenda' to produce an entry list for an agenda view. It can also be
13956 a Lisp form or a function that should be called at each matched headline, in
13957 this case the return value is a list of all return values from these calls.
13959 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13960 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13961 only lines with a not-done TODO keyword are included in the output.
13962 This should be the same variable that was scoped into
13963 and set by `org-make-tags-matcher' when it constructed MATCHER.
13965 START-LEVEL can be a string with asterisks, reducing the scope to
13966 headlines matching this string."
13967 (require 'org-agenda)
13968 (let* ((re (concat "^"
13969 (if start-level
13970 ;; Get the correct level to match
13971 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13972 org-outline-regexp)
13973 " *\\(\\<\\("
13974 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13975 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13976 (props (list 'face 'default
13977 'done-face 'org-agenda-done
13978 'undone-face 'default
13979 'mouse-face 'highlight
13980 'org-not-done-regexp org-not-done-regexp
13981 'org-todo-regexp org-todo-regexp
13982 'org-complex-heading-regexp org-complex-heading-regexp
13983 'help-echo
13984 (format "mouse-2 or RET jump to org file %s"
13985 (abbreviate-file-name
13986 (or (buffer-file-name (buffer-base-buffer))
13987 (buffer-name (buffer-base-buffer)))))))
13988 (org-map-continue-from nil)
13989 lspos tags tags-list
13990 (tags-alist (list (cons 0 org-file-tags)))
13991 (llast 0) rtn rtn1 level category i txt
13992 todo marker entry priority)
13993 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13994 (setq action (list 'lambda nil action)))
13995 (save-excursion
13996 (goto-char (point-min))
13997 (when (eq action 'sparse-tree)
13998 (org-overview)
13999 (org-remove-occur-highlights))
14000 (while (let (case-fold-search)
14001 (re-search-forward re nil t))
14002 (setq org-map-continue-from nil)
14003 (catch :skip
14004 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
14005 tags (if (match-end 4) (org-match-string-no-properties 4)))
14006 (goto-char (setq lspos (match-beginning 0)))
14007 (setq level (org-reduced-level (org-outline-level))
14008 category (org-get-category))
14009 (setq i llast llast level)
14010 ;; remove tag lists from same and sublevels
14011 (while (>= i level)
14012 (when (setq entry (assoc i tags-alist))
14013 (setq tags-alist (delete entry tags-alist)))
14014 (setq i (1- i)))
14015 ;; add the next tags
14016 (when tags
14017 (setq tags (org-split-string tags ":")
14018 tags-alist
14019 (cons (cons level tags) tags-alist)))
14020 ;; compile tags for current headline
14021 (setq tags-list
14022 (if org-use-tag-inheritance
14023 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14024 tags)
14025 org-scanner-tags tags-list)
14026 (when org-use-tag-inheritance
14027 (setcdr (car tags-alist)
14028 (mapcar (lambda (x)
14029 (setq x (copy-sequence x))
14030 (org-add-prop-inherited x))
14031 (cdar tags-alist))))
14032 (when (and tags org-use-tag-inheritance
14033 (or (not (eq t org-use-tag-inheritance))
14034 org-tags-exclude-from-inheritance))
14035 ;; selective inheritance, remove uninherited ones
14036 (setcdr (car tags-alist)
14037 (org-remove-uninherited-tags (cdar tags-alist))))
14038 (when (and
14040 ;; eval matcher only when the todo condition is OK
14041 (and (or (not todo-only) (member todo org-not-done-keywords))
14042 (let ((case-fold-search t) (org-trust-scanner-tags t))
14043 (eval matcher)))
14045 ;; Call the skipper, but return t if it does not skip,
14046 ;; so that the `and' form continues evaluating
14047 (progn
14048 (unless (eq action 'sparse-tree) (org-agenda-skip))
14051 ;; Check if timestamps are deselecting this entry
14052 (or (not todo-only)
14053 (and (member todo org-not-done-keywords)
14054 (or (not org-agenda-tags-todo-honor-ignore-options)
14055 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14057 ;; select this headline
14058 (cond
14059 ((eq action 'sparse-tree)
14060 (and org-highlight-sparse-tree-matches
14061 (org-get-heading) (match-end 0)
14062 (org-highlight-new-match
14063 (match-beginning 1) (match-end 1)))
14064 (org-show-context 'tags-tree))
14065 ((eq action 'agenda)
14066 (setq txt (org-agenda-format-item
14068 (concat
14069 (if (eq org-tags-match-list-sublevels 'indented)
14070 (make-string (1- level) ?.) "")
14071 (org-get-heading))
14072 level category
14073 tags-list)
14074 priority (org-get-priority txt))
14075 (goto-char lspos)
14076 (setq marker (org-agenda-new-marker))
14077 (org-add-props txt props
14078 'org-marker marker 'org-hd-marker marker 'org-category category
14079 'todo-state todo
14080 'priority priority 'type "tagsmatch")
14081 (push txt rtn))
14082 ((functionp action)
14083 (setq org-map-continue-from nil)
14084 (save-excursion
14085 (setq rtn1 (funcall action))
14086 (push rtn1 rtn)))
14087 (t (user-error "Invalid action")))
14089 ;; if we are to skip sublevels, jump to end of subtree
14090 (unless org-tags-match-list-sublevels
14091 (org-end-of-subtree t)
14092 (backward-char 1))))
14093 ;; Get the correct position from where to continue
14094 (if org-map-continue-from
14095 (goto-char org-map-continue-from)
14096 (and (= (point) lspos) (end-of-line 1)))))
14097 (when (and (eq action 'sparse-tree)
14098 (not org-sparse-tree-open-archived-trees))
14099 (org-hide-archived-subtrees (point-min) (point-max)))
14100 (nreverse rtn)))
14102 (defun org-remove-uninherited-tags (tags)
14103 "Remove all tags that are not inherited from the list TAGS."
14104 (cond
14105 ((eq org-use-tag-inheritance t)
14106 (if org-tags-exclude-from-inheritance
14107 (org-delete-all org-tags-exclude-from-inheritance tags)
14108 tags))
14109 ((not org-use-tag-inheritance) nil)
14110 ((stringp org-use-tag-inheritance)
14111 (delq nil (mapcar
14112 (lambda (x)
14113 (if (and (string-match org-use-tag-inheritance x)
14114 (not (member x org-tags-exclude-from-inheritance)))
14115 x nil))
14116 tags)))
14117 ((listp org-use-tag-inheritance)
14118 (delq nil (mapcar
14119 (lambda (x)
14120 (if (member x org-use-tag-inheritance) x nil))
14121 tags)))))
14123 (defun org-match-sparse-tree (&optional todo-only match)
14124 "Create a sparse tree according to tags string MATCH.
14125 MATCH can contain positive and negative selection of tags, like
14126 \"+WORK+URGENT-WITHBOSS\".
14127 If optional argument TODO-ONLY is non-nil, only select lines that are
14128 also TODO lines."
14129 (interactive "P")
14130 (org-agenda-prepare-buffers (list (current-buffer)))
14131 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
14133 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14135 (defvar org-cached-props nil)
14136 (defun org-cached-entry-get (pom property)
14137 (if (or (eq t org-use-property-inheritance)
14138 (and (stringp org-use-property-inheritance)
14139 (string-match org-use-property-inheritance property))
14140 (and (listp org-use-property-inheritance)
14141 (member property org-use-property-inheritance)))
14142 ;; Caching is not possible, check it directly
14143 (org-entry-get pom property 'inherit)
14144 ;; Get all properties, so that we can do complicated checks easily
14145 (cdr (assoc property (or org-cached-props
14146 (setq org-cached-props
14147 (org-entry-properties pom)))))))
14149 (defun org-global-tags-completion-table (&optional files)
14150 "Return the list of all tags in all agenda buffer/files.
14151 Optional FILES argument is a list of files which can be used
14152 instead of the agenda files."
14153 (save-excursion
14154 (org-uniquify
14155 (delq nil
14156 (apply 'append
14157 (mapcar
14158 (lambda (file)
14159 (set-buffer (find-file-noselect file))
14160 (append (org-get-buffer-tags)
14161 (mapcar (lambda (x) (if (stringp (car-safe x))
14162 (list (car-safe x)) nil))
14163 org-tag-alist)))
14164 (if (and files (car files))
14165 files
14166 (org-agenda-files))))))))
14168 (defun org-make-tags-matcher (match)
14169 "Create the TAGS/TODO matcher form for the selection string MATCH.
14171 The variable `todo-only' is scoped dynamically into this function.
14172 It will be set to t if the matcher restricts matching to TODO entries,
14173 otherwise will not be touched.
14175 Returns a cons of the selection string MATCH and the constructed
14176 lisp form implementing the matcher. The matcher is to be evaluated
14177 at an Org entry, with point on the headline, and returns t if the
14178 entry matches the selection string MATCH. The returned lisp form
14179 references two variables with information about the entry, which
14180 must be bound around the form's evaluation: todo, the TODO keyword
14181 at the entry (or nil of none); and tags-list, the list of all tags
14182 at the entry including inherited ones. Additionally, the category
14183 of the entry (if any) must be specified as the text property
14184 'org-category on the headline.
14186 See also `org-scan-tags'.
14188 (declare (special todo-only))
14189 (unless (boundp 'todo-only)
14190 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14191 (unless match
14192 ;; Get a new match request, with completion against the global
14193 ;; tags table and the local tags in current buffer
14194 (let ((org-last-tags-completion-table
14195 (org-uniquify
14196 (delq nil (append (org-get-buffer-tags)
14197 (org-global-tags-completion-table))))))
14198 (setq match (org-completing-read-no-i
14199 "Match: " 'org-tags-completion-function nil nil nil
14200 'org-tags-history))))
14202 ;; Parse the string and create a lisp form
14203 (let ((match0 match)
14204 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14205 minus tag mm
14206 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14207 orterms term orlist re-p str-p level-p level-op time-p
14208 prop-p pn pv po gv rest (start 0) (ss 0))
14209 ;; Expand group tags
14210 (setq match (org-tags-expand match))
14212 ;; Check if there is a TODO part of this match, which would be the
14213 ;; part after a "/". TO make sure that this slash is not part of
14214 ;; a property value to be matched against, we also check that there
14215 ;; is no " after that slash.
14216 ;; First, find the last slash
14217 (while (string-match "/+" match ss)
14218 (setq start (match-beginning 0) ss (match-end 0)))
14219 (if (and (string-match "/+" match start)
14220 (not (save-match-data (string-match "\"" match start))))
14221 ;; match contains also a todo-matching request
14222 (progn
14223 (setq tagsmatch (substring match 0 (match-beginning 0))
14224 todomatch (substring match (match-end 0)))
14225 (if (string-match "^!" todomatch)
14226 (setq todo-only t todomatch (substring todomatch 1)))
14227 (if (string-match "^\\s-*$" todomatch)
14228 (setq todomatch nil)))
14229 ;; only matching tags
14230 (setq tagsmatch match todomatch nil))
14232 ;; Make the tags matcher
14233 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14234 (setq tagsmatcher t)
14235 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14236 (while (setq term (pop orterms))
14237 (while (and (equal (substring term -1) "\\") orterms)
14238 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14239 (while (string-match re term)
14240 (setq rest (substring term (match-end 0))
14241 minus (and (match-end 1)
14242 (equal (match-string 1 term) "-"))
14243 tag (save-match-data (replace-regexp-in-string
14244 "\\\\-" "-"
14245 (match-string 2 term)))
14246 re-p (equal (string-to-char tag) ?{)
14247 level-p (match-end 4)
14248 prop-p (match-end 5)
14249 mm (cond
14250 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14251 (level-p
14252 (setq level-op (org-op-to-function (match-string 3 term)))
14253 `(,level-op level ,(string-to-number
14254 (match-string 4 term))))
14255 (prop-p
14256 (setq pn (match-string 5 term)
14257 po (match-string 6 term)
14258 pv (match-string 7 term)
14259 re-p (equal (string-to-char pv) ?{)
14260 str-p (equal (string-to-char pv) ?\")
14261 time-p (save-match-data
14262 (string-match "^\"[[<].*[]>]\"$" pv))
14263 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14264 (if time-p (setq pv (org-matcher-time pv)))
14265 (setq po (org-op-to-function po (if time-p 'time str-p)))
14266 (cond
14267 ((equal pn "CATEGORY")
14268 (setq gv '(get-text-property (point) 'org-category)))
14269 ((equal pn "TODO")
14270 (setq gv 'todo))
14272 (setq gv `(org-cached-entry-get nil ,pn))))
14273 (if re-p
14274 (if (eq po 'org<>)
14275 `(not (string-match ,pv (or ,gv "")))
14276 `(string-match ,pv (or ,gv "")))
14277 (if str-p
14278 `(,po (or ,gv "") ,pv)
14279 `(,po (string-to-number (or ,gv ""))
14280 ,(string-to-number pv) ))))
14281 (t `(member ,tag tags-list)))
14282 mm (if minus (list 'not mm) mm)
14283 term rest)
14284 (push mm tagsmatcher))
14285 (push (if (> (length tagsmatcher) 1)
14286 (cons 'and tagsmatcher)
14287 (car tagsmatcher))
14288 orlist)
14289 (setq tagsmatcher nil))
14290 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14291 (setq tagsmatcher
14292 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14293 ;; Make the todo matcher
14294 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14295 (setq todomatcher t)
14296 (setq orterms (org-split-string todomatch "|") orlist nil)
14297 (while (setq term (pop orterms))
14298 (while (string-match re term)
14299 (setq minus (and (match-end 1)
14300 (equal (match-string 1 term) "-"))
14301 kwd (match-string 2 term)
14302 re-p (equal (string-to-char kwd) ?{)
14303 term (substring term (match-end 0))
14304 mm (if re-p
14305 `(string-match ,(substring kwd 1 -1) todo)
14306 (list 'equal 'todo kwd))
14307 mm (if minus (list 'not mm) mm))
14308 (push mm todomatcher))
14309 (push (if (> (length todomatcher) 1)
14310 (cons 'and todomatcher)
14311 (car todomatcher))
14312 orlist)
14313 (setq todomatcher nil))
14314 (setq todomatcher (if (> (length orlist) 1)
14315 (cons 'or orlist) (car orlist))))
14317 ;; Return the string and lisp forms of the matcher
14318 (setq matcher (if todomatcher
14319 (list 'and tagsmatcher todomatcher)
14320 tagsmatcher))
14321 (when todo-only
14322 (setq matcher (list 'and '(member todo org-not-done-keywords)
14323 matcher)))
14324 (cons match0 matcher)))
14326 (defun org-tags-expand (match &optional single-as-list downcased)
14327 "Expand group tags in MATCH.
14329 This replaces every group tag in MATCH with a regexp tag search.
14330 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14331 will be replaced like this:
14333 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14334 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14335 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14337 Replacing by a regexp preserves the structure of the match.
14338 E.g., this expansion
14340 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14342 will match anything tagged with \"Lab\" and \"Home\", or tagged
14343 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14345 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14346 assumed to be a single group tag, and the function will return
14347 the list of tags in this group.
14349 When DOWNCASE is non-nil, expand downcased TAGS."
14350 (if org-group-tags
14351 (let* ((case-fold-search t)
14352 (stable org-mode-syntax-table)
14353 (tal (or org-tag-groups-alist-for-agenda
14354 org-tag-groups-alist))
14355 (tal (if downcased
14356 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14357 (tml (mapcar 'car tal))
14358 (rtnmatch match) rpl)
14359 ;; @ and _ are allowed as word-components in tags
14360 (modify-syntax-entry ?@ "w" stable)
14361 (modify-syntax-entry ?_ "w" stable)
14362 (while (and tml
14363 (with-syntax-table stable
14364 (string-match
14365 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14366 (regexp-opt tml) "\\>\\)") rtnmatch)))
14367 (let* ((dir (match-string 1 rtnmatch))
14368 (tag (match-string 2 rtnmatch))
14369 (tag (if downcased (downcase tag) tag)))
14370 (setq tml (delete tag tml))
14371 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14372 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14373 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14374 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14375 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14376 (if single-as-list
14377 (or (reverse rpl) (list rtnmatch))
14378 rtnmatch))
14379 (if single-as-list (list (if downcased (downcase match) match))
14380 match)))
14382 (defun org-op-to-function (op &optional stringp)
14383 "Turn an operator into the appropriate function."
14384 (setq op
14385 (cond
14386 ((equal op "<" ) '(< string< org-time<))
14387 ((equal op ">" ) '(> org-string> org-time>))
14388 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14389 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14390 ((member op '("=" "==")) '(= string= org-time=))
14391 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14392 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14394 (defun org<> (a b) (not (= a b)))
14395 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14396 (defun org-string>= (a b) (not (string< a b)))
14397 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14398 (defun org-string<> (a b) (not (string= a b)))
14399 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14400 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14401 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14402 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14403 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14404 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14405 (defun org-2ft (s)
14406 "Convert S to a floating point time.
14407 If S is already a number, just return it. If it is a string, parse
14408 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14409 (cond
14410 ((numberp s) s)
14411 ((stringp s)
14412 (condition-case nil
14413 (float-time (apply 'encode-time (org-parse-time-string s)))
14414 (error 0.)))
14415 (t 0.)))
14417 (defun org-time-today ()
14418 "Time in seconds today at 0:00.
14419 Returns the float number of seconds since the beginning of the
14420 epoch to the beginning of today (00:00)."
14421 (float-time (apply 'encode-time
14422 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14424 (defun org-matcher-time (s)
14425 "Interpret a time comparison value."
14426 (save-match-data
14427 (cond
14428 ((string= s "<now>") (float-time))
14429 ((string= s "<today>") (org-time-today))
14430 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14431 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14432 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14433 (+ (org-time-today)
14434 (* (string-to-number (match-string 1 s))
14435 (cdr (assoc (match-string 2 s)
14436 '(("d" . 86400.0) ("w" . 604800.0)
14437 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14438 (t (org-2ft s)))))
14440 (defun org-match-any-p (re list)
14441 "Does re match any element of list?"
14442 (setq list (mapcar (lambda (x) (string-match re x)) list))
14443 (delq nil list))
14445 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14446 (defvar org-tags-overlay (make-overlay 1 1))
14447 (org-detach-overlay org-tags-overlay)
14449 (defun org-get-local-tags-at (&optional pos)
14450 "Get a list of tags defined in the current headline."
14451 (org-get-tags-at pos 'local))
14453 (defun org-get-local-tags ()
14454 "Get a list of tags defined in the current headline."
14455 (org-get-tags-at nil 'local))
14457 (defun org-get-tags-at (&optional pos local)
14458 "Get a list of all headline tags applicable at POS.
14459 POS defaults to point. If tags are inherited, the list contains
14460 the targets in the same sequence as the headlines appear, i.e.
14461 the tags of the current headline come last.
14462 When LOCAL is non-nil, only return tags from the current headline,
14463 ignore inherited ones."
14464 (interactive)
14465 (if (and org-trust-scanner-tags
14466 (or (not pos) (equal pos (point)))
14467 (not local))
14468 org-scanner-tags
14469 (let (tags ltags lastpos parent)
14470 (save-excursion
14471 (save-restriction
14472 (widen)
14473 (goto-char (or pos (point)))
14474 (save-match-data
14475 (catch 'done
14476 (condition-case nil
14477 (progn
14478 (org-back-to-heading t)
14479 (while (not (equal lastpos (point)))
14480 (setq lastpos (point))
14481 (when (looking-at
14482 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14483 (setq ltags (org-split-string
14484 (org-match-string-no-properties 1) ":"))
14485 (when parent
14486 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14487 (setq tags (append
14488 (if parent
14489 (org-remove-uninherited-tags ltags)
14490 ltags)
14491 tags)))
14492 (or org-use-tag-inheritance (throw 'done t))
14493 (if local (throw 'done t))
14494 (or (org-up-heading-safe) (error nil))
14495 (setq parent t)))
14496 (error nil)))))
14497 (if local
14498 tags
14499 (reverse (delete-dups
14500 (reverse (append
14501 (org-remove-uninherited-tags
14502 org-file-tags) tags)))))))))
14504 (defun org-add-prop-inherited (s)
14505 (add-text-properties 0 (length s) '(inherited t) s)
14508 (defun org-toggle-tag (tag &optional onoff)
14509 "Toggle the tag TAG for the current line.
14510 If ONOFF is `on' or `off', don't toggle but set to this state."
14511 (let (res current)
14512 (save-excursion
14513 (org-back-to-heading t)
14514 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14515 (point-at-eol) t)
14516 (progn
14517 (setq current (match-string 1))
14518 (replace-match ""))
14519 (setq current ""))
14520 (setq current (nreverse (org-split-string current ":")))
14521 (cond
14522 ((eq onoff 'on)
14523 (setq res t)
14524 (or (member tag current) (push tag current)))
14525 ((eq onoff 'off)
14526 (or (not (member tag current)) (setq current (delete tag current))))
14527 (t (if (member tag current)
14528 (setq current (delete tag current))
14529 (setq res t)
14530 (push tag current))))
14531 (end-of-line 1)
14532 (if current
14533 (progn
14534 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14535 (org-set-tags nil t))
14536 (delete-horizontal-space))
14537 (run-hooks 'org-after-tags-change-hook))
14538 res))
14540 (defun org-align-tags-here (to-col)
14541 ;; Assumes that this is a headline
14542 "Align tags on the current headline to TO-COL."
14543 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14544 (beginning-of-line 1)
14545 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14546 (< pos (match-beginning 2)))
14547 (progn
14548 (setq tags-l (- (match-end 2) (match-beginning 2)))
14549 (goto-char (match-beginning 1))
14550 (insert " ")
14551 (delete-region (point) (1+ (match-beginning 2)))
14552 (setq ncol (max (current-column)
14553 (1+ col)
14554 (if (> to-col 0)
14555 to-col
14556 (- (abs to-col) tags-l))))
14557 (setq p (point))
14558 (insert (make-string (- ncol (current-column)) ?\ ))
14559 (setq ncol (current-column))
14560 (when indent-tabs-mode (tabify p (point-at-eol)))
14561 (org-move-to-column (min ncol col)))
14562 (goto-char pos))))
14564 (defun org-set-tags-command (&optional arg just-align)
14565 "Call the set-tags command for the current entry."
14566 (interactive "P")
14567 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14568 (org-set-tags arg just-align)
14569 (save-excursion
14570 (unless (and (org-region-active-p)
14571 org-loop-over-headlines-in-active-region)
14572 (org-back-to-heading t))
14573 (org-set-tags arg just-align))))
14575 (defun org-set-tags-to (data)
14576 "Set the tags of the current entry to DATA, replacing the current tags.
14577 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14578 If DATA is nil or the empty string, any tags will be removed."
14579 (interactive "sTags: ")
14580 (setq data
14581 (cond
14582 ((eq data nil) "")
14583 ((equal data "") "")
14584 ((stringp data)
14585 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14586 ":"))
14587 ((listp data)
14588 (concat ":" (mapconcat 'identity data ":") ":"))))
14589 (when data
14590 (save-excursion
14591 (org-back-to-heading t)
14592 (when (looking-at org-complex-heading-regexp)
14593 (if (match-end 5)
14594 (progn
14595 (goto-char (match-beginning 5))
14596 (insert data)
14597 (delete-region (point) (point-at-eol))
14598 (org-set-tags nil 'align))
14599 (goto-char (point-at-eol))
14600 (insert " " data)
14601 (org-set-tags nil 'align)))
14602 (beginning-of-line 1)
14603 (if (looking-at ".*?\\([ \t]+\\)$")
14604 (delete-region (match-beginning 1) (match-end 1))))))
14606 (defun org-align-all-tags ()
14607 "Align the tags i all headings."
14608 (interactive)
14609 (save-excursion
14610 (or (ignore-errors (org-back-to-heading t))
14611 (outline-next-heading))
14612 (if (org-at-heading-p)
14613 (org-set-tags t)
14614 (message "No headings"))))
14616 (defvar org-indent-indentation-per-level)
14617 (defun org-set-tags (&optional arg just-align)
14618 "Set the tags for the current headline.
14619 With prefix ARG, realign all tags in headings in the current buffer.
14620 When JUST-ALIGN is non-nil, only align tags."
14621 (interactive "P")
14622 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14623 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14624 'region-start-level 'region))
14625 org-loop-over-headlines-in-active-region)
14626 (org-map-entries
14627 ;; We don't use ARG and JUST-ALIGN here because these args
14628 ;; are not useful when looping over headlines.
14629 `(org-set-tags)
14630 org-loop-over-headlines-in-active-region
14631 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14632 (let* ((re org-outline-regexp-bol)
14633 (current (unless arg (org-get-tags-string)))
14634 (col (current-column))
14635 (org-setting-tags t)
14636 table current-tags inherited-tags ; computed below when needed
14637 tags p0 c0 c1 rpl di tc level)
14638 (if arg
14639 (save-excursion
14640 (goto-char (point-min))
14641 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14642 (while (re-search-forward re nil t)
14643 (org-set-tags nil t)
14644 (end-of-line 1)))
14645 (message "All tags realigned to column %d" org-tags-column))
14646 (if just-align
14647 (setq tags current)
14648 ;; Get a new set of tags from the user
14649 (save-excursion
14650 (setq table (append org-tag-persistent-alist
14651 (or org-tag-alist (org-get-buffer-tags))
14652 (and
14653 org-complete-tags-always-offer-all-agenda-tags
14654 (org-global-tags-completion-table
14655 (org-agenda-files))))
14656 org-last-tags-completion-table table
14657 current-tags (org-split-string current ":")
14658 inherited-tags (nreverse
14659 (nthcdr (length current-tags)
14660 (nreverse (org-get-tags-at))))
14661 tags
14662 (if (or (eq t org-use-fast-tag-selection)
14663 (and org-use-fast-tag-selection
14664 (delq nil (mapcar 'cdr table))))
14665 (org-fast-tag-selection
14666 current-tags inherited-tags table
14667 (if org-fast-tag-selection-include-todo
14668 org-todo-key-alist))
14669 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14670 (org-trim
14671 (org-icompleting-read "Tags: "
14672 'org-tags-completion-function
14673 nil nil current 'org-tags-history))))))
14674 (while (string-match "[-+&]+" tags)
14675 ;; No boolean logic, just a list
14676 (setq tags (replace-match ":" t t tags))))
14678 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14680 (if org-tags-sort-function
14681 (setq tags (mapconcat 'identity
14682 (sort (org-split-string
14683 tags (org-re "[^[:alnum:]_@#%]+"))
14684 org-tags-sort-function) ":")))
14686 (if (string-match "\\`[\t ]*\\'" tags)
14687 (setq tags "")
14688 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14689 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14691 ;; Insert new tags at the correct column
14692 (beginning-of-line 1)
14693 (setq level (or (and (looking-at org-outline-regexp)
14694 (- (match-end 0) (point) 1))
14696 (cond
14697 ((and (equal current "") (equal tags "")))
14698 ((re-search-forward
14699 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14700 (point-at-eol) t)
14701 (if (equal tags "")
14702 (setq rpl "")
14703 (goto-char (match-beginning 0))
14704 (setq c0 (current-column)
14705 ;; compute offset for the case of org-indent-mode active
14706 di (if (org-bound-and-true-p org-indent-mode)
14707 (* (1- org-indent-indentation-per-level) (1- level))
14709 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14710 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14711 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (string-width tags))))
14712 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14713 (replace-match rpl t t)
14714 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14715 tags)
14716 (t (error "Tags alignment failed")))
14717 (org-move-to-column col)
14718 (unless just-align
14719 (run-hooks 'org-after-tags-change-hook))))))
14721 (defun org-change-tag-in-region (beg end tag off)
14722 "Add or remove TAG for each entry in the region.
14723 This works in the agenda, and also in an org-mode buffer."
14724 (interactive
14725 (list (region-beginning) (region-end)
14726 (let ((org-last-tags-completion-table
14727 (if (derived-mode-p 'org-mode)
14728 (org-uniquify
14729 (delq nil (append (org-get-buffer-tags)
14730 (org-global-tags-completion-table))))
14731 (org-global-tags-completion-table))))
14732 (org-icompleting-read
14733 "Tag: " 'org-tags-completion-function nil nil nil
14734 'org-tags-history))
14735 (progn
14736 (message "[s]et or [r]emove? ")
14737 (equal (read-char-exclusive) ?r))))
14738 (if (fboundp 'deactivate-mark) (deactivate-mark))
14739 (let ((agendap (equal major-mode 'org-agenda-mode))
14740 l1 l2 m buf pos newhead (cnt 0))
14741 (goto-char end)
14742 (setq l2 (1- (org-current-line)))
14743 (goto-char beg)
14744 (setq l1 (org-current-line))
14745 (loop for l from l1 to l2 do
14746 (org-goto-line l)
14747 (setq m (get-text-property (point) 'org-hd-marker))
14748 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14749 (and agendap m))
14750 (setq buf (if agendap (marker-buffer m) (current-buffer))
14751 pos (if agendap m (point)))
14752 (with-current-buffer buf
14753 (save-excursion
14754 (save-restriction
14755 (goto-char pos)
14756 (setq cnt (1+ cnt))
14757 (org-toggle-tag tag (if off 'off 'on))
14758 (setq newhead (org-get-heading)))))
14759 (and agendap (org-agenda-change-all-lines newhead m))))
14760 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14762 (defun org-tags-completion-function (string predicate &optional flag)
14763 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14764 (confirm (lambda (x) (stringp (car x)))))
14765 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14766 (setq s1 (match-string 1 string)
14767 s2 (match-string 2 string))
14768 (setq s1 "" s2 string))
14769 (cond
14770 ((eq flag nil)
14771 ;; try completion
14772 (setq rtn (try-completion s2 ctable confirm))
14773 (if (stringp rtn)
14774 (setq rtn
14775 (concat s1 s2 (substring rtn (length s2))
14776 (if (and org-add-colon-after-tag-completion
14777 (assoc rtn ctable))
14778 ":" ""))))
14779 rtn)
14780 ((eq flag t)
14781 ;; all-completions
14782 (all-completions s2 ctable confirm))
14783 ((eq flag 'lambda)
14784 ;; exact match?
14785 (assoc s2 ctable)))))
14787 (defun org-fast-tag-insert (kwd tags face &optional end)
14788 "Insert KDW, and the TAGS, the latter with face FACE.
14789 Also insert END."
14790 (insert (format "%-12s" (concat kwd ":"))
14791 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14792 (or end "")))
14794 (defun org-fast-tag-show-exit (flag)
14795 (save-excursion
14796 (org-goto-line 3)
14797 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14798 (replace-match ""))
14799 (when flag
14800 (end-of-line 1)
14801 (org-move-to-column (- (window-width) 19) t)
14802 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14804 (defun org-set-current-tags-overlay (current prefix)
14805 "Add an overlay to CURRENT tag with PREFIX."
14806 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14807 (if (featurep 'xemacs)
14808 (org-overlay-display org-tags-overlay (concat prefix s)
14809 'secondary-selection)
14810 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14811 (org-overlay-display org-tags-overlay (concat prefix s)))))
14813 (defvar org-last-tag-selection-key nil)
14814 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14815 "Fast tag selection with single keys.
14816 CURRENT is the current list of tags in the headline, INHERITED is the
14817 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14818 possibly with grouping information. TODO-TABLE is a similar table with
14819 TODO keywords, should these have keys assigned to them.
14820 If the keys are nil, a-z are automatically assigned.
14821 Returns the new tags string, or nil to not change the current settings."
14822 (let* ((fulltable (append table todo-table))
14823 (maxlen (apply 'max (mapcar
14824 (lambda (x)
14825 (if (stringp (car x)) (string-width (car x)) 0))
14826 fulltable)))
14827 (buf (current-buffer))
14828 (expert (eq org-fast-tag-selection-single-key 'expert))
14829 (buffer-tags nil)
14830 (fwidth (+ maxlen 3 1 3))
14831 (ncol (/ (- (window-width) 4) fwidth))
14832 (i-face 'org-done)
14833 (c-face 'org-todo)
14834 tg cnt e c char c1 c2 ntable tbl rtn
14835 ov-start ov-end ov-prefix
14836 (exit-after-next org-fast-tag-selection-single-key)
14837 (done-keywords org-done-keywords)
14838 groups ingroup)
14839 (save-excursion
14840 (beginning-of-line 1)
14841 (if (looking-at
14842 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14843 (setq ov-start (match-beginning 1)
14844 ov-end (match-end 1)
14845 ov-prefix "")
14846 (setq ov-start (1- (point-at-eol))
14847 ov-end (1+ ov-start))
14848 (skip-chars-forward "^\n\r")
14849 (setq ov-prefix
14850 (concat
14851 (buffer-substring (1- (point)) (point))
14852 (if (> (current-column) org-tags-column)
14854 (make-string (- org-tags-column (current-column)) ?\ ))))))
14855 (move-overlay org-tags-overlay ov-start ov-end)
14856 (save-window-excursion
14857 (if expert
14858 (set-buffer (get-buffer-create " *Org tags*"))
14859 (delete-other-windows)
14860 (split-window-vertically)
14861 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14862 (erase-buffer)
14863 (org-set-local 'org-done-keywords done-keywords)
14864 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14865 (org-fast-tag-insert "Current" current c-face "\n\n")
14866 (org-fast-tag-show-exit exit-after-next)
14867 (org-set-current-tags-overlay current ov-prefix)
14868 (setq tbl fulltable char ?a cnt 0)
14869 (while (setq e (pop tbl))
14870 (cond
14871 ((equal (car e) :startgroup)
14872 (push '() groups) (setq ingroup t)
14873 (when (not (= cnt 0))
14874 (setq cnt 0)
14875 (insert "\n"))
14876 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14877 ((equal (car e) :endgroup)
14878 (setq ingroup nil cnt 0)
14879 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14880 ((equal e '(:newline))
14881 (when (not (= cnt 0))
14882 (setq cnt 0)
14883 (insert "\n")
14884 (setq e (car tbl))
14885 (while (equal (car tbl) '(:newline))
14886 (insert "\n")
14887 (setq tbl (cdr tbl)))))
14888 ((equal e '(:grouptags)) nil)
14890 (setq tg (copy-sequence (car e)) c2 nil)
14891 (if (cdr e)
14892 (setq c (cdr e))
14893 ;; automatically assign a character.
14894 (setq c1 (string-to-char
14895 (downcase (substring
14896 tg (if (= (string-to-char tg) ?@) 1 0)))))
14897 (if (or (rassoc c1 ntable) (rassoc c1 table))
14898 (while (or (rassoc char ntable) (rassoc char table))
14899 (setq char (1+ char)))
14900 (setq c2 c1))
14901 (setq c (or c2 char)))
14902 (if ingroup (push tg (car groups)))
14903 (setq tg (org-add-props tg nil 'face
14904 (cond
14905 ((not (assoc tg table))
14906 (org-get-todo-face tg))
14907 ((member tg current) c-face)
14908 ((member tg inherited) i-face))))
14909 (if (equal (caar tbl) :grouptags)
14910 (org-add-props tg nil 'face 'org-tag-group))
14911 (if (and (= cnt 0) (not ingroup)) (insert " "))
14912 (insert "[" c "] " tg (make-string
14913 (- fwidth 4 (length tg)) ?\ ))
14914 (push (cons tg c) ntable)
14915 (when (= (setq cnt (1+ cnt)) ncol)
14916 (insert "\n")
14917 (if ingroup (insert " "))
14918 (setq cnt 0)))))
14919 (setq ntable (nreverse ntable))
14920 (insert "\n")
14921 (goto-char (point-min))
14922 (if (not expert) (org-fit-window-to-buffer))
14923 (setq rtn
14924 (catch 'exit
14925 (while t
14926 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14927 (if (not groups) "no " "")
14928 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14929 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14930 (setq org-last-tag-selection-key c)
14931 (cond
14932 ((= c ?\r) (throw 'exit t))
14933 ((= c ?!)
14934 (setq groups (not groups))
14935 (goto-char (point-min))
14936 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14937 ((= c ?\C-c)
14938 (if (not expert)
14939 (org-fast-tag-show-exit
14940 (setq exit-after-next (not exit-after-next)))
14941 (setq expert nil)
14942 (delete-other-windows)
14943 (set-window-buffer (split-window-vertically) " *Org tags*")
14944 (org-switch-to-buffer-other-window " *Org tags*")
14945 (org-fit-window-to-buffer)))
14946 ((or (= c ?\C-g)
14947 (and (= c ?q) (not (rassoc c ntable))))
14948 (org-detach-overlay org-tags-overlay)
14949 (setq quit-flag t))
14950 ((= c ?\ )
14951 (setq current nil)
14952 (if exit-after-next (setq exit-after-next 'now)))
14953 ((= c ?\t)
14954 (condition-case nil
14955 (setq tg (org-icompleting-read
14956 "Tag: "
14957 (or buffer-tags
14958 (with-current-buffer buf
14959 (org-get-buffer-tags)))))
14960 (quit (setq tg "")))
14961 (when (string-match "\\S-" tg)
14962 (add-to-list 'buffer-tags (list tg))
14963 (if (member tg current)
14964 (setq current (delete tg current))
14965 (push tg current)))
14966 (if exit-after-next (setq exit-after-next 'now)))
14967 ((setq e (rassoc c todo-table) tg (car e))
14968 (with-current-buffer buf
14969 (save-excursion (org-todo tg)))
14970 (if exit-after-next (setq exit-after-next 'now)))
14971 ((setq e (rassoc c ntable) tg (car e))
14972 (if (member tg current)
14973 (setq current (delete tg current))
14974 (loop for g in groups do
14975 (if (member tg g)
14976 (mapc (lambda (x)
14977 (setq current (delete x current)))
14978 g)))
14979 (push tg current))
14980 (if exit-after-next (setq exit-after-next 'now))))
14982 ;; Create a sorted list
14983 (setq current
14984 (sort current
14985 (lambda (a b)
14986 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14987 (if (eq exit-after-next 'now) (throw 'exit t))
14988 (goto-char (point-min))
14989 (beginning-of-line 2)
14990 (delete-region (point) (point-at-eol))
14991 (org-fast-tag-insert "Current" current c-face)
14992 (org-set-current-tags-overlay current ov-prefix)
14993 (while (re-search-forward
14994 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14995 (setq tg (match-string 1))
14996 (add-text-properties
14997 (match-beginning 1) (match-end 1)
14998 (list 'face
14999 (cond
15000 ((member tg current) c-face)
15001 ((member tg inherited) i-face)
15002 (t (get-text-property (match-beginning 1) 'face))))))
15003 (goto-char (point-min)))))
15004 (org-detach-overlay org-tags-overlay)
15005 (if rtn
15006 (mapconcat 'identity current ":")
15007 nil))))
15009 (defun org-get-tags-string ()
15010 "Get the TAGS string in the current headline."
15011 (unless (org-at-heading-p t)
15012 (user-error "Not on a heading"))
15013 (save-excursion
15014 (beginning-of-line 1)
15015 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
15016 (org-match-string-no-properties 1)
15017 "")))
15019 (defun org-get-tags ()
15020 "Get the list of tags specified in the current headline."
15021 (org-split-string (org-get-tags-string) ":"))
15023 (defun org-get-buffer-tags ()
15024 "Get a table of all tags used in the buffer, for completion."
15025 (let (tags)
15026 (save-excursion
15027 (goto-char (point-min))
15028 (while (re-search-forward
15029 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
15030 (when (equal (char-after (point-at-bol 0)) ?*)
15031 (mapc (lambda (x) (add-to-list 'tags x))
15032 (org-split-string (org-match-string-no-properties 1) ":")))))
15033 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
15034 (mapcar 'list tags)))
15036 ;;;; The mapping API
15038 (defun org-map-entries (func &optional match scope &rest skip)
15039 "Call FUNC at each headline selected by MATCH in SCOPE.
15041 FUNC is a function or a lisp form. The function will be called without
15042 arguments, with the cursor positioned at the beginning of the headline.
15043 The return values of all calls to the function will be collected and
15044 returned as a list.
15046 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15047 does not need to preserve point. After evaluation, the cursor will be
15048 moved to the end of the line (presumably of the headline of the
15049 processed entry) and search continues from there. Under some
15050 circumstances, this may not produce the wanted results. For example,
15051 if you have removed (e.g. archived) the current (sub)tree it could
15052 mean that the next entry will be skipped entirely. In such cases, you
15053 can specify the position from where search should continue by making
15054 FUNC set the variable `org-map-continue-from' to the desired buffer
15055 position.
15057 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15058 Only headlines that are matched by this query will be considered during
15059 the iteration. When MATCH is nil or t, all headlines will be
15060 visited by the iteration.
15062 SCOPE determines the scope of this command. It can be any of:
15064 nil The current buffer, respecting the restriction if any
15065 tree The subtree started with the entry at point
15066 region The entries within the active region, if any
15067 region-start-level
15068 The entries within the active region, but only those at
15069 the same level than the first one.
15070 file The current buffer, without restriction
15071 file-with-archives
15072 The current buffer, and any archives associated with it
15073 agenda All agenda files
15074 agenda-with-archives
15075 All agenda files with any archive files associated with them
15076 \(file1 file2 ...)
15077 If this is a list, all files in the list will be scanned
15079 The remaining args are treated as settings for the skipping facilities of
15080 the scanner. The following items can be given here:
15082 archive skip trees with the archive tag
15083 comment skip trees with the COMMENT keyword
15084 function or Emacs Lisp form:
15085 will be used as value for `org-agenda-skip-function', so
15086 whenever the function returns a position, FUNC will not be
15087 called for that entry and search will continue from the
15088 position returned
15090 If your function needs to retrieve the tags including inherited tags
15091 at the *current* entry, you can use the value of the variable
15092 `org-scanner-tags' which will be much faster than getting the value
15093 with `org-get-tags-at'. If your function gets properties with
15094 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15095 to t around the call to `org-entry-properties' to get the same speedup.
15096 Note that if your function moves around to retrieve tags and properties at
15097 a *different* entry, you cannot use these techniques."
15098 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15099 (not (org-region-active-p)))
15100 (let* ((org-agenda-archives-mode nil) ; just to make sure
15101 (org-agenda-skip-archived-trees (memq 'archive skip))
15102 (org-agenda-skip-comment-trees (memq 'comment skip))
15103 (org-agenda-skip-function
15104 (car (org-delete-all '(comment archive) skip)))
15105 (org-tags-match-list-sublevels t)
15106 (start-level (eq scope 'region-start-level))
15107 matcher file res
15108 org-todo-keywords-for-agenda
15109 org-done-keywords-for-agenda
15110 org-todo-keyword-alist-for-agenda
15111 org-tag-alist-for-agenda
15112 todo-only)
15114 (cond
15115 ((eq match t) (setq matcher t))
15116 ((eq match nil) (setq matcher t))
15117 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15119 (save-excursion
15120 (save-restriction
15121 (cond ((eq scope 'tree)
15122 (org-back-to-heading t)
15123 (org-narrow-to-subtree)
15124 (setq scope nil))
15125 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15126 (org-region-active-p))
15127 ;; If needed, set start-level to a string like "2"
15128 (when start-level
15129 (save-excursion
15130 (goto-char (region-beginning))
15131 (unless (org-at-heading-p) (outline-next-heading))
15132 (setq start-level (org-current-level))))
15133 (narrow-to-region (region-beginning)
15134 (save-excursion
15135 (goto-char (region-end))
15136 (unless (and (bolp) (org-at-heading-p))
15137 (outline-next-heading))
15138 (point)))
15139 (setq scope nil)))
15141 (if (not scope)
15142 (progn
15143 (org-agenda-prepare-buffers
15144 (list (buffer-file-name (current-buffer))))
15145 (setq res (org-scan-tags func matcher todo-only start-level)))
15146 ;; Get the right scope
15147 (cond
15148 ((and scope (listp scope) (symbolp (car scope)))
15149 (setq scope (eval scope)))
15150 ((eq scope 'agenda)
15151 (setq scope (org-agenda-files t)))
15152 ((eq scope 'agenda-with-archives)
15153 (setq scope (org-agenda-files t))
15154 (setq scope (org-add-archive-files scope)))
15155 ((eq scope 'file)
15156 (setq scope (list (buffer-file-name))))
15157 ((eq scope 'file-with-archives)
15158 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15159 (org-agenda-prepare-buffers scope)
15160 (while (setq file (pop scope))
15161 (with-current-buffer (org-find-base-buffer-visiting file)
15162 (save-excursion
15163 (save-restriction
15164 (widen)
15165 (goto-char (point-min))
15166 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
15167 res)))
15169 ;;;; Properties
15171 ;;; Setting and retrieving properties
15173 (defconst org-special-properties
15174 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
15175 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
15176 "The special properties valid in Org-mode.
15178 These are properties that are not defined in the property drawer,
15179 but in some other way.")
15181 (defconst org-default-properties
15182 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15183 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15184 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15185 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15186 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
15187 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15188 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15189 "Some properties that are used by Org-mode for various purposes.
15190 Being in this list makes sure that they are offered for completion.")
15192 (defun org-property-action ()
15193 "Do an action on properties."
15194 (interactive)
15195 (let (c)
15196 (org-at-property-p)
15197 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15198 (setq c (read-char-exclusive))
15199 (cond
15200 ((equal c ?s)
15201 (call-interactively 'org-set-property))
15202 ((equal c ?d)
15203 (call-interactively 'org-delete-property))
15204 ((equal c ?D)
15205 (call-interactively 'org-delete-property-globally))
15206 ((equal c ?c)
15207 (call-interactively 'org-compute-property-at-point))
15208 (t (user-error "No such property action %c" c)))))
15210 (defun org-inc-effort ()
15211 "Increment the value of the effort property in the current entry."
15212 (interactive)
15213 (org-set-effort nil t))
15215 (defvar org-clock-effort) ;; Defined in org-clock.el
15216 (defvar org-clock-current-task) ;; Defined in org-clock.el
15217 (defun org-set-effort (&optional value increment)
15218 "Set the effort property of the current entry.
15219 With numerical prefix arg, use the nth allowed value, 0 stands for the
15220 10th allowed value.
15222 When INCREMENT is non-nil, set the property to the next allowed value."
15223 (interactive "P")
15224 (if (equal value 0) (setq value 10))
15225 (let* ((completion-ignore-case t)
15226 (prop org-effort-property)
15227 (cur (org-entry-get nil prop))
15228 (allowed (org-property-get-allowed-values nil prop 'table))
15229 (existing (mapcar 'list (org-property-values prop)))
15230 (heading (nth 4 (org-heading-components)))
15232 (val (cond
15233 ((stringp value) value)
15234 ((and allowed (integerp value))
15235 (or (car (nth (1- value) allowed))
15236 (car (org-last allowed))))
15237 ((and allowed increment)
15238 (or (caadr (member (list cur) allowed))
15239 (user-error "Allowed effort values are not set")))
15240 (allowed
15241 (message "Select 1-9,0, [RET%s]: %s"
15242 (if cur (concat "=" cur) "")
15243 (mapconcat 'car allowed " "))
15244 (setq rpl (read-char-exclusive))
15245 (if (equal rpl ?\r)
15247 (setq rpl (- rpl ?0))
15248 (if (equal rpl 0) (setq rpl 10))
15249 (if (and (> rpl 0) (<= rpl (length allowed)))
15250 (car (nth (1- rpl) allowed))
15251 (org-completing-read "Effort: " allowed nil))))
15253 (let (org-completion-use-ido org-completion-use-iswitchb)
15254 (org-completing-read
15255 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15256 (concat "[" cur "]") "")
15257 ": ")
15258 existing nil nil "" nil cur))))))
15259 (unless (equal (org-entry-get nil prop) val)
15260 (org-entry-put nil prop val))
15261 (save-excursion
15262 (org-back-to-heading t)
15263 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
15264 (when (string= heading org-clock-current-task)
15265 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
15266 (org-clock-update-mode-line))
15267 (message "%s is now %s" prop val)))
15269 (defun org-at-property-p ()
15270 "Is cursor inside a property drawer?"
15271 (save-excursion
15272 (when (equal 'node-property (car (org-element-at-point)))
15273 (beginning-of-line 1)
15274 (looking-at org-property-re))))
15276 (defun org-get-property-block (&optional beg end force)
15277 "Return the (beg . end) range of the body of the property drawer.
15278 BEG and END are the beginning and end of the current subtree, or of
15279 the part before the first headline. If they are not given, they will
15280 be found. If the drawer does not exist and FORCE is non-nil, create
15281 the drawer."
15282 (catch 'exit
15283 (save-excursion
15284 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15285 (progn (org-back-to-heading t) (point))))
15286 (end (or end (and (not (outline-next-heading)) (point-max))
15287 (point))))
15288 (goto-char beg)
15289 (if (re-search-forward org-property-start-re end t)
15290 (setq beg (1+ (match-end 0)))
15291 (if force
15292 (save-excursion
15293 (org-insert-property-drawer)
15294 (setq end (progn (outline-next-heading) (point))))
15295 (throw 'exit nil))
15296 (goto-char beg)
15297 (if (re-search-forward org-property-start-re end t)
15298 (setq beg (1+ (match-end 0)))))
15299 (if (re-search-forward org-property-end-re end t)
15300 (setq end (match-beginning 0))
15301 (or force (throw 'exit nil))
15302 (goto-char beg)
15303 (setq end beg)
15304 (org-indent-line)
15305 (insert ":END:\n"))
15306 (cons beg end)))))
15308 (defun org-entry-properties (&optional pom which specific)
15309 "Get all properties of the entry at point-or-marker POM.
15310 This includes the TODO keyword, the tags, time strings for deadline,
15311 scheduled, and clocking, and any additional properties defined in the
15312 entry. The return value is an alist, keys may occur multiple times
15313 if the property key was used several times.
15314 POM may also be nil, in which case the current entry is used.
15315 If WHICH is nil or `all', get all properties. If WHICH is
15316 `special' or `standard', only get that subclass. If WHICH
15317 is a string only get exactly this property. SPECIFIC can be a string, the
15318 specific property we are interested in. Specifying it can speed
15319 things up because then unnecessary parsing is avoided."
15320 (setq which (or which 'all))
15321 (org-with-wide-buffer
15322 (org-with-point-at pom
15323 (let ((clockstr (substring org-clock-string 0 -1))
15324 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15325 (case-fold-search nil)
15326 beg end range props sum-props key key1 value string clocksum clocksumt)
15327 (when (and (derived-mode-p 'org-mode)
15328 (ignore-errors (org-back-to-heading t)))
15329 (setq beg (point))
15330 (setq sum-props (get-text-property (point) 'org-summaries))
15331 (setq clocksum (get-text-property (point) :org-clock-minutes)
15332 clocksumt (get-text-property (point) :org-clock-minutes-today))
15333 (outline-next-heading)
15334 (setq end (point))
15335 (when (memq which '(all special))
15336 ;; Get the special properties, like TODO and tags
15337 (goto-char beg)
15338 (when (and (or (not specific) (string= specific "TODO"))
15339 (looking-at org-todo-line-regexp) (match-end 2))
15340 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15341 (when (and (or (not specific) (string= specific "PRIORITY"))
15342 (looking-at org-priority-regexp))
15343 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15344 (when (or (not specific) (string= specific "FILE"))
15345 (push (cons "FILE" buffer-file-name) props))
15346 (when (and (or (not specific) (string= specific "TAGS"))
15347 (setq value (org-get-tags-string))
15348 (string-match "\\S-" value))
15349 (push (cons "TAGS" value) props))
15350 (when (and (or (not specific) (string= specific "ALLTAGS"))
15351 (setq value (org-get-tags-at)))
15352 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15353 ":"))
15354 props))
15355 (when (or (not specific) (string= specific "BLOCKED"))
15356 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15357 (when (or (not specific)
15358 (member specific
15359 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15360 "TIMESTAMP" "TIMESTAMP_IA")))
15361 (catch 'match
15362 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15363 (setq key (if (match-end 1)
15364 (substring (org-match-string-no-properties 1)
15365 0 -1))
15366 string (if (equal key clockstr)
15367 (org-trim
15368 (buffer-substring-no-properties
15369 (match-beginning 3) (goto-char
15370 (point-at-eol))))
15371 (substring (org-match-string-no-properties 3)
15372 1 -1)))
15373 ;; Get the correct property name from the key. This is
15374 ;; necessary if the user has configured time keywords.
15375 (setq key1 (concat key ":"))
15376 (cond
15377 ((not key)
15378 (setq key
15379 (if (= (char-after (match-beginning 3)) ?\[)
15380 "TIMESTAMP_IA" "TIMESTAMP")))
15381 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15382 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15383 ((equal key1 org-closed-string) (setq key "CLOSED"))
15384 ((equal key1 org-clock-string) (setq key "CLOCK")))
15385 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15386 (progn
15387 (push (cons key string) props)
15388 ;; no need to search further if match is found
15389 (throw 'match t))
15390 (when (or (equal key "CLOCK") (not (assoc key props)))
15391 (push (cons key string) props)))))))
15393 (when (memq which '(all standard))
15394 ;; Get the standard properties, like :PROP: ...
15395 (setq range (org-get-property-block beg end))
15396 (when range
15397 (goto-char (car range))
15398 (while (re-search-forward org-property-re
15399 (cdr range) t)
15400 (setq key (org-match-string-no-properties 2)
15401 value (org-trim (or (org-match-string-no-properties 3) "")))
15402 (unless (member key excluded)
15403 (push (cons key (or value "")) props)))))
15404 (if clocksum
15405 (push (cons "CLOCKSUM"
15406 (org-columns-number-to-string (/ (float clocksum) 60.)
15407 'add_times))
15408 props))
15409 (if clocksumt
15410 (push (cons "CLOCKSUM_T"
15411 (org-columns-number-to-string (/ (float clocksumt) 60.)
15412 'add_times))
15413 props))
15414 (unless (assoc "CATEGORY" props)
15415 (push (cons "CATEGORY" (org-get-category)) props))
15416 (append sum-props (nreverse props)))))))
15418 (defun org-entry-get (pom property &optional inherit literal-nil)
15419 "Get value of PROPERTY for entry or content at point-or-marker POM.
15420 If INHERIT is non-nil and the entry does not have the property,
15421 then also check higher levels of the hierarchy.
15422 If INHERIT is the symbol `selective', use inheritance only if the setting
15423 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15424 If the property is present but empty, the return value is the empty string.
15425 If the property is not present at all, nil is returned.
15427 Return the value as a string.
15429 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15430 do not interpret it as the list atom nil. This is used for inheritance
15431 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15432 (org-with-point-at pom
15433 (if (and inherit (if (eq inherit 'selective)
15434 (org-property-inherit-p property)
15436 (org-entry-get-with-inheritance property literal-nil)
15437 (if (member property org-special-properties)
15438 ;; We need a special property. Use `org-entry-properties'
15439 ;; to retrieve it, but specify the wanted property
15440 (cdr (assoc property (org-entry-properties nil 'special property)))
15441 (org-with-wide-buffer
15442 (let ((range (org-get-property-block)))
15443 (when (and range (not (eq (car range) (cdr range)))
15444 (save-excursion
15445 (goto-char (car range))
15446 (re-search-forward
15447 (concat (org-re-property property) "\\|"
15448 (org-re-property (concat property "+")))
15449 (cdr range) t)))
15450 (let* ((props
15451 (list (or (assoc property org-file-properties)
15452 (assoc property org-global-properties)
15453 (assoc property org-global-properties-fixed))))
15454 (ap (lambda (key)
15455 (when (re-search-forward
15456 (org-re-property key) (cdr range) t)
15457 (setq props
15458 (org-update-property-plist
15460 (if (match-end 3)
15461 (org-match-string-no-properties 3) "")
15462 props)))))
15463 val)
15464 (goto-char (car range))
15465 (funcall ap property)
15466 (goto-char (car range))
15467 (while (funcall ap (concat property "+")))
15468 (setq val (cdr (assoc property props)))
15469 (when val (if literal-nil val (org-not-nil val)))))))))))
15471 (defun org-property-or-variable-value (var &optional inherit)
15472 "Check if there is a property fixing the value of VAR.
15473 If yes, return this value. If not, return the current value of the variable."
15474 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15475 (if (and prop (stringp prop) (string-match "\\S-" prop))
15476 (read prop)
15477 (symbol-value var))))
15479 (defun org-entry-delete (pom property)
15480 "Delete the property PROPERTY from entry at point-or-marker POM."
15481 (unless (member property org-special-properties)
15482 (org-with-point-at pom
15483 (let ((range (org-get-property-block)))
15484 (if (and range
15485 (goto-char (car range))
15486 (re-search-forward
15487 (org-re-property property)
15488 (cdr range) t))
15489 (progn
15490 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15491 (org-remove-empty-drawer-at (car range))
15493 nil)))))
15495 ;; Multi-values properties are properties that contain multiple values
15496 ;; These values are assumed to be single words, separated by whitespace.
15497 (defun org-entry-add-to-multivalued-property (pom property value)
15498 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15499 (let* ((old (org-entry-get pom property))
15500 (values (and old (org-split-string old "[ \t]"))))
15501 (setq value (org-entry-protect-space value))
15502 (unless (member value values)
15503 (setq values (append values (list value)))
15504 (org-entry-put pom property
15505 (mapconcat 'identity values " ")))))
15507 (defun org-entry-remove-from-multivalued-property (pom property value)
15508 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15509 (let* ((old (org-entry-get pom property))
15510 (values (and old (org-split-string old "[ \t]"))))
15511 (setq value (org-entry-protect-space value))
15512 (when (member value values)
15513 (setq values (delete value values))
15514 (org-entry-put pom property
15515 (mapconcat 'identity values " ")))))
15517 (defun org-entry-member-in-multivalued-property (pom property value)
15518 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15519 (let* ((old (org-entry-get pom property))
15520 (values (and old (org-split-string old "[ \t]"))))
15521 (setq value (org-entry-protect-space value))
15522 (member value values)))
15524 (defun org-entry-get-multivalued-property (pom property)
15525 "Return a list of values in a multivalued property."
15526 (let* ((value (org-entry-get pom property))
15527 (values (and value (org-split-string value "[ \t]"))))
15528 (mapcar 'org-entry-restore-space values)))
15530 (defun org-entry-put-multivalued-property (pom property &rest values)
15531 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15532 VALUES should be a list of strings. Spaces will be protected."
15533 (org-entry-put pom property
15534 (mapconcat 'org-entry-protect-space values " "))
15535 (let* ((value (org-entry-get pom property))
15536 (values (and value (org-split-string value "[ \t]"))))
15537 (mapcar 'org-entry-restore-space values)))
15539 (defun org-entry-protect-space (s)
15540 "Protect spaces and newline in string S."
15541 (while (string-match " " s)
15542 (setq s (replace-match "%20" t t s)))
15543 (while (string-match "\n" s)
15544 (setq s (replace-match "%0A" t t s)))
15547 (defun org-entry-restore-space (s)
15548 "Restore spaces and newline in string S."
15549 (while (string-match "%20" s)
15550 (setq s (replace-match " " t t s)))
15551 (while (string-match "%0A" s)
15552 (setq s (replace-match "\n" t t s)))
15555 (defvar org-entry-property-inherited-from (make-marker)
15556 "Marker pointing to the entry from where a property was inherited.
15557 Each call to `org-entry-get-with-inheritance' will set this marker to the
15558 location of the entry where the inheritance search matched. If there was
15559 no match, the marker will point nowhere.
15560 Note that also `org-entry-get' calls this function, if the INHERIT flag
15561 is set.")
15563 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15564 "Get PROPERTY of entry or content at point, search higher levels if needed.
15565 The search will stop at the first ancestor which has the property defined.
15566 If the value found is \"nil\", return nil to show that the property
15567 should be considered as undefined (this is the meaning of nil here).
15568 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15569 (move-marker org-entry-property-inherited-from nil)
15570 (let (tmp)
15571 (save-excursion
15572 (save-restriction
15573 (widen)
15574 (catch 'ex
15575 (while t
15576 (when (setq tmp (org-entry-get nil property nil literal-nil))
15577 (or (ignore-errors (org-back-to-heading t))
15578 (goto-char (point-min)))
15579 (move-marker org-entry-property-inherited-from (point))
15580 (throw 'ex tmp))
15581 (or (ignore-errors (org-up-heading-safe))
15582 (throw 'ex nil))))))
15583 (setq tmp (or tmp
15584 (cdr (assoc property org-file-properties))
15585 (cdr (assoc property org-global-properties))
15586 (cdr (assoc property org-global-properties-fixed))))
15587 (if literal-nil tmp (org-not-nil tmp))))
15589 (defvar org-property-changed-functions nil
15590 "Hook called when the value of a property has changed.
15591 Each hook function should accept two arguments, the name of the property
15592 and the new value.")
15594 (defun org-entry-put (pom property value)
15595 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15596 If the value is `nil', it is converted to the empty string.
15597 If it is not a string, an error is raised."
15598 (cond ((null value) (setq value ""))
15599 ((not (stringp value))
15600 (error "Properties values should be strings.")))
15601 (org-with-point-at pom
15602 (org-back-to-heading t)
15603 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15604 range)
15605 (cond
15606 ((equal property "TODO")
15607 (when (and (string-match "\\S-" value)
15608 (not (member value org-todo-keywords-1)))
15609 (user-error "\"%s\" is not a valid TODO state" value))
15610 (if (or (not value)
15611 (not (string-match "\\S-" value)))
15612 (setq value 'none))
15613 (org-todo value)
15614 (org-set-tags nil 'align))
15615 ((equal property "PRIORITY")
15616 (org-priority (if (and value (string-match "\\S-" value))
15617 (string-to-char value) ?\ ))
15618 (org-set-tags nil 'align))
15619 ((equal property "CLOCKSUM")
15620 (if (not (re-search-forward
15621 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15622 (error "Cannot find a clock log")
15623 (goto-char (- (match-end 1) 2))
15624 (cond
15625 ((eq value 'earlier) (org-timestamp-down))
15626 ((eq value 'later) (org-timestamp-up)))
15627 (org-clock-sum-current-item)))
15628 ((equal property "SCHEDULED")
15629 (if (re-search-forward org-scheduled-time-regexp end t)
15630 (cond
15631 ((eq value 'earlier) (org-timestamp-change -1 'day))
15632 ((eq value 'later) (org-timestamp-change 1 'day))
15633 (t (call-interactively 'org-schedule)))
15634 (call-interactively 'org-schedule)))
15635 ((equal property "DEADLINE")
15636 (if (re-search-forward org-deadline-time-regexp end t)
15637 (cond
15638 ((eq value 'earlier) (org-timestamp-change -1 'day))
15639 ((eq value 'later) (org-timestamp-change 1 'day))
15640 (t (call-interactively 'org-deadline)))
15641 (call-interactively 'org-deadline)))
15642 ((member property org-special-properties)
15643 (error "The %s property can not yet be set with `org-entry-put'"
15644 property))
15645 (t ; a non-special property
15646 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15647 (setq range (org-get-property-block beg end 'force))
15648 (goto-char (car range))
15649 (if (re-search-forward
15650 (org-re-property property) (cdr range) t)
15651 (progn
15652 (delete-region (match-beginning 0) (match-end 0))
15653 (goto-char (match-beginning 0)))
15654 (goto-char (cdr range))
15655 (insert "\n")
15656 (backward-char 1)
15657 (org-indent-line))
15658 (insert ":" property ":")
15659 (and value (insert " " value))
15660 (org-indent-line)))))
15661 (run-hook-with-args 'org-property-changed-functions property value)))
15663 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15664 "Get all property keys in the current buffer.
15665 With INCLUDE-SPECIALS, also list the special properties that reflect things
15666 like tags and TODO state.
15667 With INCLUDE-DEFAULTS, also include properties that has special meaning
15668 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15669 and others.
15670 With INCLUDE-COLUMNS, also include property names given in COLUMN
15671 formats in the current buffer."
15672 (let (rtn range cfmt s p)
15673 (save-excursion
15674 (save-restriction
15675 (widen)
15676 (goto-char (point-min))
15677 (while (re-search-forward org-property-start-re nil t)
15678 (setq range (org-get-property-block))
15679 (goto-char (car range))
15680 (while (re-search-forward org-property-re
15681 (cdr range) t)
15682 (add-to-list 'rtn (org-match-string-no-properties 2)))
15683 (outline-next-heading))))
15685 (when include-specials
15686 (setq rtn (append org-special-properties rtn)))
15688 (when include-defaults
15689 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15690 (add-to-list 'rtn org-effort-property))
15692 (when include-columns
15693 (save-excursion
15694 (save-restriction
15695 (widen)
15696 (goto-char (point-min))
15697 (while (re-search-forward
15698 "^[ \t]*\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15699 nil t)
15700 (setq cfmt (match-string 2) s 0)
15701 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15702 cfmt s)
15703 (setq s (match-end 0)
15704 p (match-string 1 cfmt))
15705 (unless (or (equal p "ITEM")
15706 (member p org-special-properties))
15707 (add-to-list 'rtn (match-string 1 cfmt))))))))
15709 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15711 (defun org-property-values (key)
15712 "Return a list of all values of property KEY in the current buffer."
15713 (save-excursion
15714 (save-restriction
15715 (widen)
15716 (goto-char (point-min))
15717 (let ((re (org-re-property key))
15718 values)
15719 (while (re-search-forward re nil t)
15720 (add-to-list 'values (org-trim (match-string 3))))
15721 (delete "" values)))))
15723 (defun org-insert-property-drawer ()
15724 "Insert a property drawer into the current entry."
15725 (org-back-to-heading t)
15726 (looking-at org-outline-regexp)
15727 (let ((indent (if org-adapt-indentation
15728 (- (match-end 0) (match-beginning 0))
15730 (beg (point))
15731 (re (concat "^[ \t]*" org-keyword-time-regexp))
15732 end hiddenp)
15733 (outline-next-heading)
15734 (setq end (point))
15735 (goto-char beg)
15736 (while (re-search-forward re end t))
15737 (setq hiddenp (outline-invisible-p))
15738 (end-of-line 1)
15739 (and (equal (char-after) ?\n) (forward-char 1))
15740 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15741 (if (member (match-string 1) '("CLOCK:" ":END:"))
15742 ;; just skip this line
15743 (beginning-of-line 2)
15744 ;; Drawer start, find the end
15745 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15746 (beginning-of-line 1)))
15747 (org-skip-over-state-notes)
15748 (skip-chars-backward " \t\n\r")
15749 (if (and (eq (char-before) ?*) (not (eq (char-after) ?\n)))
15750 (forward-char 1))
15751 (goto-char (point-at-eol))
15752 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15753 (beginning-of-line 0)
15754 (org-indent-to-column indent)
15755 (beginning-of-line 2)
15756 (org-indent-to-column indent)
15757 (beginning-of-line 0)
15758 (if hiddenp
15759 (save-excursion
15760 (org-back-to-heading t)
15761 (hide-entry))
15762 (org-flag-drawer t))))
15764 (defun org-insert-drawer (&optional arg drawer)
15765 "Insert a drawer at point.
15767 Optional argument DRAWER, when non-nil, is a string representing
15768 drawer's name. Otherwise, the user is prompted for a name.
15770 If a region is active, insert the drawer around that region
15771 instead.
15773 Point is left between drawer's boundaries."
15774 (interactive "P")
15775 (let* ((drawer (if arg "PROPERTIES"
15776 (or drawer (read-from-minibuffer "Drawer: ")))))
15777 (cond
15778 ;; With C-u, fall back on `org-insert-property-drawer'
15779 (arg (org-insert-property-drawer))
15781 ((not (org-string-match-p org-drawer-regexp (format ":%s:" drawer)))
15782 (user-error "Invalid drawer name"))
15783 ;; With an active region, insert a drawer at point.
15784 ((not (org-region-active-p))
15785 (progn
15786 (unless (bolp) (insert "\n"))
15787 (insert (format ":%s:\n\n:END:\n" drawer))
15788 (forward-line -2)))
15789 ;; Otherwise, insert the drawer at point
15791 (let ((rbeg (region-beginning))
15792 (rend (copy-marker (region-end))))
15793 (unwind-protect
15794 (progn
15795 (goto-char rbeg)
15796 (beginning-of-line)
15797 (when (save-excursion
15798 (re-search-forward org-outline-regexp-bol rend t))
15799 (user-error "Drawers cannot contain headlines"))
15800 ;; Position point at the beginning of the first
15801 ;; non-blank line in region. Insert drawer's opening
15802 ;; there, then indent it.
15803 (org-skip-whitespace)
15804 (beginning-of-line)
15805 (insert ":" drawer ":\n")
15806 (forward-line -1)
15807 (indent-for-tab-command)
15808 ;; Move point to the beginning of the first blank line
15809 ;; after the last non-blank line in region. Insert
15810 ;; drawer's closing, then indent it.
15811 (goto-char rend)
15812 (skip-chars-backward " \r\t\n")
15813 (insert "\n:END:")
15814 (deactivate-mark t)
15815 (indent-for-tab-command)
15816 (unless (eolp) (insert "\n")))
15817 ;; Clear marker, whatever the outcome of insertion is.
15818 (set-marker rend nil)))))))
15820 (defvar org-property-set-functions-alist nil
15821 "Property set function alist.
15822 Each entry should have the following format:
15824 (PROPERTY . READ-FUNCTION)
15826 The read function will be called with the same argument as
15827 `org-completing-read'.")
15829 (defun org-set-property-function (property)
15830 "Get the function that should be used to set PROPERTY.
15831 This is computed according to `org-property-set-functions-alist'."
15832 (or (cdr (assoc property org-property-set-functions-alist))
15833 'org-completing-read))
15835 (defun org-read-property-value (property)
15836 "Read PROPERTY value from user."
15837 (let* ((completion-ignore-case t)
15838 (allowed (org-property-get-allowed-values nil property 'table))
15839 (cur (org-entry-get nil property))
15840 (prompt (concat property " value"
15841 (if (and cur (string-match "\\S-" cur))
15842 (concat " [" cur "]") "") ": "))
15843 (set-function (org-set-property-function property))
15844 (val (if allowed
15845 (funcall set-function prompt allowed nil
15846 (not (get-text-property 0 'org-unrestricted
15847 (caar allowed))))
15848 (let (org-completion-use-ido org-completion-use-iswitchb)
15849 (funcall set-function prompt
15850 (mapcar 'list (org-property-values property))
15851 nil nil "" nil cur)))))
15852 (if (equal val "")
15854 val)))
15856 (defvar org-last-set-property nil)
15857 (defvar org-last-set-property-value nil)
15858 (defun org-read-property-name ()
15859 "Read a property name."
15860 (let* ((completion-ignore-case t)
15861 (keys (org-buffer-property-keys nil t t))
15862 (default-prop (or (save-excursion
15863 (save-match-data
15864 (beginning-of-line)
15865 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15866 (null (string= (match-string 1) "END"))
15867 (match-string 1))))
15868 org-last-set-property))
15869 (property (org-icompleting-read
15870 (concat "Property"
15871 (if default-prop (concat " [" default-prop "]") "")
15872 ": ")
15873 (mapcar 'list keys)
15874 nil nil nil nil
15875 default-prop)))
15876 (if (member property keys)
15877 property
15878 (or (cdr (assoc (downcase property)
15879 (mapcar (lambda (x) (cons (downcase x) x))
15880 keys)))
15881 property))))
15883 (defun org-set-property-and-value (use-last)
15884 "Allow to set [PROPERTY]: [value] direction from prompt.
15885 When use-default, don't even ask, just use the last
15886 \"[PROPERTY]: [value]\" string from the history."
15887 (interactive "P")
15888 (let* ((completion-ignore-case t)
15889 (pv (or (and use-last org-last-set-property-value)
15890 (org-completing-read
15891 "Enter a \"[Property]: [value]\" pair: "
15892 nil nil nil nil nil
15893 org-last-set-property-value)))
15894 prop val)
15895 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15896 (setq prop (match-string 1 pv)
15897 val (match-string 2 pv))
15898 (org-set-property prop val))))
15900 (defun org-set-property (property value)
15901 "In the current entry, set PROPERTY to VALUE.
15902 When called interactively, this will prompt for a property name, offering
15903 completion on existing and default properties. And then it will prompt
15904 for a value, offering completion either on allowed values (via an inherited
15905 xxx_ALL property) or on existing values in other instances of this property
15906 in the current file."
15907 (interactive (list nil nil))
15908 (let* ((property (or property (org-read-property-name)))
15909 (value (or value (org-read-property-value property)))
15910 (fn (cdr (assoc property org-properties-postprocess-alist))))
15911 (setq org-last-set-property property)
15912 (setq org-last-set-property-value (concat property ": " value))
15913 ;; Possibly postprocess the inserted value:
15914 (when fn (setq value (funcall fn value)))
15915 (unless (equal (org-entry-get nil property) value)
15916 (org-entry-put nil property value))))
15918 (defun org-delete-property (property)
15919 "In the current entry, delete PROPERTY."
15920 (interactive
15921 (let* ((completion-ignore-case t)
15922 (cat (org-entry-get (point) "CATEGORY"))
15923 (props0 (org-entry-properties nil 'standard))
15924 (props (if cat props0
15925 (delete `("CATEGORY" . ,(org-get-category)) props0)))
15926 (prop (if (< 1 (length props))
15927 (org-icompleting-read "Property: " props nil t)
15928 (caar props))))
15929 (list prop)))
15930 (if (org-entry-delete nil property)
15931 (message "Property %s deleted" property)))
15933 (defun org-delete-property-globally (property)
15934 "Remove PROPERTY globally, from all entries."
15935 (interactive
15936 (let* ((completion-ignore-case t)
15937 (prop (org-icompleting-read
15938 "Globally remove property: "
15939 (mapcar 'list (org-buffer-property-keys)))))
15940 (list prop)))
15941 (save-excursion
15942 (save-restriction
15943 (widen)
15944 (goto-char (point-min))
15945 (let ((cnt 0))
15946 (while (re-search-forward
15947 (org-re-property property)
15948 nil t)
15949 (setq cnt (1+ cnt))
15950 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15951 (message "Property \"%s\" removed from %d entries" property cnt)))))
15953 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15955 (defun org-compute-property-at-point ()
15956 "Compute the property at point.
15957 This looks for an enclosing column format, extracts the operator and
15958 then applies it to the property in the column format's scope."
15959 (interactive)
15960 (unless (org-at-property-p)
15961 (user-error "Not at a property"))
15962 (let ((prop (org-match-string-no-properties 2)))
15963 (org-columns-get-format-and-top-level)
15964 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15965 (user-error "No operator defined for property %s" prop))
15966 (org-columns-compute prop)))
15968 (defvar org-property-allowed-value-functions nil
15969 "Hook for functions supplying allowed values for a specific property.
15970 The functions must take a single argument, the name of the property, and
15971 return a flat list of allowed values. If \":ETC\" is one of
15972 the values, this means that these values are intended as defaults for
15973 completion, but that other values should be allowed too.
15974 The functions must return nil if they are not responsible for this
15975 property.")
15977 (defun org-property-get-allowed-values (pom property &optional table)
15978 "Get allowed values for the property PROPERTY.
15979 When TABLE is non-nil, return an alist that can directly be used for
15980 completion."
15981 (let (vals)
15982 (cond
15983 ((equal property "TODO")
15984 (setq vals (org-with-point-at pom
15985 (append org-todo-keywords-1 '("")))))
15986 ((equal property "PRIORITY")
15987 (let ((n org-lowest-priority))
15988 (while (>= n org-highest-priority)
15989 (push (char-to-string n) vals)
15990 (setq n (1- n)))))
15991 ((member property org-special-properties))
15992 ((setq vals (run-hook-with-args-until-success
15993 'org-property-allowed-value-functions property)))
15995 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15996 (when (and vals (string-match "\\S-" vals))
15997 (setq vals (car (read-from-string (concat "(" vals ")"))))
15998 (setq vals (mapcar (lambda (x)
15999 (cond ((stringp x) x)
16000 ((numberp x) (number-to-string x))
16001 ((symbolp x) (symbol-name x))
16002 (t "???")))
16003 vals)))))
16004 (when (member ":ETC" vals)
16005 (setq vals (remove ":ETC" vals))
16006 (org-add-props (car vals) '(org-unrestricted t)))
16007 (if table (mapcar 'list vals) vals)))
16009 (defun org-property-previous-allowed-value (&optional previous)
16010 "Switch to the next allowed value for this property."
16011 (interactive)
16012 (org-property-next-allowed-value t))
16014 (defun org-property-next-allowed-value (&optional previous)
16015 "Switch to the next allowed value for this property."
16016 (interactive)
16017 (unless (org-at-property-p)
16018 (user-error "Not at a property"))
16019 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16020 (key (match-string 2))
16021 (value (match-string 3))
16022 (allowed (or (org-property-get-allowed-values (point) key)
16023 (and (member value '("[ ]" "[-]" "[X]"))
16024 '("[ ]" "[X]"))))
16025 (heading (save-match-data (nth 4 (org-heading-components))))
16026 nval)
16027 (unless allowed
16028 (user-error "Allowed values for this property have not been defined"))
16029 (if previous (setq allowed (reverse allowed)))
16030 (if (member value allowed)
16031 (setq nval (car (cdr (member value allowed)))))
16032 (setq nval (or nval (car allowed)))
16033 (if (equal nval value)
16034 (user-error "Only one allowed value for this property"))
16035 (org-at-property-p)
16036 (replace-match (concat " :" key ": " nval) t t)
16037 (org-indent-line)
16038 (beginning-of-line 1)
16039 (skip-chars-forward " \t")
16040 (when (equal prop org-effort-property)
16041 (save-excursion
16042 (org-back-to-heading t)
16043 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
16044 (when (string= org-clock-current-task heading)
16045 (setq org-clock-effort nval)
16046 (org-clock-update-mode-line)))
16047 (run-hook-with-args 'org-property-changed-functions key nval)))
16049 (defun org-find-olp (path &optional this-buffer)
16050 "Return a marker pointing to the entry at outline path OLP.
16051 If anything goes wrong, throw an error.
16052 You can wrap this call to catch the error like this:
16054 (condition-case msg
16055 (org-mobile-locate-entry (match-string 4))
16056 (error (nth 1 msg)))
16058 The return value will then be either a string with the error message,
16059 or a marker if everything is OK.
16061 If THIS-BUFFER is set, the outline path does not contain a file,
16062 only headings."
16063 (let* ((file (if this-buffer buffer-file-name (pop path)))
16064 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16065 (level 1)
16066 (lmin 1)
16067 (lmax 1)
16068 limit re end found pos heading cnt flevel)
16069 (unless buffer (error "File not found :%s" file))
16070 (with-current-buffer buffer
16071 (save-excursion
16072 (save-restriction
16073 (widen)
16074 (setq limit (point-max))
16075 (goto-char (point-min))
16076 (while (setq heading (pop path))
16077 (setq re (format org-complex-heading-regexp-format
16078 (regexp-quote heading)))
16079 (setq cnt 0 pos (point))
16080 (while (re-search-forward re end t)
16081 (setq level (- (match-end 1) (match-beginning 1)))
16082 (if (and (>= level lmin) (<= level lmax))
16083 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16084 (when (= cnt 0) (error "Heading not found on level %d: %s"
16085 lmax heading))
16086 (when (> cnt 1) (error "Heading not unique on level %d: %s"
16087 lmax heading))
16088 (goto-char found)
16089 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16090 (setq end (save-excursion (org-end-of-subtree t t))))
16091 (when (org-at-heading-p)
16092 (point-marker)))))))
16094 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16095 "Find node HEADING in BUFFER.
16096 Return a marker to the heading if it was found, or nil if not.
16097 If POS-ONLY is set, return just the position instead of a marker.
16099 The heading text must match exact, but it may have a TODO keyword,
16100 a priority cookie and tags in the standard locations."
16101 (with-current-buffer (or buffer (current-buffer))
16102 (save-excursion
16103 (save-restriction
16104 (widen)
16105 (goto-char (point-min))
16106 (let (case-fold-search)
16107 (if (re-search-forward
16108 (format org-complex-heading-regexp-format
16109 (regexp-quote heading)) nil t)
16110 (if pos-only
16111 (match-beginning 0)
16112 (move-marker (make-marker) (match-beginning 0)))))))))
16114 (defun org-find-exact-heading-in-directory (heading &optional dir)
16115 "Find Org node headline HEADING in all .org files in directory DIR.
16116 When the target headline is found, return a marker to this location."
16117 (let ((files (directory-files (or dir default-directory)
16118 nil "\\`[^.#].*\\.org\\'"))
16119 file visiting m buffer)
16120 (catch 'found
16121 (while (setq file (pop files))
16122 (message "trying %s" file)
16123 (setq visiting (org-find-base-buffer-visiting file))
16124 (setq buffer (or visiting (find-file-noselect file)))
16125 (setq m (org-find-exact-headline-in-buffer
16126 heading buffer))
16127 (when (and (not m) (not visiting)) (kill-buffer buffer))
16128 (and m (throw 'found m))))))
16130 (defun org-find-entry-with-id (ident)
16131 "Locate the entry that contains the ID property with exact value IDENT.
16132 IDENT can be a string, a symbol or a number, this function will search for
16133 the string representation of it.
16134 Return the position where this entry starts, or nil if there is no such entry."
16135 (interactive "sID: ")
16136 (let ((id (cond
16137 ((stringp ident) ident)
16138 ((symbol-name ident) (symbol-name ident))
16139 ((numberp ident) (number-to-string ident))
16140 (t (error "IDENT %s must be a string, symbol or number" ident))))
16141 (case-fold-search nil))
16142 (save-excursion
16143 (save-restriction
16144 (widen)
16145 (goto-char (point-min))
16146 (when (re-search-forward
16147 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16148 nil t)
16149 (org-back-to-heading t)
16150 (point))))))
16152 ;;;; Timestamps
16154 (defvar org-last-changed-timestamp nil)
16155 (defvar org-last-inserted-timestamp nil
16156 "The last time stamp inserted with `org-insert-time-stamp'.")
16157 (defvar org-ts-what) ; dynamically scoped parameter
16159 (defun org-time-stamp (arg &optional inactive)
16160 "Prompt for a date/time and insert a time stamp.
16161 If the user specifies a time like HH:MM or if this command is
16162 called with at least one prefix argument, the time stamp contains
16163 the date and the time. Otherwise, only the date is be included.
16165 All parts of a date not specified by the user is filled in from
16166 the current date/time. So if you just press return without
16167 typing anything, the time stamp will represent the current
16168 date/time.
16170 If there is already a timestamp at the cursor, it will be
16171 modified.
16173 With two universal prefix arguments, insert an active timestamp
16174 with the current time without prompting the user.
16176 When called from lisp, the timestamp is inactive if INACTIVE is
16177 non-nil."
16178 (interactive "P")
16179 (let* ((ts nil)
16180 (default-time
16181 ;; Default time is either today, or, when entering a range,
16182 ;; the range start.
16183 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16184 (save-excursion
16185 (re-search-backward
16186 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16187 (- (point) 20) t)))
16188 (apply 'encode-time (org-parse-time-string (match-string 1)))
16189 (current-time)))
16190 (default-input (and ts (org-get-compact-tod ts)))
16191 (repeater (save-excursion
16192 (save-match-data
16193 (beginning-of-line)
16194 (when (re-search-forward
16195 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16196 (save-excursion (progn (end-of-line) (point))) t)
16197 (match-string 0)))))
16198 org-time-was-given org-end-time-was-given time)
16199 (cond
16200 ((and (org-at-timestamp-p t)
16201 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16202 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16203 (insert "--")
16204 (setq time (let ((this-command this-command))
16205 (org-read-date arg 'totime nil nil
16206 default-time default-input inactive)))
16207 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16208 ((org-at-timestamp-p t)
16209 (setq time (let ((this-command this-command))
16210 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16211 (when (org-at-timestamp-p t) ; just to get the match data
16212 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16213 (replace-match "")
16214 (setq org-last-changed-timestamp
16215 (org-insert-time-stamp
16216 time (or org-time-was-given arg)
16217 inactive nil nil (list org-end-time-was-given)))
16218 (when repeater (goto-char (1- (point))) (insert " " repeater)
16219 (setq org-last-changed-timestamp
16220 (concat (substring org-last-inserted-timestamp 0 -1)
16221 " " repeater ">"))))
16222 (message "Timestamp updated"))
16223 ((equal arg '(16))
16224 (org-insert-time-stamp (current-time) t inactive))
16226 (setq time (let ((this-command this-command))
16227 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16228 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16229 nil nil (list org-end-time-was-given))))))
16231 ;; FIXME: can we use this for something else, like computing time differences?
16232 (defun org-get-compact-tod (s)
16233 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16234 (let* ((t1 (match-string 1 s))
16235 (h1 (string-to-number (match-string 2 s)))
16236 (m1 (string-to-number (match-string 3 s)))
16237 (t2 (and (match-end 4) (match-string 5 s)))
16238 (h2 (and t2 (string-to-number (match-string 6 s))))
16239 (m2 (and t2 (string-to-number (match-string 7 s))))
16240 dh dm)
16241 (if (not t2)
16243 (setq dh (- h2 h1) dm (- m2 m1))
16244 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16245 (concat t1 "+" (number-to-string dh)
16246 (and (/= 0 dm) (format ":%02d" dm)))))))
16248 (defun org-time-stamp-inactive (&optional arg)
16249 "Insert an inactive time stamp.
16250 An inactive time stamp is enclosed in square brackets instead of angle
16251 brackets. It is inactive in the sense that it does not trigger agenda entries,
16252 does not link to the calendar and cannot be changed with the S-cursor keys.
16253 So these are more for recording a certain time/date."
16254 (interactive "P")
16255 (org-time-stamp arg 'inactive))
16257 (defvar org-date-ovl (make-overlay 1 1))
16258 (overlay-put org-date-ovl 'face 'org-date-selected)
16259 (org-detach-overlay org-date-ovl)
16261 (defvar org-ans1) ; dynamically scoped parameter
16262 (defvar org-ans2) ; dynamically scoped parameter
16264 (defvar org-plain-time-of-day-regexp) ; defined below
16266 (defvar org-overriding-default-time nil) ; dynamically scoped
16267 (defvar org-read-date-overlay nil)
16268 (defvar org-dcst nil) ; dynamically scoped
16269 (defvar org-read-date-history nil)
16270 (defvar org-read-date-final-answer nil)
16271 (defvar org-read-date-analyze-futurep nil)
16272 (defvar org-read-date-analyze-forced-year nil)
16273 (defvar org-read-date-inactive)
16275 (defvar org-read-date-minibuffer-local-map
16276 (let* ((org-replace-disputed-keys nil)
16277 (map (make-sparse-keymap)))
16278 (set-keymap-parent map minibuffer-local-map)
16279 (org-defkey map (kbd ".")
16280 (lambda () (interactive)
16281 ;; Are we at the beginning of the prompt?
16282 (if (looking-back "^[^:]+: ")
16283 (org-eval-in-calendar '(calendar-goto-today))
16284 (insert "."))))
16285 (org-defkey map (kbd "C-.")
16286 (lambda () (interactive)
16287 (org-eval-in-calendar '(calendar-goto-today))))
16288 (org-defkey map [(meta shift left)]
16289 (lambda () (interactive)
16290 (org-eval-in-calendar '(calendar-backward-month 1))))
16291 (org-defkey map [(meta shift right)]
16292 (lambda () (interactive)
16293 (org-eval-in-calendar '(calendar-forward-month 1))))
16294 (org-defkey map [(meta shift up)]
16295 (lambda () (interactive)
16296 (org-eval-in-calendar '(calendar-backward-year 1))))
16297 (org-defkey map [(meta shift down)]
16298 (lambda () (interactive)
16299 (org-eval-in-calendar '(calendar-forward-year 1))))
16300 (org-defkey map [?\e (shift left)]
16301 (lambda () (interactive)
16302 (org-eval-in-calendar '(calendar-backward-month 1))))
16303 (org-defkey map [?\e (shift right)]
16304 (lambda () (interactive)
16305 (org-eval-in-calendar '(calendar-forward-month 1))))
16306 (org-defkey map [?\e (shift up)]
16307 (lambda () (interactive)
16308 (org-eval-in-calendar '(calendar-backward-year 1))))
16309 (org-defkey map [?\e (shift down)]
16310 (lambda () (interactive)
16311 (org-eval-in-calendar '(calendar-forward-year 1))))
16312 (org-defkey map [(shift up)]
16313 (lambda () (interactive)
16314 (org-eval-in-calendar '(calendar-backward-week 1))))
16315 (org-defkey map [(shift down)]
16316 (lambda () (interactive)
16317 (org-eval-in-calendar '(calendar-forward-week 1))))
16318 (org-defkey map [(shift left)]
16319 (lambda () (interactive)
16320 (org-eval-in-calendar '(calendar-backward-day 1))))
16321 (org-defkey map [(shift right)]
16322 (lambda () (interactive)
16323 (org-eval-in-calendar '(calendar-forward-day 1))))
16324 (org-defkey map "!"
16325 (lambda () (interactive)
16326 (org-eval-in-calendar '(diary-view-entries))
16327 (message "")))
16328 (org-defkey map ">"
16329 (lambda () (interactive)
16330 (org-eval-in-calendar '(scroll-calendar-left 1))))
16331 (org-defkey map "<"
16332 (lambda () (interactive)
16333 (org-eval-in-calendar '(scroll-calendar-right 1))))
16334 (org-defkey map "\C-v"
16335 (lambda () (interactive)
16336 (org-eval-in-calendar
16337 '(calendar-scroll-left-three-months 1))))
16338 (org-defkey map "\M-v"
16339 (lambda () (interactive)
16340 (org-eval-in-calendar
16341 '(calendar-scroll-right-three-months 1))))
16342 map)
16343 "Keymap for minibuffer commands when using `org-read-date'.")
16345 (defvar org-def)
16346 (defvar org-defdecode)
16347 (defvar org-with-time)
16349 (defun org-read-date (&optional org-with-time to-time from-string prompt
16350 default-time default-input inactive)
16351 "Read a date, possibly a time, and make things smooth for the user.
16352 The prompt will suggest to enter an ISO date, but you can also enter anything
16353 which will at least partially be understood by `parse-time-string'.
16354 Unrecognized parts of the date will default to the current day, month, year,
16355 hour and minute. If this command is called to replace a timestamp at point,
16356 or to enter the second timestamp of a range, the default time is taken
16357 from the existing stamp. Furthermore, the command prefers the future,
16358 so if you are giving a date where the year is not given, and the day-month
16359 combination is already past in the current year, it will assume you
16360 mean next year. For details, see the manual. A few examples:
16362 3-2-5 --> 2003-02-05
16363 feb 15 --> currentyear-02-15
16364 2/15 --> currentyear-02-15
16365 sep 12 9 --> 2009-09-12
16366 12:45 --> today 12:45
16367 22 sept 0:34 --> currentyear-09-22 0:34
16368 12 --> currentyear-currentmonth-12
16369 Fri --> nearest Friday after today
16370 -Tue --> last Tuesday
16371 etc.
16373 Furthermore you can specify a relative date by giving, as the *first* thing
16374 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16375 change in days weeks, months, years.
16376 With a single plus or minus, the date is relative to today. With a double
16377 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16378 +4d --> four days from today
16379 +4 --> same as above
16380 +2w --> two weeks from today
16381 ++5 --> five days from default date
16383 The function understands only English month and weekday abbreviations.
16385 While prompting, a calendar is popped up - you can also select the
16386 date with the mouse (button 1). The calendar shows a period of three
16387 months. To scroll it to other months, use the keys `>' and `<'.
16388 If you don't like the calendar, turn it off with
16389 \(setq org-read-date-popup-calendar nil)
16391 With optional argument TO-TIME, the date will immediately be converted
16392 to an internal time.
16393 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16394 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16395 still enter a time, and this function will inform the calling routine
16396 about this change. The calling routine may then choose to change the
16397 format used to insert the time stamp into the buffer to include the time.
16398 With optional argument FROM-STRING, read from this string instead from
16399 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16400 the time/date that is used for everything that is not specified by the
16401 user."
16402 (require 'parse-time)
16403 (let* ((org-time-stamp-rounding-minutes
16404 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16405 (org-dcst org-display-custom-times)
16406 (ct (org-current-time))
16407 (org-def (or org-overriding-default-time default-time ct))
16408 (org-defdecode (decode-time org-def))
16409 (dummy (progn
16410 (when (< (nth 2 org-defdecode) org-extend-today-until)
16411 (setcar (nthcdr 2 org-defdecode) -1)
16412 (setcar (nthcdr 1 org-defdecode) 59)
16413 (setq org-def (apply 'encode-time org-defdecode)
16414 org-defdecode (decode-time org-def)))))
16415 (mouse-autoselect-window nil) ; Don't let the mouse jump
16416 (calendar-frame-setup nil)
16417 (calendar-setup nil)
16418 (calendar-move-hook nil)
16419 (calendar-view-diary-initially-flag nil)
16420 (calendar-view-holidays-initially-flag nil)
16421 (timestr (format-time-string
16422 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16423 (prompt (concat (if prompt (concat prompt " ") "")
16424 (format "Date+time [%s]: " timestr)))
16425 ans (org-ans0 "") org-ans1 org-ans2 final)
16427 (cond
16428 (from-string (setq ans from-string))
16429 (org-read-date-popup-calendar
16430 (save-excursion
16431 (save-window-excursion
16432 (calendar)
16433 (org-eval-in-calendar '(setq cursor-type nil) t)
16434 (unwind-protect
16435 (progn
16436 (calendar-forward-day (- (time-to-days org-def)
16437 (calendar-absolute-from-gregorian
16438 (calendar-current-date))))
16439 (org-eval-in-calendar nil t)
16440 (let* ((old-map (current-local-map))
16441 (map (copy-keymap calendar-mode-map))
16442 (minibuffer-local-map
16443 (copy-keymap org-read-date-minibuffer-local-map)))
16444 (org-defkey map (kbd "RET") 'org-calendar-select)
16445 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16446 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16447 (unwind-protect
16448 (progn
16449 (use-local-map map)
16450 (setq org-read-date-inactive inactive)
16451 (add-hook 'post-command-hook 'org-read-date-display)
16452 (setq org-ans0 (read-string prompt default-input
16453 'org-read-date-history nil))
16454 ;; org-ans0: from prompt
16455 ;; org-ans1: from mouse click
16456 ;; org-ans2: from calendar motion
16457 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16458 (remove-hook 'post-command-hook 'org-read-date-display)
16459 (use-local-map old-map)
16460 (when org-read-date-overlay
16461 (delete-overlay org-read-date-overlay)
16462 (setq org-read-date-overlay nil)))))
16463 (bury-buffer "*Calendar*")))))
16465 (t ; Naked prompt only
16466 (unwind-protect
16467 (setq ans (read-string prompt default-input
16468 'org-read-date-history timestr))
16469 (when org-read-date-overlay
16470 (delete-overlay org-read-date-overlay)
16471 (setq org-read-date-overlay nil)))))
16473 (setq final (org-read-date-analyze ans org-def org-defdecode))
16475 (when org-read-date-analyze-forced-year
16476 (message "Year was forced into %s"
16477 (if org-read-date-force-compatible-dates
16478 "compatible range (1970-2037)"
16479 "range representable on this machine"))
16480 (ding))
16482 ;; One round trip to get rid of 34th of August and stuff like that....
16483 (setq final (decode-time (apply 'encode-time final)))
16485 (setq org-read-date-final-answer ans)
16487 (if to-time
16488 (apply 'encode-time final)
16489 (if (and (boundp 'org-time-was-given) org-time-was-given)
16490 (format "%04d-%02d-%02d %02d:%02d"
16491 (nth 5 final) (nth 4 final) (nth 3 final)
16492 (nth 2 final) (nth 1 final))
16493 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16495 (defun org-read-date-display ()
16496 "Display the current date prompt interpretation in the minibuffer."
16497 (when org-read-date-display-live
16498 (when org-read-date-overlay
16499 (delete-overlay org-read-date-overlay))
16500 (when (minibufferp (current-buffer))
16501 (save-excursion
16502 (end-of-line 1)
16503 (while (not (equal (buffer-substring
16504 (max (point-min) (- (point) 4)) (point))
16505 " "))
16506 (insert " ")))
16507 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16508 " " (or org-ans1 org-ans2)))
16509 (org-end-time-was-given nil)
16510 (f (org-read-date-analyze ans org-def org-defdecode))
16511 (fmts (if org-dcst
16512 org-time-stamp-custom-formats
16513 org-time-stamp-formats))
16514 (fmt (if (or org-with-time
16515 (and (boundp 'org-time-was-given) org-time-was-given))
16516 (cdr fmts)
16517 (car fmts)))
16518 (txt (format-time-string fmt (apply 'encode-time f)))
16519 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16520 (txt (concat "=> " txt)))
16521 (when (and org-end-time-was-given
16522 (string-match org-plain-time-of-day-regexp txt))
16523 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16524 org-end-time-was-given
16525 (substring txt (match-end 0)))))
16526 (when org-read-date-analyze-futurep
16527 (setq txt (concat txt " (=>F)")))
16528 (setq org-read-date-overlay
16529 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16530 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16532 (defun org-read-date-analyze (ans org-def org-defdecode)
16533 "Analyze the combined answer of the date prompt."
16534 ;; FIXME: cleanup and comment
16535 (let ((nowdecode (decode-time (current-time)))
16536 delta deltan deltaw deltadef year month day
16537 hour minute second wday pm h2 m2 tl wday1
16538 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16539 (setq org-read-date-analyze-futurep nil
16540 org-read-date-analyze-forced-year nil)
16541 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16542 (setq ans "+0"))
16544 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16545 (setq ans (replace-match "" t t ans)
16546 deltan (car delta)
16547 deltaw (nth 1 delta)
16548 deltadef (nth 2 delta)))
16550 ;; Check if there is an iso week date in there. If yes, store the
16551 ;; info and postpone interpreting it until the rest of the parsing
16552 ;; is done.
16553 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16554 (setq iso-year (if (match-end 1)
16555 (org-small-year-to-year
16556 (string-to-number (match-string 1 ans))))
16557 iso-weekday (if (match-end 3)
16558 (string-to-number (match-string 3 ans)))
16559 iso-week (string-to-number (match-string 2 ans)))
16560 (setq ans (replace-match "" t t ans)))
16562 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16563 (when (string-match
16564 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16565 (setq year (if (match-end 2)
16566 (string-to-number (match-string 2 ans))
16567 (progn (setq kill-year t)
16568 (string-to-number (format-time-string "%Y"))))
16569 month (string-to-number (match-string 3 ans))
16570 day (string-to-number (match-string 4 ans)))
16571 (if (< year 100) (setq year (+ 2000 year)))
16572 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16573 t nil ans)))
16575 ;; Help matching dotted european dates
16576 (when (string-match
16577 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16578 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16579 (setq kill-year t)
16580 (string-to-number (format-time-string "%Y")))
16581 day (string-to-number (match-string 1 ans))
16582 month (string-to-number (match-string 2 ans))
16583 ans (replace-match (format "%04d-%02d-%02d" year month day)
16584 t nil ans)))
16586 ;; Help matching american dates, like 5/30 or 5/30/7
16587 (when (string-match
16588 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16589 (setq year (if (match-end 4)
16590 (string-to-number (match-string 4 ans))
16591 (progn (setq kill-year t)
16592 (string-to-number (format-time-string "%Y"))))
16593 month (string-to-number (match-string 1 ans))
16594 day (string-to-number (match-string 2 ans)))
16595 (if (< year 100) (setq year (+ 2000 year)))
16596 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16597 t nil ans)))
16598 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16599 ;; If there is a time with am/pm, and *no* time without it, we convert
16600 ;; so that matching will be successful.
16601 (loop for i from 1 to 2 do ; twice, for end time as well
16602 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16603 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16604 (setq hour (string-to-number (match-string 1 ans))
16605 minute (if (match-end 3)
16606 (string-to-number (match-string 3 ans))
16608 pm (equal ?p
16609 (string-to-char (downcase (match-string 4 ans)))))
16610 (if (and (= hour 12) (not pm))
16611 (setq hour 0)
16612 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16613 (setq ans (replace-match (format "%02d:%02d" hour minute)
16614 t t ans))))
16616 ;; Check if a time range is given as a duration
16617 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16618 (setq hour (string-to-number (match-string 1 ans))
16619 h2 (+ hour (string-to-number (match-string 3 ans)))
16620 minute (string-to-number (match-string 2 ans))
16621 m2 (+ minute (if (match-end 5) (string-to-number
16622 (match-string 5 ans))0)))
16623 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16624 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16625 t t ans)))
16627 ;; Check if there is a time range
16628 (when (boundp 'org-end-time-was-given)
16629 (setq org-time-was-given nil)
16630 (when (and (string-match org-plain-time-of-day-regexp ans)
16631 (match-end 8))
16632 (setq org-end-time-was-given (match-string 8 ans))
16633 (setq ans (concat (substring ans 0 (match-beginning 7))
16634 (substring ans (match-end 7))))))
16636 (setq tl (parse-time-string ans)
16637 day (or (nth 3 tl) (nth 3 org-defdecode))
16638 month (or (nth 4 tl)
16639 (if (and org-read-date-prefer-future
16640 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16641 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16642 (nth 4 org-defdecode)))
16643 year (or (and (not kill-year) (nth 5 tl))
16644 (if (and org-read-date-prefer-future
16645 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16646 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16647 (nth 5 org-defdecode)))
16648 hour (or (nth 2 tl) (nth 2 org-defdecode))
16649 minute (or (nth 1 tl) (nth 1 org-defdecode))
16650 second (or (nth 0 tl) 0)
16651 wday (nth 6 tl))
16653 (when (and (eq org-read-date-prefer-future 'time)
16654 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16655 (equal day (nth 3 nowdecode))
16656 (equal month (nth 4 nowdecode))
16657 (equal year (nth 5 nowdecode))
16658 (nth 2 tl)
16659 (or (< (nth 2 tl) (nth 2 nowdecode))
16660 (and (= (nth 2 tl) (nth 2 nowdecode))
16661 (nth 1 tl)
16662 (< (nth 1 tl) (nth 1 nowdecode)))))
16663 (setq day (1+ day)
16664 futurep t))
16666 ;; Special date definitions below
16667 (cond
16668 (iso-week
16669 ;; There was an iso week
16670 (require 'cal-iso)
16671 (setq futurep nil)
16672 (setq year (or iso-year year)
16673 day (or iso-weekday wday 1)
16674 wday nil ; to make sure that the trigger below does not match
16675 iso-date (calendar-gregorian-from-absolute
16676 (calendar-absolute-from-iso
16677 (list iso-week day year))))
16678 ; FIXME: Should we also push ISO weeks into the future?
16679 ; (when (and org-read-date-prefer-future
16680 ; (not iso-year)
16681 ; (< (calendar-absolute-from-gregorian iso-date)
16682 ; (time-to-days (current-time))))
16683 ; (setq year (1+ year)
16684 ; iso-date (calendar-gregorian-from-absolute
16685 ; (calendar-absolute-from-iso
16686 ; (list iso-week day year)))))
16687 (setq month (car iso-date)
16688 year (nth 2 iso-date)
16689 day (nth 1 iso-date)))
16690 (deltan
16691 (setq futurep nil)
16692 (unless deltadef
16693 (let ((now (decode-time (current-time))))
16694 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16695 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16696 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16697 ((equal deltaw "m") (setq month (+ month deltan)))
16698 ((equal deltaw "y") (setq year (+ year deltan)))))
16699 ((and wday (not (nth 3 tl)))
16700 ;; Weekday was given, but no day, so pick that day in the week
16701 ;; on or after the derived date.
16702 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16703 (unless (equal wday wday1)
16704 (setq day (+ day (% (- wday wday1 -7) 7))))))
16705 (if (and (boundp 'org-time-was-given)
16706 (nth 2 tl))
16707 (setq org-time-was-given t))
16708 (if (< year 100) (setq year (+ 2000 year)))
16709 ;; Check of the date is representable
16710 (if org-read-date-force-compatible-dates
16711 (progn
16712 (if (< year 1970)
16713 (setq year 1970 org-read-date-analyze-forced-year t))
16714 (if (> year 2037)
16715 (setq year 2037 org-read-date-analyze-forced-year t)))
16716 (condition-case nil
16717 (ignore (encode-time second minute hour day month year))
16718 (error
16719 (setq year (nth 5 org-defdecode))
16720 (setq org-read-date-analyze-forced-year t))))
16721 (setq org-read-date-analyze-futurep futurep)
16722 (list second minute hour day month year)))
16724 (defvar parse-time-weekdays)
16725 (defun org-read-date-get-relative (s today default)
16726 "Check string S for special relative date string.
16727 TODAY and DEFAULT are internal times, for today and for a default.
16728 Return shift list (N what def-flag)
16729 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16730 N is the number of WHATs to shift.
16731 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16732 the DEFAULT date rather than TODAY."
16733 (require 'parse-time)
16734 (when (and
16735 (string-match
16736 (concat
16737 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16738 "\\([0-9]+\\)?"
16739 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16740 "\\([ \t]\\|$\\)") s)
16741 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16742 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16743 (string-to-char (substring (match-string 1 s) -1))
16744 ?+))
16745 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16746 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16747 (what (if (match-end 3) (match-string 3 s) "d"))
16748 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16749 (date (if rel default today))
16750 (wday (nth 6 (decode-time date)))
16751 delta)
16752 (if wday1
16753 (progn
16754 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16755 (if (= delta 0) (setq delta 7))
16756 (if (= dir ?-)
16757 (progn
16758 (setq delta (- delta 7))
16759 (if (= delta 0) (setq delta -7))))
16760 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16761 (list delta "d" rel))
16762 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16764 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16765 "Turn a user-specified date into the internal representation.
16766 The internal representation needed by the calendar is (month day year).
16767 This is a wrapper to handle the brain-dead convention in calendar that
16768 user function argument order change dependent on argument order."
16769 (if (boundp 'calendar-date-style)
16770 (cond
16771 ((eq calendar-date-style 'american)
16772 (list arg1 arg2 arg3))
16773 ((eq calendar-date-style 'european)
16774 (list arg2 arg1 arg3))
16775 ((eq calendar-date-style 'iso)
16776 (list arg2 arg3 arg1)))
16777 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16778 (if (org-bound-and-true-p european-calendar-style)
16779 (list arg2 arg1 arg3)
16780 (list arg1 arg2 arg3)))))
16782 (defun org-eval-in-calendar (form &optional keepdate)
16783 "Eval FORM in the calendar window and return to current window.
16784 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16785 otherwise stick to the current value of `org-ans2'."
16786 (let ((sf (selected-frame))
16787 (sw (selected-window)))
16788 (select-window (get-buffer-window "*Calendar*" t))
16789 (eval form)
16790 (when (and (not keepdate) (calendar-cursor-to-date))
16791 (let* ((date (calendar-cursor-to-date))
16792 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16793 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16794 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16795 (select-window sw)
16796 (org-select-frame-set-input-focus sf)))
16798 (defun org-calendar-select ()
16799 "Return to `org-read-date' with the date currently selected.
16800 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16801 (interactive)
16802 (when (calendar-cursor-to-date)
16803 (let* ((date (calendar-cursor-to-date))
16804 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16805 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16806 (if (active-minibuffer-window) (exit-minibuffer))))
16808 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16809 "Insert a date stamp for the date given by the internal TIME.
16810 WITH-HM means use the stamp format that includes the time of the day.
16811 INACTIVE means use square brackets instead of angular ones, so that the
16812 stamp will not contribute to the agenda.
16813 PRE and POST are optional strings to be inserted before and after the
16814 stamp.
16815 The command returns the inserted time stamp."
16816 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16817 stamp)
16818 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16819 (insert-before-markers (or pre ""))
16820 (when (listp extra)
16821 (setq extra (car extra))
16822 (if (and (stringp extra)
16823 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16824 (setq extra (format "-%02d:%02d"
16825 (string-to-number (match-string 1 extra))
16826 (string-to-number (match-string 2 extra))))
16827 (setq extra nil)))
16828 (when extra
16829 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16830 (insert-before-markers (setq stamp (format-time-string fmt time)))
16831 (insert-before-markers (or post ""))
16832 (setq org-last-inserted-timestamp stamp)))
16834 (defun org-toggle-time-stamp-overlays ()
16835 "Toggle the use of custom time stamp formats."
16836 (interactive)
16837 (setq org-display-custom-times (not org-display-custom-times))
16838 (unless org-display-custom-times
16839 (let ((p (point-min)) (bmp (buffer-modified-p)))
16840 (while (setq p (next-single-property-change p 'display))
16841 (if (and (get-text-property p 'display)
16842 (eq (get-text-property p 'face) 'org-date))
16843 (remove-text-properties
16844 p (setq p (next-single-property-change p 'display))
16845 '(display t))))
16846 (set-buffer-modified-p bmp)))
16847 (if (featurep 'xemacs)
16848 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16849 (org-restart-font-lock)
16850 (setq org-table-may-need-update t)
16851 (if org-display-custom-times
16852 (message "Time stamps are overlaid with custom format")
16853 (message "Time stamp overlays removed")))
16855 (defun org-display-custom-time (beg end)
16856 "Overlay modified time stamp format over timestamp between BEG and END."
16857 (let* ((ts (buffer-substring beg end))
16858 t1 w1 with-hm tf time str w2 (off 0))
16859 (save-match-data
16860 (setq t1 (org-parse-time-string ts t))
16861 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16862 (setq off (- (match-end 0) (match-beginning 0)))))
16863 (setq end (- end off))
16864 (setq w1 (- end beg)
16865 with-hm (and (nth 1 t1) (nth 2 t1))
16866 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16867 time (org-fix-decoded-time t1)
16868 str (org-add-props
16869 (format-time-string
16870 (substring tf 1 -1) (apply 'encode-time time))
16871 nil 'mouse-face 'highlight)
16872 w2 (length str))
16873 (if (not (= w2 w1))
16874 (add-text-properties (1+ beg) (+ 2 beg)
16875 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16876 (if (featurep 'xemacs)
16877 (progn
16878 (put-text-property beg end 'invisible t)
16879 (put-text-property beg end 'end-glyph (make-glyph str)))
16880 (put-text-property beg end 'display str))))
16882 (defun org-translate-time (string)
16883 "Translate all timestamps in STRING to custom format.
16884 But do this only if the variable `org-display-custom-times' is set."
16885 (when org-display-custom-times
16886 (save-match-data
16887 (let* ((start 0)
16888 (re org-ts-regexp-both)
16889 t1 with-hm inactive tf time str beg end)
16890 (while (setq start (string-match re string start))
16891 (setq beg (match-beginning 0)
16892 end (match-end 0)
16893 t1 (save-match-data
16894 (org-parse-time-string (substring string beg end) t))
16895 with-hm (and (nth 1 t1) (nth 2 t1))
16896 inactive (equal (substring string beg (1+ beg)) "[")
16897 tf (funcall (if with-hm 'cdr 'car)
16898 org-time-stamp-custom-formats)
16899 time (org-fix-decoded-time t1)
16900 str (format-time-string
16901 (concat
16902 (if inactive "[" "<") (substring tf 1 -1)
16903 (if inactive "]" ">"))
16904 (apply 'encode-time time))
16905 string (replace-match str t t string)
16906 start (+ start (length str)))))))
16907 string)
16909 (defun org-fix-decoded-time (time)
16910 "Set 0 instead of nil for the first 6 elements of time.
16911 Don't touch the rest."
16912 (let ((n 0))
16913 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16915 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16917 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16918 "Difference between TIMESTAMP-STRING and now in days.
16919 If SECONDS is non-nil, return the difference in seconds."
16920 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16921 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16922 (funcall fdiff (current-time)))))
16924 (defun org-deadline-close (timestamp-string &optional ndays)
16925 "Is the time in TIMESTAMP-STRING close to the current date?"
16926 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16927 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16928 (not (org-entry-is-done-p))))
16930 (defun org-get-wdays (ts &optional delay zero-delay)
16931 "Get the deadline lead time appropriate for timestring TS.
16932 When DELAY is non-nil, get the delay time for scheduled items
16933 instead of the deadline lead time. When ZERO-DELAY is non-nil
16934 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16935 don't try to find the delay cookie in the scheduled timestamp."
16936 (let ((tv (if delay org-scheduled-delay-days
16937 org-deadline-warning-days)))
16938 (cond
16939 ((or (and delay (< tv 0))
16940 (and delay zero-delay (<= tv 0))
16941 (and (not delay) (<= tv 0)))
16942 ;; Enforce this value no matter what
16943 (- tv))
16944 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16945 ;; lead time is specified.
16946 (floor (* (string-to-number (match-string 1 ts))
16947 (cdr (assoc (match-string 2 ts)
16948 '(("d" . 1) ("w" . 7)
16949 ("m" . 30.4) ("y" . 365.25)
16950 ("h" . 0.041667)))))))
16951 ;; go for the default.
16952 (t tv))))
16954 (defun org-calendar-select-mouse (ev)
16955 "Return to `org-read-date' with the date currently selected.
16956 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16957 (interactive "e")
16958 (mouse-set-point ev)
16959 (when (calendar-cursor-to-date)
16960 (let* ((date (calendar-cursor-to-date))
16961 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16962 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16963 (if (active-minibuffer-window) (exit-minibuffer))))
16965 (defun org-check-deadlines (ndays)
16966 "Check if there are any deadlines due or past due.
16967 A deadline is considered due if it happens within `org-deadline-warning-days'
16968 days from today's date. If the deadline appears in an entry marked DONE,
16969 it is not shown. The prefix arg NDAYS can be used to test that many
16970 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16971 (interactive "P")
16972 (let* ((org-warn-days
16973 (cond
16974 ((equal ndays '(4)) 100000)
16975 (ndays (prefix-numeric-value ndays))
16976 (t (abs org-deadline-warning-days))))
16977 (case-fold-search nil)
16978 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16979 (callback
16980 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16982 (message "%d deadlines past-due or due within %d days"
16983 (org-occur regexp nil callback)
16984 org-warn-days)))
16986 (defsubst org-re-timestamp (type)
16987 "Return a regexp for timestamp TYPE.
16988 Allowed values for TYPE are:
16990 all: all timestamps
16991 active: only active timestamps (<...>)
16992 inactive: only inactive timestamps ([...])
16993 scheduled: only scheduled timestamps
16994 deadline: only deadline timestamps
16995 closed: only closed time-stamps
16997 When TYPE is nil, fall back on returning a regexp that matches
16998 both scheduled and deadline timestamps."
16999 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
17000 ((eq type 'active) org-ts-regexp)
17001 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
17002 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
17003 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17004 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
17005 ((eq type 'scheduled-or-deadline)
17006 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
17008 (defun org-check-before-date (date)
17009 "Check if there are deadlines or scheduled entries before DATE."
17010 (interactive (list (org-read-date)))
17011 (let ((case-fold-search nil)
17012 (regexp (org-re-timestamp org-ts-type))
17013 (callback
17014 (lambda () (time-less-p
17015 (org-time-string-to-time (match-string 1))
17016 (org-time-string-to-time date)))))
17017 (message "%d entries before %s"
17018 (org-occur regexp nil callback) date)))
17020 (defun org-check-after-date (date)
17021 "Check if there are deadlines or scheduled entries after DATE."
17022 (interactive (list (org-read-date)))
17023 (let ((case-fold-search nil)
17024 (regexp (org-re-timestamp org-ts-type))
17025 (callback
17026 (lambda () (not
17027 (time-less-p
17028 (org-time-string-to-time (match-string 1))
17029 (org-time-string-to-time date))))))
17030 (message "%d entries after %s"
17031 (org-occur regexp nil callback) date)))
17033 (defun org-check-dates-range (start-date end-date)
17034 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17035 (interactive (list (org-read-date nil nil nil "Range starts")
17036 (org-read-date nil nil nil "Range end")))
17037 (let ((case-fold-search nil)
17038 (regexp (org-re-timestamp org-ts-type))
17039 (callback
17040 (lambda ()
17041 (let ((match (match-string 1)))
17042 (and
17043 (not (time-less-p
17044 (org-time-string-to-time match)
17045 (org-time-string-to-time start-date)))
17046 (time-less-p
17047 (org-time-string-to-time match)
17048 (org-time-string-to-time end-date)))))))
17049 (message "%d entries between %s and %s"
17050 (org-occur regexp nil callback) start-date end-date)))
17052 (defun org-evaluate-time-range (&optional to-buffer)
17053 "Evaluate a time range by computing the difference between start and end.
17054 Normally the result is just printed in the echo area, but with prefix arg
17055 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17056 If the time range is actually in a table, the result is inserted into the
17057 next column.
17058 For time difference computation, a year is assumed to be exactly 365
17059 days in order to avoid rounding problems."
17060 (interactive "P")
17062 (org-clock-update-time-maybe)
17063 (save-excursion
17064 (unless (org-at-date-range-p t)
17065 (goto-char (point-at-bol))
17066 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17067 (if (not (org-at-date-range-p t))
17068 (user-error "Not at a time-stamp range, and none found in current line")))
17069 (let* ((ts1 (match-string 1))
17070 (ts2 (match-string 2))
17071 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17072 (match-end (match-end 0))
17073 (time1 (org-time-string-to-time ts1))
17074 (time2 (org-time-string-to-time ts2))
17075 (t1 (org-float-time time1))
17076 (t2 (org-float-time time2))
17077 (diff (abs (- t2 t1)))
17078 (negative (< (- t2 t1) 0))
17079 ;; (ys (floor (* 365 24 60 60)))
17080 (ds (* 24 60 60))
17081 (hs (* 60 60))
17082 (fy "%dy %dd %02d:%02d")
17083 (fy1 "%dy %dd")
17084 (fd "%dd %02d:%02d")
17085 (fd1 "%dd")
17086 (fh "%02d:%02d")
17087 y d h m align)
17088 (if havetime
17089 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17091 d (floor (/ diff ds)) diff (mod diff ds)
17092 h (floor (/ diff hs)) diff (mod diff hs)
17093 m (floor (/ diff 60)))
17094 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17096 d (floor (+ (/ diff ds) 0.5))
17097 h 0 m 0))
17098 (if (not to-buffer)
17099 (message "%s" (org-make-tdiff-string y d h m))
17100 (if (org-at-table-p)
17101 (progn
17102 (goto-char match-end)
17103 (setq align t)
17104 (and (looking-at " *|") (goto-char (match-end 0))))
17105 (goto-char match-end))
17106 (if (looking-at
17107 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17108 (replace-match ""))
17109 (if negative (insert " -"))
17110 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17111 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17112 (insert " " (format fh h m))))
17113 (if align (org-table-align))
17114 (message "Time difference inserted")))))
17116 (defun org-make-tdiff-string (y d h m)
17117 (let ((fmt "")
17118 (l nil))
17119 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
17120 l (push y l)))
17121 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
17122 l (push d l)))
17123 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
17124 l (push h l)))
17125 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
17126 l (push m l)))
17127 (apply 'format fmt (nreverse l))))
17129 (defun org-time-string-to-time (s &optional buffer pos)
17130 "Convert a timestamp string into internal time."
17131 (condition-case errdata
17132 (apply 'encode-time (org-parse-time-string s))
17133 (error (error "Bad timestamp `%s'%s\nError was: %s"
17134 s (if (not (and buffer pos))
17136 (format " at %d in buffer `%s'" pos buffer))
17137 (cdr errdata)))))
17139 (defun org-time-string-to-seconds (s)
17140 "Convert a timestamp string to a number of seconds."
17141 (org-float-time (org-time-string-to-time s)))
17143 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17144 "Convert a time stamp to an absolute day number.
17145 If there is a specifier for a cyclic time stamp, get the closest
17146 date to DAYNR.
17147 PREFER and SHOW-ALL are passed through to `org-closest-date'.
17148 The variable `date' is bound by the calendar when this is called."
17149 (cond
17150 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17151 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17152 daynr
17153 (+ daynr 1000)))
17154 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
17155 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17156 (time-to-days (current-time))) (match-string 0 s)
17157 prefer show-all))
17158 (t (time-to-days
17159 (condition-case errdata
17160 (apply 'encode-time (org-parse-time-string s))
17161 (error (error "Bad timestamp `%s'%s\nError was: %s"
17162 s (if (not (and buffer pos))
17164 (format " at %d in buffer `%s'" pos buffer))
17165 (cdr errdata))))))))
17167 (defun org-days-to-iso-week (days)
17168 "Return the iso week number."
17169 (require 'cal-iso)
17170 (car (calendar-iso-from-absolute days)))
17172 (defun org-small-year-to-year (year)
17173 "Convert 2-digit years into 4-digit years.
17174 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
17175 The year 2000 cannot be abbreviated. Any year larger than 99
17176 is returned unchanged."
17177 (if (< year 38)
17178 (setq year (+ 2000 year))
17179 (if (< year 100)
17180 (setq year (+ 1900 year))))
17181 year)
17183 (defun org-time-from-absolute (d)
17184 "Return the time corresponding to date D.
17185 D may be an absolute day number, or a calendar-type list (month day year)."
17186 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17187 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17189 (defun org-calendar-holiday ()
17190 "List of holidays, for Diary display in Org-mode."
17191 (require 'holidays)
17192 (let ((hl (funcall
17193 (if (fboundp 'calendar-check-holidays)
17194 'calendar-check-holidays 'check-calendar-holidays) date)))
17195 (if hl (mapconcat 'identity hl "; "))))
17197 (defun org-diary-sexp-entry (sexp entry date)
17198 "Process a SEXP diary ENTRY for DATE."
17199 (require 'diary-lib)
17200 (let ((result (if calendar-debug-sexp
17201 (let ((stack-trace-on-error t))
17202 (eval (car (read-from-string sexp))))
17203 (condition-case nil
17204 (eval (car (read-from-string sexp)))
17205 (error
17206 (beep)
17207 (message "Bad sexp at line %d in %s: %s"
17208 (org-current-line)
17209 (buffer-file-name) sexp)
17210 (sleep-for 2))))))
17211 (cond ((stringp result) (split-string result "; "))
17212 ((and (consp result)
17213 (not (consp (cdr result)))
17214 (stringp (cdr result))) (cdr result))
17215 ((and (consp result)
17216 (stringp (car result))) result)
17217 (result entry))))
17219 (defun org-diary-to-ical-string (frombuf)
17220 "Get iCalendar entries from diary entries in buffer FROMBUF.
17221 This uses the icalendar.el library."
17222 (let* ((tmpdir (if (featurep 'xemacs)
17223 (temp-directory)
17224 temporary-file-directory))
17225 (tmpfile (make-temp-name
17226 (expand-file-name "orgics" tmpdir)))
17227 buf rtn b e)
17228 (with-current-buffer frombuf
17229 (icalendar-export-region (point-min) (point-max) tmpfile)
17230 (setq buf (find-buffer-visiting tmpfile))
17231 (set-buffer buf)
17232 (goto-char (point-min))
17233 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17234 (setq b (match-beginning 0)))
17235 (goto-char (point-max))
17236 (if (re-search-backward "^END:VEVENT" nil t)
17237 (setq e (match-end 0)))
17238 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17239 (kill-buffer buf)
17240 (delete-file tmpfile)
17241 rtn))
17243 (defun org-closest-date (start current change prefer show-all)
17244 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17245 When PREFER is `past', return a date that is either CURRENT or past.
17246 When PREFER is `future', return a date that is either CURRENT or future.
17247 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17248 ;; Make the proper lists from the dates
17249 (catch 'exit
17250 (let ((a1 '(("h" . hour)
17251 ("d" . day)
17252 ("w" . week)
17253 ("m" . month)
17254 ("y" . year)))
17255 (shour (nth 2 (org-parse-time-string start)))
17256 dn dw sday cday n1 n2 n0
17257 d m y y1 y2 date1 date2 nmonths nm ny m2)
17259 (setq start (org-date-to-gregorian start)
17260 current (org-date-to-gregorian
17261 (if show-all
17262 current
17263 (time-to-days (current-time))))
17264 sday (calendar-absolute-from-gregorian start)
17265 cday (calendar-absolute-from-gregorian current))
17267 (if (<= cday sday) (throw 'exit sday))
17269 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17270 (setq dn (string-to-number (match-string 1 change))
17271 dw (cdr (assoc (match-string 2 change) a1)))
17272 (user-error "Invalid change specifier: %s" change))
17273 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17274 (cond
17275 ((eq dw 'hour)
17276 (let ((missing-hours
17277 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17278 dn)))
17279 (setq n1 (if (zerop missing-hours) cday
17280 (- cday (1+ (floor (/ missing-hours 24)))))
17281 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17282 ((eq dw 'day)
17283 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17284 n2 (+ n1 dn)))
17285 ((eq dw 'year)
17286 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17287 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17288 (setq date1 (list m d y1)
17289 n1 (calendar-absolute-from-gregorian date1)
17290 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17291 n2 (calendar-absolute-from-gregorian date2)))
17292 ((eq dw 'month)
17293 ;; approx number of month between the two dates
17294 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17295 ;; How often does dn fit in there?
17296 (setq d (nth 1 start) m (car start) y (nth 2 start)
17297 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17298 m (+ m nm)
17299 ny (floor (/ m 12))
17300 y (+ y ny)
17301 m (- m (* ny 12)))
17302 (while (> m 12) (setq m (- m 12) y (1+ y)))
17303 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17304 (setq m2 (+ m dn) y2 y)
17305 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17306 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17307 (while (<= n2 cday)
17308 (setq n1 n2 m m2 y y2)
17309 (setq m2 (+ m dn) y2 y)
17310 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17311 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17312 ;; Make sure n1 is the earlier date
17313 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17314 (if show-all
17315 (cond
17316 ((eq prefer 'past) (if (= cday n2) n2 n1))
17317 ((eq prefer 'future) (if (= cday n1) n1 n2))
17318 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17319 (cond
17320 ((eq prefer 'past) (if (= cday n2) n2 n1))
17321 ((eq prefer 'future) (if (= cday n1) n1 n2))
17322 (t (if (= cday n1) n1 n2)))))))
17324 (defun org-date-to-gregorian (date)
17325 "Turn any specification of DATE into a Gregorian date for the calendar."
17326 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17327 ((and (listp date) (= (length date) 3)) date)
17328 ((stringp date)
17329 (setq date (org-parse-time-string date))
17330 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17331 ((listp date)
17332 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17334 (defun org-parse-time-string (s &optional nodefault)
17335 "Parse the standard Org-mode time string.
17336 This should be a lot faster than the normal `parse-time-string'.
17337 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17338 hour and minute fields will be nil if not given."
17339 (cond ((string-match org-ts-regexp0 s)
17340 (list 0
17341 (if (or (match-beginning 8) (not nodefault))
17342 (string-to-number (or (match-string 8 s) "0")))
17343 (if (or (match-beginning 7) (not nodefault))
17344 (string-to-number (or (match-string 7 s) "0")))
17345 (string-to-number (match-string 4 s))
17346 (string-to-number (match-string 3 s))
17347 (string-to-number (match-string 2 s))
17348 nil nil nil))
17349 ((string-match "^<[^>]+>$" s)
17350 (decode-time (seconds-to-time (org-matcher-time s))))
17351 (t (error "Not a standard Org-mode time string: %s" s))))
17353 (defun org-timestamp-up (&optional arg)
17354 "Increase the date item at the cursor by one.
17355 If the cursor is on the year, change the year. If it is on the month,
17356 the day or the time, change that.
17357 With prefix ARG, change by that many units."
17358 (interactive "p")
17359 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17361 (defun org-timestamp-down (&optional arg)
17362 "Decrease the date item at the cursor by one.
17363 If the cursor is on the year, change the year. If it is on the month,
17364 the day or the time, change that.
17365 With prefix ARG, change by that many units."
17366 (interactive "p")
17367 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17369 (defun org-timestamp-up-day (&optional arg)
17370 "Increase the date in the time stamp by one day.
17371 With prefix ARG, change that many days."
17372 (interactive "p")
17373 (if (and (not (org-at-timestamp-p t))
17374 (org-at-heading-p))
17375 (org-todo 'up)
17376 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17378 (defun org-timestamp-down-day (&optional arg)
17379 "Decrease the date in the time stamp by one day.
17380 With prefix ARG, change that many days."
17381 (interactive "p")
17382 (if (and (not (org-at-timestamp-p t))
17383 (org-at-heading-p))
17384 (org-todo 'down)
17385 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17387 (defun org-at-timestamp-p (&optional inactive-ok)
17388 "Determine if the cursor is in or at a timestamp."
17389 (interactive)
17390 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17391 (pos (point))
17392 (ans (or (looking-at tsr)
17393 (save-excursion
17394 (skip-chars-backward "^[<\n\r\t")
17395 (if (> (point) (point-min)) (backward-char 1))
17396 (and (looking-at tsr)
17397 (> (- (match-end 0) pos) -1))))))
17398 (and ans
17399 (boundp 'org-ts-what)
17400 (setq org-ts-what
17401 (cond
17402 ((= pos (match-beginning 0)) 'bracket)
17403 ;; Point is considered to be "on the bracket" whether
17404 ;; it's really on it or right after it.
17405 ((= pos (1- (match-end 0))) 'bracket)
17406 ((= pos (match-end 0)) 'after)
17407 ((org-pos-in-match-range pos 2) 'year)
17408 ((org-pos-in-match-range pos 3) 'month)
17409 ((org-pos-in-match-range pos 7) 'hour)
17410 ((org-pos-in-match-range pos 8) 'minute)
17411 ((or (org-pos-in-match-range pos 4)
17412 (org-pos-in-match-range pos 5)) 'day)
17413 ((and (> pos (or (match-end 8) (match-end 5)))
17414 (< pos (match-end 0)))
17415 (- pos (or (match-end 8) (match-end 5))))
17416 (t 'day))))
17417 ans))
17419 (defun org-toggle-timestamp-type ()
17420 "Toggle the type (<active> or [inactive]) of a time stamp."
17421 (interactive)
17422 (when (org-at-timestamp-p t)
17423 (let ((beg (match-beginning 0)) (end (match-end 0))
17424 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17425 (save-excursion
17426 (goto-char beg)
17427 (while (re-search-forward "[][<>]" end t)
17428 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17429 t t)))
17430 (message "Timestamp is now %sactive"
17431 (if (equal (char-after beg) ?<) "" "in")))))
17433 (defun org-at-clock-log-p nil
17434 "Is the cursor on the clock log line?"
17435 (save-excursion
17436 (move-beginning-of-line 1)
17437 (looking-at "^[ \t]*CLOCK:")))
17439 (defvar org-clock-history) ; defined in org-clock.el
17440 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17441 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17442 "Change the date in the time stamp at point.
17443 The date will be changed by N times WHAT. WHAT can be `day', `month',
17444 `year', `minute', `second'. If WHAT is not given, the cursor position
17445 in the timestamp determines what will be changed.
17446 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17447 (let ((origin (point)) origin-cat
17448 with-hm inactive
17449 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17450 org-ts-what
17451 extra rem
17452 ts time time0 fixnext clrgx)
17453 (if (not (org-at-timestamp-p t))
17454 (user-error "Not at a timestamp"))
17455 (if (and (not what) (eq org-ts-what 'bracket))
17456 (org-toggle-timestamp-type)
17457 ;; Point isn't on brackets. Remember the part of the time-stamp
17458 ;; the point was in. Indeed, size of time-stamps may change,
17459 ;; but point must be kept in the same category nonetheless.
17460 (setq origin-cat org-ts-what)
17461 (if (and (not what) (not (eq org-ts-what 'day))
17462 org-display-custom-times
17463 (get-text-property (point) 'display)
17464 (not (get-text-property (1- (point)) 'display)))
17465 (setq org-ts-what 'day))
17466 (setq org-ts-what (or what org-ts-what)
17467 inactive (= (char-after (match-beginning 0)) ?\[)
17468 ts (match-string 0))
17469 (replace-match "")
17470 (when (string-match
17471 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17473 (setq extra (match-string 1 ts))
17474 (if suppress-tmp-delay
17475 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17476 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17477 (setq with-hm t))
17478 (setq time0 (org-parse-time-string ts))
17479 (when (and updown
17480 (eq org-ts-what 'minute)
17481 (not current-prefix-arg))
17482 ;; This looks like s-up and s-down. Change by one rounding step.
17483 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17484 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17485 (setcar (cdr time0) (+ (nth 1 time0)
17486 (if (> n 0) (- rem) (- dm rem))))))
17487 (setq time
17488 (encode-time (or (car time0) 0)
17489 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17490 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17491 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17492 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17493 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17494 (nthcdr 6 time0)))
17495 (when (and (member org-ts-what '(hour minute))
17496 extra
17497 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17498 (setq extra (org-modify-ts-extra
17499 extra
17500 (if (eq org-ts-what 'hour) 2 5)
17501 n dm)))
17502 (when (integerp org-ts-what)
17503 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17504 (if (eq what 'calendar)
17505 (let ((cal-date (org-get-date-from-calendar)))
17506 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17507 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17508 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17509 (setcar time0 (or (car time0) 0))
17510 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17511 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17512 (setq time (apply 'encode-time time0))))
17513 ;; Insert the new time-stamp, and ensure point stays in the same
17514 ;; category as before (i.e. not after the last position in that
17515 ;; category).
17516 (let ((pos (point)))
17517 ;; Stay before inserted string. `save-excursion' is of no use.
17518 (setq org-last-changed-timestamp
17519 (org-insert-time-stamp time with-hm inactive nil nil extra))
17520 (goto-char pos))
17521 (save-match-data
17522 (looking-at org-ts-regexp3)
17523 (goto-char (cond
17524 ;; `day' category ends before `hour' if any, or at
17525 ;; the end of the day name.
17526 ((eq origin-cat 'day)
17527 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17528 ((eq origin-cat 'hour) (min (match-end 7) origin))
17529 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17530 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17531 ;; `year' and `month' have both fixed size: point
17532 ;; couldn't have moved into another part.
17533 (t origin))))
17534 ;; Update clock if on a CLOCK line.
17535 (org-clock-update-time-maybe)
17536 ;; Maybe adjust the closest clock in `org-clock-history'
17537 (when org-clock-adjust-closest
17538 (if (not (and (org-at-clock-log-p)
17539 (< 1 (length (delq nil (mapcar 'marker-position
17540 org-clock-history))))))
17541 (message "No clock to adjust")
17542 (cond ((save-excursion ; fix previous clock?
17543 (re-search-backward org-ts-regexp0 nil t)
17544 (org-looking-back (concat org-clock-string " \\[")))
17545 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17546 ((save-excursion ; fix next clock?
17547 (re-search-backward org-ts-regexp0 nil t)
17548 (looking-at (concat org-ts-regexp0 "\\] =>")))
17549 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17550 (save-window-excursion
17551 ;; Find closest clock to point, adjust the previous/next one in history
17552 (let* ((p (save-excursion (org-back-to-heading t)))
17553 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17554 (clfixnth
17555 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17556 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17557 (if (not clfixpos)
17558 (message "No clock to adjust")
17559 (save-excursion
17560 (org-goto-marker-or-bmk clfixpos)
17561 (org-show-subtree)
17562 (when (re-search-forward clrgx nil t)
17563 (goto-char (match-beginning 1))
17564 (let (org-clock-adjust-closest)
17565 (org-timestamp-change n org-ts-what updown))
17566 (message "Clock adjusted in %s for heading: %s"
17567 (file-name-nondirectory (buffer-file-name))
17568 (org-get-heading t t)))))))))
17569 ;; Try to recenter the calendar window, if any.
17570 (if (and org-calendar-follow-timestamp-change
17571 (get-buffer-window "*Calendar*" t)
17572 (memq org-ts-what '(day month year)))
17573 (org-recenter-calendar (time-to-days time))))))
17575 (defun org-modify-ts-extra (s pos n dm)
17576 "Change the different parts of the lead-time and repeat fields in timestamp."
17577 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17578 ng h m new rem)
17579 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17580 (cond
17581 ((or (org-pos-in-match-range pos 2)
17582 (org-pos-in-match-range pos 3))
17583 (setq m (string-to-number (match-string 3 s))
17584 h (string-to-number (match-string 2 s)))
17585 (if (org-pos-in-match-range pos 2)
17586 (setq h (+ h n))
17587 (setq n (* dm (org-no-warnings (signum n))))
17588 (when (not (= 0 (setq rem (% m dm))))
17589 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17590 (setq m (+ m n)))
17591 (if (< m 0) (setq m (+ m 60) h (1- h)))
17592 (if (> m 59) (setq m (- m 60) h (1+ h)))
17593 (setq h (min 24 (max 0 h)))
17594 (setq ng 1 new (format "-%02d:%02d" h m)))
17595 ((org-pos-in-match-range pos 6)
17596 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17597 ((org-pos-in-match-range pos 5)
17598 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17600 ((org-pos-in-match-range pos 9)
17601 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17602 ((org-pos-in-match-range pos 8)
17603 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17605 (when ng
17606 (setq s (concat
17607 (substring s 0 (match-beginning ng))
17609 (substring s (match-end ng))))))
17612 (defun org-recenter-calendar (date)
17613 "If the calendar is visible, recenter it to DATE."
17614 (let ((cwin (get-buffer-window "*Calendar*" t)))
17615 (when cwin
17616 (let ((calendar-move-hook nil))
17617 (with-selected-window cwin
17618 (calendar-goto-date (if (listp date) date
17619 (calendar-gregorian-from-absolute date))))))))
17621 (defun org-goto-calendar (&optional arg)
17622 "Go to the Emacs calendar at the current date.
17623 If there is a time stamp in the current line, go to that date.
17624 A prefix ARG can be used to force the current date."
17625 (interactive "P")
17626 (let ((tsr org-ts-regexp) diff
17627 (calendar-move-hook nil)
17628 (calendar-view-holidays-initially-flag nil)
17629 (calendar-view-diary-initially-flag nil))
17630 (if (or (org-at-timestamp-p)
17631 (save-excursion
17632 (beginning-of-line 1)
17633 (looking-at (concat ".*" tsr))))
17634 (let ((d1 (time-to-days (current-time)))
17635 (d2 (time-to-days
17636 (org-time-string-to-time (match-string 1)))))
17637 (setq diff (- d2 d1))))
17638 (calendar)
17639 (calendar-goto-today)
17640 (if (and diff (not arg)) (calendar-forward-day diff))))
17642 (defun org-get-date-from-calendar ()
17643 "Return a list (month day year) of date at point in calendar."
17644 (with-current-buffer "*Calendar*"
17645 (save-match-data
17646 (calendar-cursor-to-date))))
17648 (defun org-date-from-calendar ()
17649 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17650 If there is already a time stamp at the cursor position, update it."
17651 (interactive)
17652 (if (org-at-timestamp-p t)
17653 (org-timestamp-change 0 'calendar)
17654 (let ((cal-date (org-get-date-from-calendar)))
17655 (org-insert-time-stamp
17656 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17658 (defcustom org-effort-durations
17659 `(("h" . 60)
17660 ("d" . ,(* 60 8))
17661 ("w" . ,(* 60 8 5))
17662 ("m" . ,(* 60 8 5 4))
17663 ("y" . ,(* 60 8 5 40)))
17664 "Conversion factor to minutes for an effort modifier.
17666 Each entry has the form (MODIFIER . MINUTES).
17668 In an effort string, a number followed by MODIFIER is multiplied
17669 by the specified number of MINUTES to obtain an effort in
17670 minutes.
17672 For example, if the value of this variable is ((\"hours\" . 60)), then an
17673 effort string \"2hours\" is equivalent to 120 minutes."
17674 :group 'org-agenda
17675 :version "24.1"
17676 :type '(alist :key-type (string :tag "Modifier")
17677 :value-type (number :tag "Minutes")))
17679 (defun org-minutes-to-clocksum-string (m)
17680 "Format number of minutes as a clocksum string.
17681 The format is determined by `org-time-clocksum-format',
17682 `org-time-clocksum-use-fractional' and
17683 `org-time-clocksum-fractional-format' and
17684 `org-time-clocksum-use-effort-durations'."
17685 (let ((clocksum "")
17686 (m (round m)) ; Don't allow fractions of minutes
17687 h d w mo y fmt n)
17688 (setq h (if org-time-clocksum-use-effort-durations
17689 (cdr (assoc "h" org-effort-durations)) 60)
17690 d (if org-time-clocksum-use-effort-durations
17691 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17692 w (if org-time-clocksum-use-effort-durations
17693 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17694 mo (if org-time-clocksum-use-effort-durations
17695 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17696 y (if org-time-clocksum-use-effort-durations
17697 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17698 ;; fractional format
17699 (if org-time-clocksum-use-fractional
17700 (cond
17701 ;; single format string
17702 ((stringp org-time-clocksum-fractional-format)
17703 (format org-time-clocksum-fractional-format (/ m (float h))))
17704 ;; choice of fractional formats for different time units
17705 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17706 (> (/ (truncate m) (* y d h)) 0))
17707 (format fmt (/ m (* y d (float h)))))
17708 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17709 (> (/ (truncate m) (* mo d h)) 0))
17710 (format fmt (/ m (* mo d (float h)))))
17711 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17712 (> (/ (truncate m) (* w d h)) 0))
17713 (format fmt (/ m (* w d (float h)))))
17714 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17715 (> (/ (truncate m) (* d h)) 0))
17716 (format fmt (/ m (* d (float h)))))
17717 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17718 (> (/ (truncate m) h) 0))
17719 (format fmt (/ m (float h))))
17720 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17721 (format fmt m))
17722 ;; fall back to smallest time unit with a format
17723 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17724 (format fmt (/ m (float h))))
17725 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17726 (format fmt (/ m (* d (float h)))))
17727 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17728 (format fmt (/ m (* w d (float h)))))
17729 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17730 (format fmt (/ m (* mo d (float h)))))
17731 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17732 (format fmt (/ m (* y d (float h))))))
17733 ;; standard (non-fractional) format, with single format string
17734 (if (stringp org-time-clocksum-format)
17735 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17736 ;; separate formats components
17737 (and (setq fmt (plist-get org-time-clocksum-format :years))
17738 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17739 (plist-get org-time-clocksum-format :require-years))
17740 (setq clocksum (concat clocksum (format fmt n))
17741 m (- m (* n y d h))))
17742 (and (setq fmt (plist-get org-time-clocksum-format :months))
17743 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17744 (plist-get org-time-clocksum-format :require-months))
17745 (setq clocksum (concat clocksum (format fmt n))
17746 m (- m (* n mo d h))))
17747 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17748 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17749 (plist-get org-time-clocksum-format :require-weeks))
17750 (setq clocksum (concat clocksum (format fmt n))
17751 m (- m (* n w d h))))
17752 (and (setq fmt (plist-get org-time-clocksum-format :days))
17753 (or (> (setq n (/ (truncate m) (* d h))) 0)
17754 (plist-get org-time-clocksum-format :require-days))
17755 (setq clocksum (concat clocksum (format fmt n))
17756 m (- m (* n d h))))
17757 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17758 (or (> (setq n (/ (truncate m) h)) 0)
17759 (plist-get org-time-clocksum-format :require-hours))
17760 (setq clocksum (concat clocksum (format fmt n))
17761 m (- m (* n h))))
17762 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17763 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17764 (setq clocksum (concat clocksum (format fmt m))))
17765 ;; return formatted time duration
17766 clocksum))))
17768 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17769 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17770 "Org mode version 8.0")
17772 (defun org-hours-to-clocksum-string (n)
17773 (org-minutes-to-clocksum-string (* n 60)))
17775 (defun org-hh:mm-string-to-minutes (s)
17776 "Convert a string H:MM to a number of minutes.
17777 If the string is just a number, interpret it as minutes.
17778 In fact, the first hh:mm or number in the string will be taken,
17779 there can be extra stuff in the string.
17780 If no number is found, the return value is 0."
17781 (cond
17782 ((integerp s) s)
17783 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17784 (+ (* (string-to-number (match-string 1 s)) 60)
17785 (string-to-number (match-string 2 s))))
17786 ((string-match "\\([0-9]+\\)" s)
17787 (string-to-number (match-string 1 s)))
17788 (t 0)))
17790 (defcustom org-image-actual-width t
17791 "Should we use the actual width of images when inlining them?
17793 When set to `t', always use the image width.
17795 When set to a number, use imagemagick (when available) to set
17796 the image's width to this value.
17798 When set to a number in a list, try to get the width from any
17799 #+ATTR.* keyword if it matches a width specification like
17801 #+ATTR_HTML: :width 300px
17803 and fall back on that number if none is found.
17805 When set to nil, try to get the width from an #+ATTR.* keyword
17806 and fall back on the original width if none is found.
17808 This requires Emacs >= 24.1, build with imagemagick support."
17809 :group 'org-appearance
17810 :version "24.4"
17811 :package-version '(Org . "8.0")
17812 :type '(choice
17813 (const :tag "Use the image width" t)
17814 (integer :tag "Use a number of pixels")
17815 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17816 (const :tag "Use #+ATTR* or don't resize" nil)))
17818 (defcustom org-agenda-inhibit-startup nil
17819 "Inhibit startup when preparing agenda buffers.
17820 When this variable is `t' (the default), the initialization of
17821 the Org agenda buffers is inhibited: e.g. the visibility state
17822 is not set, the tables are not re-aligned, etc."
17823 :type 'boolean
17824 :version "24.3"
17825 :group 'org-agenda)
17827 (defcustom org-agenda-ignore-drawer-properties nil
17828 "Avoid updating text properties when building the agenda.
17829 Properties are used to prepare buffers for effort estimates, appointments,
17830 and subtree-local categories.
17831 If you don't use these in the agenda, you can add them to this list and
17832 agenda building will be a bit faster.
17833 The value is a list, with zero or more of the symbols `effort', `appt',
17834 or `category'."
17835 :type '(set :greedy t
17836 (const effort)
17837 (const appt)
17838 (const category))
17839 :version "24.3"
17840 :group 'org-agenda)
17842 (defun org-duration-string-to-minutes (s &optional output-to-string)
17843 "Convert a duration string S to minutes.
17845 A bare number is interpreted as minutes, modifiers can be set by
17846 customizing `org-effort-durations' (which see).
17848 Entries containing a colon are interpreted as H:MM by
17849 `org-hh:mm-string-to-minutes'."
17850 (let ((result 0)
17851 (re (concat "\\([0-9.]+\\) *\\("
17852 (regexp-opt (mapcar 'car org-effort-durations))
17853 "\\)")))
17854 (while (string-match re s)
17855 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17856 (string-to-number (match-string 1 s))))
17857 (setq s (replace-match "" nil t s)))
17858 (setq result (floor result))
17859 (incf result (org-hh:mm-string-to-minutes s))
17860 (if output-to-string (number-to-string result) result)))
17862 ;;;; Files
17864 (defun org-save-all-org-buffers ()
17865 "Save all Org-mode buffers without user confirmation."
17866 (interactive)
17867 (message "Saving all Org-mode buffers...")
17868 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17869 (when (featurep 'org-id) (org-id-locations-save))
17870 (message "Saving all Org-mode buffers... done"))
17872 (defun org-revert-all-org-buffers ()
17873 "Revert all Org-mode buffers.
17874 Prompt for confirmation when there are unsaved changes.
17875 Be sure you know what you are doing before letting this function
17876 overwrite your changes.
17878 This function is useful in a setup where one tracks org files
17879 with a version control system, to revert on one machine after pulling
17880 changes from another. I believe the procedure must be like this:
17882 1. M-x org-save-all-org-buffers
17883 2. Pull changes from the other machine, resolve conflicts
17884 3. M-x org-revert-all-org-buffers"
17885 (interactive)
17886 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17887 (user-error "Abort"))
17888 (save-excursion
17889 (save-window-excursion
17890 (mapc
17891 (lambda (b)
17892 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17893 (with-current-buffer b buffer-file-name))
17894 (org-pop-to-buffer-same-window b)
17895 (revert-buffer t 'no-confirm)))
17896 (buffer-list))
17897 (when (and (featurep 'org-id) org-id-track-globally)
17898 (org-id-locations-load)))))
17900 ;;;; Agenda files
17902 ;;;###autoload
17903 (defun org-switchb (&optional arg)
17904 "Switch between Org buffers.
17905 With one prefix argument, restrict available buffers to files.
17906 With two prefix arguments, restrict available buffers to agenda files.
17908 Defaults to `iswitchb' for buffer name completion.
17909 Set `org-completion-use-ido' to make it use ido instead."
17910 (interactive "P")
17911 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17912 ((equal arg '(16)) (org-buffer-list 'agenda))
17913 (t (org-buffer-list))))
17914 (org-completion-use-iswitchb org-completion-use-iswitchb)
17915 (org-completion-use-ido org-completion-use-ido))
17916 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17917 (setq org-completion-use-iswitchb t))
17918 (org-pop-to-buffer-same-window
17919 (org-icompleting-read "Org buffer: "
17920 (mapcar 'list (mapcar 'buffer-name blist))
17921 nil t))))
17923 ;;; Define some older names previously used for this functionality
17924 ;;;###autoload
17925 (defalias 'org-ido-switchb 'org-switchb)
17926 ;;;###autoload
17927 (defalias 'org-iswitchb 'org-switchb)
17929 (defun org-buffer-list (&optional predicate exclude-tmp)
17930 "Return a list of Org buffers.
17931 PREDICATE can be `export', `files' or `agenda'.
17933 export restrict the list to Export buffers.
17934 files restrict the list to buffers visiting Org files.
17935 agenda restrict the list to buffers visiting agenda files.
17937 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17938 (let* ((bfn nil)
17939 (agenda-files (and (eq predicate 'agenda)
17940 (mapcar 'file-truename (org-agenda-files t))))
17941 (filter
17942 (cond
17943 ((eq predicate 'files)
17944 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17945 ((eq predicate 'export)
17946 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17947 ((eq predicate 'agenda)
17948 (lambda (b)
17949 (with-current-buffer b
17950 (and (derived-mode-p 'org-mode)
17951 (setq bfn (buffer-file-name b))
17952 (member (file-truename bfn) agenda-files)))))
17953 (t (lambda (b) (with-current-buffer b
17954 (or (derived-mode-p 'org-mode)
17955 (string-match "\*Org .*Export"
17956 (buffer-name b)))))))))
17957 (delq nil
17958 (mapcar
17959 (lambda(b)
17960 (if (and (funcall filter b)
17961 (or (not exclude-tmp)
17962 (not (string-match "tmp" (buffer-name b)))))
17964 nil))
17965 (buffer-list)))))
17967 (defun org-agenda-files (&optional unrestricted archives)
17968 "Get the list of agenda files.
17969 Optional UNRESTRICTED means return the full list even if a restriction
17970 is currently in place.
17971 When ARCHIVES is t, include all archive files that are really being
17972 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17973 `org-agenda-archives-mode' is t."
17974 (let ((files
17975 (cond
17976 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17977 ((stringp org-agenda-files) (org-read-agenda-file-list))
17978 ((listp org-agenda-files) org-agenda-files)
17979 (t (error "Invalid value of `org-agenda-files'")))))
17980 (setq files (apply 'append
17981 (mapcar (lambda (f)
17982 (if (file-directory-p f)
17983 (directory-files
17984 f t org-agenda-file-regexp)
17985 (list f)))
17986 files)))
17987 (when org-agenda-skip-unavailable-files
17988 (setq files (delq nil
17989 (mapcar (function
17990 (lambda (file)
17991 (and (file-readable-p file) file)))
17992 files))))
17993 (when (or (eq archives t)
17994 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17995 (setq files (org-add-archive-files files)))
17996 files))
17998 (defun org-agenda-file-p (&optional file)
17999 "Return non-nil, if FILE is an agenda file.
18000 If FILE is omitted, use the file associated with the current
18001 buffer."
18002 (member (or file (buffer-file-name))
18003 (org-agenda-files t)))
18005 (defun org-edit-agenda-file-list ()
18006 "Edit the list of agenda files.
18007 Depending on setup, this either uses customize to edit the variable
18008 `org-agenda-files', or it visits the file that is holding the list. In the
18009 latter case, the buffer is set up in a way that saving it automatically kills
18010 the buffer and restores the previous window configuration."
18011 (interactive)
18012 (if (stringp org-agenda-files)
18013 (let ((cw (current-window-configuration)))
18014 (find-file org-agenda-files)
18015 (org-set-local 'org-window-configuration cw)
18016 (org-add-hook 'after-save-hook
18017 (lambda ()
18018 (set-window-configuration
18019 (prog1 org-window-configuration
18020 (kill-buffer (current-buffer))))
18021 (org-install-agenda-files-menu)
18022 (message "New agenda file list installed"))
18023 nil 'local)
18024 (message "%s" (substitute-command-keys
18025 "Edit list and finish with \\[save-buffer]")))
18026 (customize-variable 'org-agenda-files)))
18028 (defun org-store-new-agenda-file-list (list)
18029 "Set new value for the agenda file list and save it correctly."
18030 (if (stringp org-agenda-files)
18031 (let ((fe (org-read-agenda-file-list t)) b u)
18032 (while (setq b (find-buffer-visiting org-agenda-files))
18033 (kill-buffer b))
18034 (with-temp-file org-agenda-files
18035 (insert
18036 (mapconcat
18037 (lambda (f) ;; Keep un-expanded entries.
18038 (if (setq u (assoc f fe))
18039 (cdr u)
18041 list "\n")
18042 "\n")))
18043 (let ((org-mode-hook nil) (org-inhibit-startup t)
18044 (org-insert-mode-line-in-empty-file nil))
18045 (setq org-agenda-files list)
18046 (customize-save-variable 'org-agenda-files org-agenda-files))))
18048 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18049 "Read the list of agenda files from a file.
18050 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18051 filenames, used by `org-store-new-agenda-file-list' to write back
18052 un-expanded file names."
18053 (when (file-directory-p org-agenda-files)
18054 (error "`org-agenda-files' cannot be a single directory"))
18055 (when (stringp org-agenda-files)
18056 (with-temp-buffer
18057 (insert-file-contents org-agenda-files)
18058 (mapcar
18059 (lambda (f)
18060 (let ((e (expand-file-name (substitute-in-file-name f)
18061 org-directory)))
18062 (if pair-with-expansion
18063 (cons e f)
18064 e)))
18065 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18067 ;;;###autoload
18068 (defun org-cycle-agenda-files ()
18069 "Cycle through the files in `org-agenda-files'.
18070 If the current buffer visits an agenda file, find the next one in the list.
18071 If the current buffer does not, find the first agenda file."
18072 (interactive)
18073 (let* ((fs (org-agenda-files t))
18074 (files (append fs (list (car fs))))
18075 (tcf (if buffer-file-name (file-truename buffer-file-name)))
18076 file)
18077 (unless files (user-error "No agenda files"))
18078 (catch 'exit
18079 (while (setq file (pop files))
18080 (if (equal (file-truename file) tcf)
18081 (when (car files)
18082 (find-file (car files))
18083 (throw 'exit t))))
18084 (find-file (car fs)))
18085 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
18087 (defun org-agenda-file-to-front (&optional to-end)
18088 "Move/add the current file to the top of the agenda file list.
18089 If the file is not present in the list, it is added to the front. If it is
18090 present, it is moved there. With optional argument TO-END, add/move to the
18091 end of the list."
18092 (interactive "P")
18093 (let ((org-agenda-skip-unavailable-files nil)
18094 (file-alist (mapcar (lambda (x)
18095 (cons (file-truename x) x))
18096 (org-agenda-files t)))
18097 (ctf (file-truename
18098 (or buffer-file-name
18099 (user-error "Please save the current buffer to a file"))))
18100 x had)
18101 (setq x (assoc ctf file-alist) had x)
18103 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18104 (if to-end
18105 (setq file-alist (append (delq x file-alist) (list x)))
18106 (setq file-alist (cons x (delq x file-alist))))
18107 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18108 (org-install-agenda-files-menu)
18109 (message "File %s to %s of agenda file list"
18110 (if had "moved" "added") (if to-end "end" "front"))))
18112 (defun org-remove-file (&optional file)
18113 "Remove current file from the list of files in variable `org-agenda-files'.
18114 These are the files which are being checked for agenda entries.
18115 Optional argument FILE means use this file instead of the current."
18116 (interactive)
18117 (let* ((org-agenda-skip-unavailable-files nil)
18118 (file (or file buffer-file-name
18119 (user-error "Current buffer does not visit a file")))
18120 (true-file (file-truename file))
18121 (afile (abbreviate-file-name file))
18122 (files (delq nil (mapcar
18123 (lambda (x)
18124 (if (equal true-file
18125 (file-truename x))
18126 nil x))
18127 (org-agenda-files t)))))
18128 (if (not (= (length files) (length (org-agenda-files t))))
18129 (progn
18130 (org-store-new-agenda-file-list files)
18131 (org-install-agenda-files-menu)
18132 (message "Removed file: %s" afile))
18133 (message "File was not in list: %s (not removed)" afile))))
18135 (defun org-file-menu-entry (file)
18136 (vector file (list 'find-file file) t))
18138 (defun org-check-agenda-file (file)
18139 "Make sure FILE exists. If not, ask user what to do."
18140 (when (not (file-exists-p file))
18141 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18142 (abbreviate-file-name file))
18143 (let ((r (downcase (read-char-exclusive))))
18144 (cond
18145 ((equal r ?r)
18146 (org-remove-file file)
18147 (throw 'nextfile t))
18148 (t (error "Abort"))))))
18150 (defun org-get-agenda-file-buffer (file)
18151 "Get a buffer visiting FILE. If the buffer needs to be created, add
18152 it to the list of buffers which might be released later."
18153 (let ((buf (org-find-base-buffer-visiting file)))
18154 (if buf
18155 buf ; just return it
18156 ;; Make a new buffer and remember it
18157 (setq buf (find-file-noselect file))
18158 (if buf (push buf org-agenda-new-buffers))
18159 buf)))
18161 (defun org-release-buffers (blist)
18162 "Release all buffers in list, asking the user for confirmation when needed.
18163 When a buffer is unmodified, it is just killed. When modified, it is saved
18164 \(if the user agrees) and then killed."
18165 (let (buf file)
18166 (while (setq buf (pop blist))
18167 (setq file (buffer-file-name buf))
18168 (when (and (buffer-modified-p buf)
18169 file
18170 (y-or-n-p (format "Save file %s? " file)))
18171 (with-current-buffer buf (save-buffer)))
18172 (kill-buffer buf))))
18174 (defun org-agenda-prepare-buffers (files)
18175 "Create buffers for all agenda files, protect archived trees and comments."
18176 (interactive)
18177 (let ((pa '(:org-archived t))
18178 (pc '(:org-comment t))
18179 (pall '(:org-archived t :org-comment t))
18180 (inhibit-read-only t)
18181 (org-inhibit-startup org-agenda-inhibit-startup)
18182 (rea (concat ":" org-archive-tag ":"))
18183 file re pos)
18184 (setq org-tag-alist-for-agenda nil
18185 org-tag-groups-alist-for-agenda nil)
18186 (save-excursion
18187 (save-restriction
18188 (while (setq file (pop files))
18189 (catch 'nextfile
18190 (if (bufferp file)
18191 (set-buffer file)
18192 (org-check-agenda-file file)
18193 (set-buffer (org-get-agenda-file-buffer file)))
18194 (widen)
18195 (org-set-regexps-and-options-for-tags)
18196 (setq pos (point))
18197 (goto-char (point-min))
18198 (let ((case-fold-search t))
18199 (when (search-forward "#+setupfile" nil t)
18200 ;; Don't set all regexps and options systematically as
18201 ;; this is only run for setting agenda tags from setup
18202 ;; file
18203 (org-set-regexps-and-options)))
18204 (or (memq 'category org-agenda-ignore-drawer-properties)
18205 (org-refresh-category-properties))
18206 (or (memq 'effort org-agenda-ignore-drawer-properties)
18207 (org-refresh-properties org-effort-property 'org-effort))
18208 (or (memq 'appt org-agenda-ignore-drawer-properties)
18209 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18210 (setq org-todo-keywords-for-agenda
18211 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18212 (setq org-done-keywords-for-agenda
18213 (append org-done-keywords-for-agenda org-done-keywords))
18214 (setq org-todo-keyword-alist-for-agenda
18215 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18216 (setq org-tag-alist-for-agenda
18217 (org-uniquify
18218 (append org-tag-alist-for-agenda
18219 org-tag-alist
18220 org-tag-persistent-alist)))
18221 (if org-group-tags
18222 (setq org-tag-groups-alist-for-agenda
18223 (org-uniquify-alist
18224 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18225 (org-with-silent-modifications
18226 (save-excursion
18227 (remove-text-properties (point-min) (point-max) pall)
18228 (when org-agenda-skip-archived-trees
18229 (goto-char (point-min))
18230 (while (re-search-forward rea nil t)
18231 (if (org-at-heading-p t)
18232 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18233 (goto-char (point-min))
18234 (setq re (format org-heading-keyword-regexp-format
18235 org-comment-string))
18236 (while (re-search-forward re nil t)
18237 (add-text-properties
18238 (match-beginning 0) (org-end-of-subtree t) pc))))
18239 (goto-char pos)))))
18240 (setq org-todo-keywords-for-agenda
18241 (org-uniquify org-todo-keywords-for-agenda))
18242 (setq org-todo-keyword-alist-for-agenda
18243 (org-uniquify org-todo-keyword-alist-for-agenda))))
18246 ;;;; CDLaTeX minor mode
18248 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18249 "Keymap for the minor `org-cdlatex-mode'.")
18251 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18252 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18253 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18254 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18255 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
18257 (defvar org-cdlatex-texmathp-advice-is-done nil
18258 "Flag remembering if we have applied the advice to texmathp already.")
18260 (define-minor-mode org-cdlatex-mode
18261 "Toggle the minor `org-cdlatex-mode'.
18262 This mode supports entering LaTeX environment and math in LaTeX fragments
18263 in Org-mode.
18264 \\{org-cdlatex-mode-map}"
18265 nil " OCDL" nil
18266 (when org-cdlatex-mode
18267 (require 'cdlatex)
18268 (run-hooks 'cdlatex-mode-hook)
18269 (cdlatex-compute-tables))
18270 (unless org-cdlatex-texmathp-advice-is-done
18271 (setq org-cdlatex-texmathp-advice-is-done t)
18272 (defadvice texmathp (around org-math-always-on activate)
18273 "Always return t in org-mode buffers.
18274 This is because we want to insert math symbols without dollars even outside
18275 the LaTeX math segments. If Orgmode thinks that point is actually inside
18276 an embedded LaTeX fragment, let texmathp do its job.
18277 \\[org-cdlatex-mode-map]"
18278 (interactive)
18279 (let (p)
18280 (cond
18281 ((not (derived-mode-p 'org-mode)) ad-do-it)
18282 ((eq this-command 'cdlatex-math-symbol)
18283 (setq ad-return-value t
18284 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18286 (let ((p (org-inside-LaTeX-fragment-p)))
18287 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18288 (setq ad-return-value t
18289 texmathp-why '("Org-mode embedded math" . 0))
18290 (if p ad-do-it)))))))))
18292 (defun turn-on-org-cdlatex ()
18293 "Unconditionally turn on `org-cdlatex-mode'."
18294 (org-cdlatex-mode 1))
18296 (defun org-try-cdlatex-tab ()
18297 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18298 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18299 - inside a LaTeX fragment, or
18300 - after the first word in a line, where an abbreviation expansion could
18301 insert a LaTeX environment."
18302 (when org-cdlatex-mode
18303 (cond
18304 ;; Before any word on the line: No expansion possible.
18305 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18306 ;; Just after first word on the line: Expand it. Make sure it
18307 ;; cannot happen on headlines, though.
18308 ((save-excursion
18309 (skip-chars-backward "a-zA-Z0-9*")
18310 (skip-chars-backward " \t")
18311 (and (bolp) (not (org-at-heading-p))))
18312 (cdlatex-tab) t)
18313 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18315 (defun org-cdlatex-underscore-caret (&optional arg)
18316 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18317 Revert to the normal definition outside of these fragments."
18318 (interactive "P")
18319 (if (org-inside-LaTeX-fragment-p)
18320 (call-interactively 'cdlatex-sub-superscript)
18321 (let (org-cdlatex-mode)
18322 (call-interactively (key-binding (vector last-input-event))))))
18324 (defun org-cdlatex-math-modify (&optional arg)
18325 "Execute `cdlatex-math-modify' in LaTeX fragments.
18326 Revert to the normal definition outside of these fragments."
18327 (interactive "P")
18328 (if (org-inside-LaTeX-fragment-p)
18329 (call-interactively 'cdlatex-math-modify)
18330 (let (org-cdlatex-mode)
18331 (call-interactively (key-binding (vector last-input-event))))))
18335 ;;;; LaTeX fragments
18337 (defun org-inside-LaTeX-fragment-p ()
18338 "Test if point is inside a LaTeX fragment.
18339 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18340 sequence appearing also before point.
18341 Even though the matchers for math are configurable, this function assumes
18342 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18343 delimiters are skipped when they have been removed by customization.
18344 The return value is nil, or a cons cell with the delimiter and the
18345 position of this delimiter.
18347 This function does a reasonably good job, but can locally be fooled by
18348 for example currency specifications. For example it will assume being in
18349 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18350 fragments that are properly closed, but during editing, we have to live
18351 with the uncertainty caused by missing closing delimiters. This function
18352 looks only before point, not after."
18353 (catch 'exit
18354 (let ((pos (point))
18355 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18356 (lim (progn
18357 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18358 (point)))
18359 dd-on str (start 0) m re)
18360 (goto-char pos)
18361 (when dodollar
18362 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18363 re (nth 1 (assoc "$" org-latex-regexps)))
18364 (while (string-match re str start)
18365 (cond
18366 ((= (match-end 0) (length str))
18367 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18368 ((= (match-end 0) (- (length str) 5))
18369 (throw 'exit nil))
18370 (t (setq start (match-end 0))))))
18371 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18372 (goto-char pos)
18373 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18374 (and (match-beginning 2) (throw 'exit nil))
18375 ;; count $$
18376 (while (re-search-backward "\\$\\$" lim t)
18377 (setq dd-on (not dd-on)))
18378 (goto-char pos)
18379 (if dd-on (cons "$$" m))))))
18381 (defun org-inside-latex-macro-p ()
18382 "Is point inside a LaTeX macro or its arguments?"
18383 (save-match-data
18384 (org-in-regexp
18385 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18387 (defvar org-latex-fragment-image-overlays nil
18388 "List of overlays carrying the images of latex fragments.")
18389 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18391 (defun org-remove-latex-fragment-image-overlays ()
18392 "Remove all overlays with LaTeX fragment images in current buffer."
18393 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18394 (setq org-latex-fragment-image-overlays nil))
18396 (defun org-preview-latex-fragment (&optional subtree)
18397 "Preview the LaTeX fragment at point, or all locally or globally.
18398 If the cursor is in a LaTeX fragment, create the image and overlay
18399 it over the source code. If there is no fragment at point, display
18400 all fragments in the current text, from one headline to the next. With
18401 prefix SUBTREE, display all fragments in the current subtree. With a
18402 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18403 the cursor is before the first headline,
18404 display all fragments in the buffer.
18405 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18406 (interactive "P")
18407 (unless buffer-file-name
18408 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18409 (when (display-graphic-p)
18410 (org-remove-latex-fragment-image-overlays)
18411 (save-excursion
18412 (save-restriction
18413 (let (beg end at msg)
18414 (cond
18415 ((or (equal subtree '(16))
18416 (not (save-excursion
18417 (re-search-backward org-outline-regexp-bol nil t))))
18418 (setq beg (point-min) end (point-max)
18419 msg "Creating images for buffer...%s"))
18420 ((equal subtree '(4))
18421 (org-back-to-heading)
18422 (setq beg (point) end (org-end-of-subtree t)
18423 msg "Creating images for subtree...%s"))
18425 (if (setq at (org-inside-LaTeX-fragment-p))
18426 (goto-char (max (point-min) (- (cdr at) 2)))
18427 (org-back-to-heading))
18428 (setq beg (point) end (progn (outline-next-heading) (point))
18429 msg (if at "Creating image...%s"
18430 "Creating images for entry...%s"))))
18431 (message msg "")
18432 (narrow-to-region beg end)
18433 (goto-char beg)
18434 (org-format-latex
18435 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18436 (file-name-nondirectory
18437 buffer-file-name)))
18438 default-directory 'overlays msg at 'forbuffer
18439 org-latex-create-formula-image-program)
18440 (message msg "done. Use `C-c C-c' to remove images."))))))
18442 (defun org-format-latex (prefix &optional dir overlays msg at
18443 forbuffer processing-type)
18444 "Replace LaTeX fragments with links to an image, and produce images.
18445 Some of the options can be changed using the variable
18446 `org-format-latex-options'."
18447 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18448 (let* ((prefixnodir (file-name-nondirectory prefix))
18449 (absprefix (expand-file-name prefix dir))
18450 (todir (file-name-directory absprefix))
18451 (opt org-format-latex-options)
18452 (optnew org-format-latex-options)
18453 (matchers (plist-get opt :matchers))
18454 (re-list org-latex-regexps)
18455 (cnt 0) txt hash link beg end re e checkdir
18456 string
18457 m n block-type block linkfile movefile ov)
18458 ;; Check the different regular expressions
18459 (while (setq e (pop re-list))
18460 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18461 block (if block-type "\n\n" ""))
18462 (when (member m matchers)
18463 (goto-char (point-min))
18464 (while (re-search-forward re nil t)
18465 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18466 (or (not overlays)
18467 (not (eq (get-char-property (match-beginning n)
18468 'org-overlay-type)
18469 'org-latex-overlay))))
18470 (cond
18471 ((eq processing-type 'verbatim))
18472 ((eq processing-type 'mathjax)
18473 ;; Prepare for MathJax processing.
18474 (setq string (match-string n))
18475 (when (member m '("$" "$1"))
18476 (save-excursion
18477 (delete-region (match-beginning n) (match-end n))
18478 (goto-char (match-beginning n))
18479 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18480 ((or (eq processing-type 'dvipng)
18481 (eq processing-type 'imagemagick))
18482 ;; Process to an image.
18483 (setq txt (match-string n)
18484 beg (match-beginning n) end (match-end n)
18485 cnt (1+ cnt))
18486 (let ((face (face-at-point))
18487 (fg (plist-get opt :foreground))
18488 (bg (plist-get opt :background))
18489 ;; Ensure full list is printed.
18490 print-length print-level)
18491 (when forbuffer
18492 ;; Get the colors from the face at point.
18493 (goto-char beg)
18494 (when (eq fg 'auto)
18495 (setq fg (face-attribute face :foreground nil 'default)))
18496 (when (eq bg 'auto)
18497 (setq bg (face-attribute face :background nil 'default)))
18498 (setq optnew (copy-sequence opt))
18499 (plist-put optnew :foreground fg)
18500 (plist-put optnew :background bg))
18501 (setq hash (sha1 (prin1-to-string
18502 (list org-format-latex-header
18503 org-latex-default-packages-alist
18504 org-latex-packages-alist
18505 org-format-latex-options
18506 forbuffer txt fg bg)))
18507 linkfile (format "%s_%s.png" prefix hash)
18508 movefile (format "%s_%s.png" absprefix hash)))
18509 (setq link (concat block "[[file:" linkfile "]]" block))
18510 (if msg (message msg cnt))
18511 (goto-char beg)
18512 (unless checkdir ; Ensure the directory exists.
18513 (setq checkdir t)
18514 (or (file-directory-p todir) (make-directory todir t)))
18515 (unless (file-exists-p movefile)
18516 (org-create-formula-image
18517 txt movefile optnew forbuffer processing-type))
18518 (if overlays
18519 (progn
18520 (mapc (lambda (o)
18521 (if (eq (overlay-get o 'org-overlay-type)
18522 'org-latex-overlay)
18523 (delete-overlay o)))
18524 (overlays-in beg end))
18525 (setq ov (make-overlay beg end))
18526 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18527 (if (featurep 'xemacs)
18528 (progn
18529 (overlay-put ov 'invisible t)
18530 (overlay-put
18531 ov 'end-glyph
18532 (make-glyph (vector 'png :file movefile))))
18533 (overlay-put
18534 ov 'display
18535 (list 'image :type 'png :file movefile :ascent 'center)))
18536 (push ov org-latex-fragment-image-overlays)
18537 (goto-char end))
18538 (delete-region beg end)
18539 (insert (org-add-props link
18540 (list 'org-latex-src
18541 (replace-regexp-in-string
18542 "\"" "" txt)
18543 'org-latex-src-embed-type
18544 (if block-type 'paragraph 'character))))))
18545 ((eq processing-type 'mathml)
18546 ;; Process to MathML
18547 (unless (save-match-data (org-format-latex-mathml-available-p))
18548 (user-error "LaTeX to MathML converter not configured"))
18549 (setq txt (match-string n)
18550 beg (match-beginning n) end (match-end n)
18551 cnt (1+ cnt))
18552 (if msg (message msg cnt))
18553 (goto-char beg)
18554 (delete-region beg end)
18555 (insert (org-format-latex-as-mathml
18556 txt block-type prefix dir)))
18558 (error "Unknown conversion type %s for LaTeX fragments"
18559 processing-type)))))))))
18561 (defun org-create-math-formula (latex-frag &optional mathml-file)
18562 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18563 Use `org-latex-to-mathml-convert-command'. If the conversion is
18564 sucessful, return the portion between \"<math...> </math>\"
18565 elements otherwise return nil. When MATHML-FILE is specified,
18566 write the results in to that file. When invoked as an
18567 interactive command, prompt for LATEX-FRAG, with initial value
18568 set to the current active region and echo the results for user
18569 inspection."
18570 (interactive (list (let ((frag (when (org-region-active-p)
18571 (buffer-substring-no-properties
18572 (region-beginning) (region-end)))))
18573 (read-string "LaTeX Fragment: " frag nil frag))))
18574 (unless latex-frag (error "Invalid LaTeX fragment"))
18575 (let* ((tmp-in-file (file-relative-name
18576 (make-temp-name (expand-file-name "ltxmathml-in"))))
18577 (ignore (write-region latex-frag nil tmp-in-file))
18578 (tmp-out-file (file-relative-name
18579 (make-temp-name (expand-file-name "ltxmathml-out"))))
18580 (cmd (format-spec
18581 org-latex-to-mathml-convert-command
18582 `((?j . ,(shell-quote-argument
18583 (expand-file-name org-latex-to-mathml-jar-file)))
18584 (?I . ,(shell-quote-argument tmp-in-file))
18585 (?o . ,(shell-quote-argument tmp-out-file)))))
18586 mathml shell-command-output)
18587 (when (org-called-interactively-p 'any)
18588 (unless (org-format-latex-mathml-available-p)
18589 (user-error "LaTeX to MathML converter not configured")))
18590 (message "Running %s" cmd)
18591 (setq shell-command-output (shell-command-to-string cmd))
18592 (setq mathml
18593 (when (file-readable-p tmp-out-file)
18594 (with-current-buffer (find-file-noselect tmp-out-file t)
18595 (goto-char (point-min))
18596 (when (re-search-forward
18597 (concat
18598 (regexp-quote
18599 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18600 "\\(.\\|\n\\)*"
18601 (regexp-quote "</math>")) nil t)
18602 (prog1 (match-string 0) (kill-buffer))))))
18603 (cond
18604 (mathml
18605 (setq mathml
18606 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18607 (when mathml-file
18608 (write-region mathml nil mathml-file))
18609 (when (org-called-interactively-p 'any)
18610 (message mathml)))
18611 ((message "LaTeX to MathML conversion failed")
18612 (message shell-command-output)))
18613 (delete-file tmp-in-file)
18614 (when (file-exists-p tmp-out-file)
18615 (delete-file tmp-out-file))
18616 mathml))
18618 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18619 prefix &optional dir)
18620 "Use `org-create-math-formula' but check local cache first."
18621 (let* ((absprefix (expand-file-name prefix dir))
18622 (print-length nil) (print-level nil)
18623 (formula-id (concat
18624 "formula-"
18625 (sha1
18626 (prin1-to-string
18627 (list latex-frag
18628 org-latex-to-mathml-convert-command)))))
18629 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18630 (formula-cache-dir (file-name-directory formula-cache)))
18632 (unless (file-directory-p formula-cache-dir)
18633 (make-directory formula-cache-dir t))
18635 (unless (file-exists-p formula-cache)
18636 (org-create-math-formula latex-frag formula-cache))
18638 (if (file-exists-p formula-cache)
18639 ;; Successful conversion. Return the link to MathML file.
18640 (org-add-props
18641 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18642 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18643 'org-latex-src-embed-type (if latex-frag-type
18644 'paragraph 'character)))
18645 ;; Failed conversion. Return the LaTeX fragment verbatim
18646 latex-frag)))
18648 (defun org-create-formula-image (string tofile options buffer &optional type)
18649 "Create an image from LaTeX source using dvipng or convert.
18650 This function calls either `org-create-formula-image-with-dvipng'
18651 or `org-create-formula-image-with-imagemagick' depending on the
18652 value of `org-latex-create-formula-image-program' or on the value
18653 of the optional TYPE variable.
18655 Note: ultimately these two function should be combined as they
18656 share a good deal of logic."
18657 (org-check-external-command
18658 "latex" "needed to convert LaTeX fragments to images")
18659 (funcall
18660 (case (or type org-latex-create-formula-image-program)
18661 ('dvipng
18662 (org-check-external-command
18663 "dvipng" "needed to convert LaTeX fragments to images")
18664 #'org-create-formula-image-with-dvipng)
18665 ('imagemagick
18666 (org-check-external-command
18667 "convert" "you need to install imagemagick")
18668 #'org-create-formula-image-with-imagemagick)
18669 (t (error
18670 "Invalid value of `org-latex-create-formula-image-program'")))
18671 string tofile options buffer))
18673 (declare-function org-export-get-backend "ox" (name))
18674 (declare-function org-export--get-global-options "ox" (&optional backend))
18675 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18676 (declare-function org-latex-guess-inputenc "ox-latex" (header))
18677 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
18678 (defun org-create-formula--latex-header ()
18679 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18680 (let ((info (org-combine-plists (org-export--get-global-options
18681 (org-export-get-backend 'latex))
18682 (org-export--get-inbuffer-options
18683 (org-export-get-backend 'latex)))))
18684 (org-latex-guess-babel-language
18685 (org-latex-guess-inputenc
18686 (org-splice-latex-header
18687 org-format-latex-header
18688 org-latex-default-packages-alist
18689 org-latex-packages-alist t
18690 (plist-get info :latex-header)))
18691 info)))
18693 ;; This function borrows from Ganesh Swami's latex2png.el
18694 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18695 "This calls dvipng."
18696 (require 'ox-latex)
18697 (let* ((tmpdir (if (featurep 'xemacs)
18698 (temp-directory)
18699 temporary-file-directory))
18700 (texfilebase (make-temp-name
18701 (expand-file-name "orgtex" tmpdir)))
18702 (texfile (concat texfilebase ".tex"))
18703 (dvifile (concat texfilebase ".dvi"))
18704 (pngfile (concat texfilebase ".png"))
18705 (fnh (if (featurep 'xemacs)
18706 (font-height (face-font 'default))
18707 (face-attribute 'default :height nil)))
18708 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18709 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18710 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18711 "Black"))
18712 (bg (or (plist-get options (if buffer :background :html-background))
18713 "Transparent")))
18714 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18715 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18716 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18717 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18718 (let ((latex-header (org-create-formula--latex-header)))
18719 (with-temp-file texfile
18720 (insert latex-header)
18721 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18722 (let ((dir default-directory))
18723 (condition-case nil
18724 (progn
18725 (cd tmpdir)
18726 (call-process "latex" nil nil nil texfile))
18727 (error nil))
18728 (cd dir))
18729 (if (not (file-exists-p dvifile))
18730 (progn (message "Failed to create dvi file from %s" texfile) nil)
18731 (condition-case nil
18732 (if (featurep 'xemacs)
18733 (call-process "dvipng" nil nil nil
18734 "-fg" fg "-bg" bg
18735 "-T" "tight"
18736 "-o" pngfile
18737 dvifile)
18738 (call-process "dvipng" nil nil nil
18739 "-fg" fg "-bg" bg
18740 "-D" dpi
18741 ;;"-x" scale "-y" scale
18742 "-T" "tight"
18743 "-o" pngfile
18744 dvifile))
18745 (error nil))
18746 (if (not (file-exists-p pngfile))
18747 (if org-format-latex-signal-error
18748 (error "Failed to create png file from %s" texfile)
18749 (message "Failed to create png file from %s" texfile)
18750 nil)
18751 ;; Use the requested file name and clean up
18752 (copy-file pngfile tofile 'replace)
18753 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18754 (if (file-exists-p (concat texfilebase e))
18755 (delete-file (concat texfilebase e))))
18756 pngfile))))
18758 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18759 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18760 "This calls convert, which is included into imagemagick."
18761 (require 'ox-latex)
18762 (let* ((tmpdir (if (featurep 'xemacs)
18763 (temp-directory)
18764 temporary-file-directory))
18765 (texfilebase (make-temp-name
18766 (expand-file-name "orgtex" tmpdir)))
18767 (texfile (concat texfilebase ".tex"))
18768 (pdffile (concat texfilebase ".pdf"))
18769 (pngfile (concat texfilebase ".png"))
18770 (fnh (if (featurep 'xemacs)
18771 (font-height (face-font 'default))
18772 (face-attribute 'default :height nil)))
18773 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18774 (dpi (number-to-string (* scale (floor (if buffer fnh 120.)))))
18775 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18776 "black"))
18777 (bg (or (plist-get options (if buffer :background :html-background))
18778 "white")))
18779 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18780 (setq fg (org-latex-color-format fg)))
18781 (if (eq bg 'default) (setq bg (org-latex-color :background))
18782 (setq bg (org-latex-color-format
18783 (if (string= bg "Transparent") "white" bg))))
18784 (let ((latex-header (org-create-formula--latex-header)))
18785 (with-temp-file texfile
18786 (insert latex-header)
18787 (insert "\n\\begin{document}\n"
18788 "\\definecolor{fg}{rgb}{" fg "}\n"
18789 "\\definecolor{bg}{rgb}{" bg "}\n"
18790 "\n\\pagecolor{bg}\n"
18791 "\n{\\color{fg}\n"
18792 string
18793 "\n}\n"
18794 "\n\\end{document}\n")))
18795 (org-latex-compile texfile t)
18796 (if (not (file-exists-p pdffile))
18797 (progn (message "Failed to create pdf file from %s" texfile) nil)
18798 (condition-case nil
18799 (if (featurep 'xemacs)
18800 (call-process "convert" nil nil nil
18801 "-density" "96"
18802 "-trim"
18803 "-antialias"
18804 pdffile
18805 "-quality" "100"
18806 ;; "-sharpen" "0x1.0"
18807 pngfile)
18808 (call-process "convert" nil nil nil
18809 "-density" dpi
18810 "-trim"
18811 "-antialias"
18812 pdffile
18813 "-quality" "100"
18814 ;; "-sharpen" "0x1.0"
18815 pngfile))
18816 (error nil))
18817 (if (not (file-exists-p pngfile))
18818 (if org-format-latex-signal-error
18819 (error "Failed to create png file from %s" texfile)
18820 (message "Failed to create png file from %s" texfile)
18821 nil)
18822 ;; Use the requested file name and clean up
18823 (copy-file pngfile tofile 'replace)
18824 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18825 (if (file-exists-p (concat texfilebase e))
18826 (delete-file (concat texfilebase e))))
18827 pngfile))))
18829 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18830 "Fill a LaTeX header template TPL.
18831 In the template, the following place holders will be recognized:
18833 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18834 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18835 [PACKAGES] \\usepackage statements for PKG
18836 [NO-PACKAGES] do not include PKG
18837 [EXTRA] the string EXTRA
18838 [NO-EXTRA] do not include EXTRA
18840 For backward compatibility, if both the positive and the negative place
18841 holder is missing, the positive one (without the \"NO-\") will be
18842 assumed to be present at the end of the template.
18843 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18844 EXTRA is a string.
18845 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18846 (let (rpl (end ""))
18847 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18848 (setq rpl (if (or (match-end 1) (not def-pkg))
18849 "" (org-latex-packages-to-string def-pkg snippets-p t))
18850 tpl (replace-match rpl t t tpl))
18851 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18853 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18854 (setq rpl (if (or (match-end 1) (not pkg))
18855 "" (org-latex-packages-to-string pkg snippets-p t))
18856 tpl (replace-match rpl t t tpl))
18857 (if pkg (setq end
18858 (concat end "\n"
18859 (org-latex-packages-to-string pkg snippets-p)))))
18861 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18862 (setq rpl (if (or (match-end 1) (not extra))
18863 "" (concat extra "\n"))
18864 tpl (replace-match rpl t t tpl))
18865 (if (and extra (string-match "\\S-" extra))
18866 (setq end (concat end "\n" extra))))
18868 (if (string-match "\\S-" end)
18869 (concat tpl "\n" end)
18870 tpl)))
18872 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18873 "Turn an alist of packages into a string with the \\usepackage macros."
18874 (setq pkg (mapconcat (lambda(p)
18875 (cond
18876 ((stringp p) p)
18877 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18878 (format "%% Package %s omitted" (cadr p)))
18879 ((equal "" (car p))
18880 (format "\\usepackage{%s}" (cadr p)))
18882 (format "\\usepackage[%s]{%s}"
18883 (car p) (cadr p)))))
18885 "\n"))
18886 (if newline (concat pkg "\n") pkg))
18888 (defun org-dvipng-color (attr)
18889 "Return a RGB color specification for dvipng."
18890 (apply 'format "rgb %s %s %s"
18891 (mapcar 'org-normalize-color
18892 (if (featurep 'xemacs)
18893 (color-rgb-components
18894 (face-property 'default
18895 (cond ((eq attr :foreground) 'foreground)
18896 ((eq attr :background) 'background))))
18897 (color-values (face-attribute 'default attr nil))))))
18899 (defun org-dvipng-color-format (color-name)
18900 "Convert COLOR-NAME to a RGB color value for dvipng."
18901 (apply 'format "rgb %s %s %s"
18902 (mapcar 'org-normalize-color
18903 (color-values color-name))))
18905 (defun org-latex-color (attr)
18906 "Return a RGB color for the LaTeX color package."
18907 (apply 'format "%s,%s,%s"
18908 (mapcar 'org-normalize-color
18909 (if (featurep 'xemacs)
18910 (color-rgb-components
18911 (face-property 'default
18912 (cond ((eq attr :foreground) 'foreground)
18913 ((eq attr :background) 'background))))
18914 (color-values (face-attribute 'default attr nil))))))
18916 (defun org-latex-color-format (color-name)
18917 "Convert COLOR-NAME to a RGB color value."
18918 (apply 'format "%s,%s,%s"
18919 (mapcar 'org-normalize-color
18920 (color-values color-name))))
18922 (defun org-normalize-color (value)
18923 "Return string to be used as color value for an RGB component."
18924 (format "%g" (/ value 65535.0)))
18928 ;; Image display
18930 (defvar org-inline-image-overlays nil)
18931 (make-variable-buffer-local 'org-inline-image-overlays)
18933 (defun org-toggle-inline-images (&optional include-linked)
18934 "Toggle the display of inline images.
18935 INCLUDE-LINKED is passed to `org-display-inline-images'."
18936 (interactive "P")
18937 (if org-inline-image-overlays
18938 (progn
18939 (org-remove-inline-images)
18940 (message "Inline image display turned off"))
18941 (org-display-inline-images include-linked)
18942 (if (and (org-called-interactively-p)
18943 org-inline-image-overlays)
18944 (message "%d images displayed inline"
18945 (length org-inline-image-overlays))
18946 (message "No images to display inline"))))
18948 (defun org-redisplay-inline-images ()
18949 "Refresh the display of inline images."
18950 (interactive)
18951 (if (not org-inline-image-overlays)
18952 (org-toggle-inline-images)
18953 (org-toggle-inline-images)
18954 (org-toggle-inline-images)))
18956 (defun org-display-inline-images (&optional include-linked refresh beg end)
18957 "Display inline images.
18959 An inline image is a link which follows either of these
18960 conventions:
18962 1. Its path is a file with an extension matching return value
18963 from `image-file-name-regexp' and it has no contents.
18965 2. Its description consists in a single link of the previous
18966 type.
18968 When optional argument INCLUDE-LINKED is non-nil, also links with
18969 a text description part will be inlined. This can be nice for
18970 a quick look at those images, but it does not reflect what
18971 exported files will look like.
18973 When optional argument REFRESH is non-nil, refresh existing
18974 images between BEG and END. This will create new image displays
18975 only if necessary. BEG and END default to the buffer
18976 boundaries."
18977 (interactive "P")
18978 (when (display-graphic-p)
18979 (unless refresh
18980 (org-remove-inline-images)
18981 (when (fboundp 'clear-image-cache) (clear-image-cache)))
18982 (org-with-wide-buffer
18983 (goto-char (or beg (point-min)))
18984 (let ((case-fold-search t)
18985 (file-extension-re (org-image-file-name-regexp)))
18986 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
18987 (let ((link (save-match-data (org-element-context))))
18988 ;; Check if we're at an inline image.
18989 (when (and (equal (org-element-property :type link) "file")
18990 (or include-linked
18991 (not (org-element-property :contents-begin link)))
18992 (let ((parent (org-element-property :parent link)))
18993 (or (not (eq (org-element-type parent) 'link))
18994 (not (cdr (org-element-contents parent)))))
18995 (org-string-match-p file-extension-re
18996 (org-element-property :path link)))
18997 (let ((file (expand-file-name (org-element-property :path link))))
18998 (when (file-exists-p file)
18999 (let ((width
19000 ;; Apply `org-image-actual-width' specifications.
19001 (cond
19002 ((not (image-type-available-p 'imagemagick)) nil)
19003 ((eq org-image-actual-width t) nil)
19004 ((listp org-image-actual-width)
19006 ;; First try to find a width among
19007 ;; attributes associated to the paragraph
19008 ;; containing link.
19009 (let ((paragraph
19010 (let ((e link))
19011 (while (and (setq e (org-element-property
19012 :parent e))
19013 (not (eq (org-element-type e)
19014 'paragraph))))
19015 e)))
19016 (when paragraph
19017 (save-excursion
19018 (goto-char (org-element-property :begin paragraph))
19019 (when (save-match-data
19020 (re-search-forward
19021 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19022 (org-element-property
19023 :post-affiliated paragraph)
19025 (string-to-number (match-string 1))))))
19026 ;; Otherwise, fall-back to provided number.
19027 (car org-image-actual-width)))
19028 ((numberp org-image-actual-width)
19029 org-image-actual-width)))
19030 (old (get-char-property-and-overlay
19031 (org-element-property :begin link)
19032 'org-image-overlay)))
19033 (if (and (car-safe old) refresh)
19034 (image-refresh (overlay-get (cdr old) 'display))
19035 (let ((image (save-match-data
19036 (create-image file
19037 (and width 'imagemagick)
19039 :width width))))
19040 (when image
19041 (let* ((link
19042 ;; If inline image is the description
19043 ;; of another link, be sure to
19044 ;; consider the latter as the one to
19045 ;; apply the overlay on.
19046 (let ((parent
19047 (org-element-property :parent link)))
19048 (if (eq (org-element-type parent) 'link)
19049 parent
19050 link)))
19051 (ov (make-overlay
19052 (org-element-property :begin link)
19053 (progn
19054 (goto-char
19055 (org-element-property :end link))
19056 (skip-chars-backward " \t")
19057 (point)))))
19058 (overlay-put ov 'display image)
19059 (overlay-put ov 'face 'default)
19060 (overlay-put ov 'org-image-overlay t)
19061 (overlay-put
19062 ov 'modification-hooks
19063 (list 'org-display-inline-remove-overlay))
19064 (push ov org-inline-image-overlays)))))))))))))))
19066 (define-obsolete-function-alias
19067 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
19069 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
19070 "Remove inline-display overlay if a corresponding region is modified."
19071 (let ((inhibit-modification-hooks t))
19072 (when (and ov after)
19073 (delete ov org-inline-image-overlays)
19074 (delete-overlay ov))))
19076 (defun org-remove-inline-images ()
19077 "Remove inline display of images."
19078 (interactive)
19079 (mapc 'delete-overlay org-inline-image-overlays)
19080 (setq org-inline-image-overlays nil))
19082 ;;;; Key bindings
19084 ;; Outline functions from `outline-mode-prefix-map'
19085 ;; that can be remapped in Org:
19086 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19087 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
19088 (define-key org-mode-map [remap outline-forward-same-level]
19089 'org-forward-heading-same-level)
19090 (define-key org-mode-map [remap outline-backward-same-level]
19091 'org-backward-heading-same-level)
19092 (define-key org-mode-map [remap show-branches]
19093 'org-kill-note-or-show-branches)
19094 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19095 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19096 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19098 ;; Outline functions from `outline-mode-prefix-map' that can not
19099 ;; be remapped in Org:
19101 ;; - the column "key binding" shows whether the Outline function is still
19102 ;; available in Org mode on the same key that it has been bound to in
19103 ;; Outline mode:
19104 ;; - "overridden": key used for a different functionality in Org mode
19105 ;; - else: key still bound to the same Outline function in Org mode
19107 ;; | Outline function | key binding | Org replacement |
19108 ;; |------------------------------------+-------------+-----------------------|
19109 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
19110 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
19111 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19112 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19113 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19114 ;; | `show-entry' | overridden | no replacement |
19115 ;; | `show-children' | `C-c C-i' | visibility cycling |
19116 ;; | `show-branches' | `C-c C-k' | still same function |
19117 ;; | `show-subtree' | overridden | visibility cycling |
19118 ;; | `show-all' | overridden | no replacement |
19119 ;; | `hide-subtree' | overridden | visibility cycling |
19120 ;; | `hide-body' | overridden | no replacement |
19121 ;; | `hide-entry' | overridden | visibility cycling |
19122 ;; | `hide-leaves' | overridden | no replacement |
19123 ;; | `hide-sublevels' | overridden | no replacement |
19124 ;; | `hide-other' | overridden | no replacement |
19126 ;; Make `C-c C-x' a prefix key
19127 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19129 ;; TAB key with modifiers
19130 (org-defkey org-mode-map "\C-i" 'org-cycle)
19131 (org-defkey org-mode-map [(tab)] 'org-cycle)
19132 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19133 (org-defkey org-mode-map "\M-\t" 'pcomplete)
19134 ;; The following line is necessary under Suse GNU/Linux
19135 (unless (featurep 'xemacs)
19136 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
19137 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19138 (define-key org-mode-map [backtab] 'org-shifttab)
19140 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19141 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19142 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19144 ;; Cursor keys with modifiers
19145 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19146 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19147 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19148 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19150 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19151 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19152 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19153 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19155 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19156 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19157 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19158 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19160 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19161 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19162 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19163 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19165 ;; Babel keys
19166 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19167 (mapc (lambda (pair)
19168 (define-key org-babel-map (car pair) (cdr pair)))
19169 org-babel-key-bindings)
19171 ;;; Extra keys for tty access.
19172 ;; We only set them when really needed because otherwise the
19173 ;; menus don't show the simple keys
19175 (when (or org-use-extra-keys
19176 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19177 (not window-system))
19178 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19179 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19180 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19181 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19182 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19183 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19184 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19185 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19186 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19187 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19188 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19189 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19190 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19191 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19192 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19193 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19194 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19195 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19196 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19197 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19198 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19199 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19200 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
19201 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19202 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19203 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19204 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19205 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19207 ;; All the other keys
19209 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
19210 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19211 (if (boundp 'narrow-map)
19212 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19213 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19214 (if (boundp 'narrow-map)
19215 (org-defkey narrow-map "b" 'org-narrow-to-block)
19216 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19217 (if (boundp 'narrow-map)
19218 (org-defkey narrow-map "e" 'org-narrow-to-element)
19219 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19220 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19221 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19222 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19223 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19224 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19225 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19226 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19227 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19228 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19229 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19230 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
19231 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19232 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19233 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19234 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19235 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19236 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19237 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19238 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19239 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19240 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19241 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19242 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19243 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19244 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19245 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19246 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19247 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19248 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19249 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19250 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19251 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19252 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19253 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19254 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19255 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19256 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19257 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19258 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19259 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19260 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19261 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19262 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19263 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19264 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19265 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19266 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19267 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19268 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19269 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19270 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19271 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19272 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19273 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19274 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19275 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19276 (org-defkey org-mode-map "\C-c^" 'org-sort)
19277 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19278 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19279 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19280 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19281 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19282 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19283 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19284 (org-defkey org-mode-map "\C-m" 'org-return)
19285 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19286 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19287 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19288 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19289 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19290 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19291 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19292 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19293 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19294 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19295 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19296 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19297 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19298 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19299 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19300 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19301 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19302 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19303 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19304 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19305 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19306 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19307 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19309 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19310 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19311 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19313 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19314 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19315 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19316 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19317 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19318 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19319 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19320 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19321 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19322 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19323 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
19324 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19325 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19326 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19327 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19328 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19329 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19330 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19331 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19332 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19333 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19334 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19335 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19337 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19338 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19339 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19340 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19341 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19343 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19345 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19347 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19348 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19350 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19353 (when (featurep 'xemacs)
19354 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19357 (defconst org-speed-commands-default
19359 ("Outline Navigation")
19360 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19361 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19362 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19363 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19364 ("F" . org-next-block)
19365 ("B" . org-previous-block)
19366 ("u" . (org-speed-move-safe 'outline-up-heading))
19367 ("j" . org-goto)
19368 ("g" . (org-refile t))
19369 ("Outline Visibility")
19370 ("c" . org-cycle)
19371 ("C" . org-shifttab)
19372 (" " . org-display-outline-path)
19373 ("s" . org-narrow-to-subtree)
19374 ("=" . org-columns)
19375 ("Outline Structure Editing")
19376 ("U" . org-shiftmetaup)
19377 ("D" . org-shiftmetadown)
19378 ("r" . org-metaright)
19379 ("l" . org-metaleft)
19380 ("R" . org-shiftmetaright)
19381 ("L" . org-shiftmetaleft)
19382 ("i" . (progn (forward-char 1) (call-interactively
19383 'org-insert-heading-respect-content)))
19384 ("^" . org-sort)
19385 ("w" . org-refile)
19386 ("a" . org-archive-subtree-default-with-confirmation)
19387 ("@" . org-mark-subtree)
19388 ("#" . org-toggle-comment)
19389 ("Clock Commands")
19390 ("I" . org-clock-in)
19391 ("O" . org-clock-out)
19392 ("Meta Data Editing")
19393 ("t" . org-todo)
19394 ("," . (org-priority))
19395 ("0" . (org-priority ?\ ))
19396 ("1" . (org-priority ?A))
19397 ("2" . (org-priority ?B))
19398 ("3" . (org-priority ?C))
19399 (":" . org-set-tags-command)
19400 ("e" . org-set-effort)
19401 ("E" . org-inc-effort)
19402 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19403 (org-entry-put (point) "APPT_WARNTIME" m)))
19404 ("Agenda Views etc")
19405 ("v" . org-agenda)
19406 ("/" . org-sparse-tree)
19407 ("Misc")
19408 ("o" . org-open-at-point)
19409 ("?" . org-speed-command-help)
19410 ("<" . (org-agenda-set-restriction-lock 'subtree))
19411 (">" . (org-agenda-remove-restriction-lock))
19413 "The default speed commands.")
19415 (defun org-print-speed-command (e)
19416 (if (> (length (car e)) 1)
19417 (progn
19418 (princ "\n")
19419 (princ (car e))
19420 (princ "\n")
19421 (princ (make-string (length (car e)) ?-))
19422 (princ "\n"))
19423 (princ (car e))
19424 (princ " ")
19425 (if (symbolp (cdr e))
19426 (princ (symbol-name (cdr e)))
19427 (prin1 (cdr e)))
19428 (princ "\n")))
19430 (defun org-speed-command-help ()
19431 "Show the available speed commands."
19432 (interactive)
19433 (if (not org-use-speed-commands)
19434 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19435 (with-output-to-temp-buffer "*Help*"
19436 (princ "User-defined Speed commands\n===========================\n")
19437 (mapc 'org-print-speed-command org-speed-commands-user)
19438 (princ "\n")
19439 (princ "Built-in Speed commands\n=======================\n")
19440 (mapc 'org-print-speed-command org-speed-commands-default))
19441 (with-current-buffer "*Help*"
19442 (setq truncate-lines t))))
19444 (defun org-speed-move-safe (cmd)
19445 "Execute CMD, but make sure that the cursor always ends up in a headline.
19446 If not, return to the original position and throw an error."
19447 (interactive)
19448 (let ((pos (point)))
19449 (call-interactively cmd)
19450 (unless (and (bolp) (org-at-heading-p))
19451 (goto-char pos)
19452 (error "Boundary reached while executing %s" cmd))))
19454 (defvar org-self-insert-command-undo-counter 0)
19456 (defvar org-table-auto-blank-field) ; defined in org-table.el
19457 (defvar org-speed-command nil)
19459 (define-obsolete-function-alias
19460 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19462 (defun org-speed-command-activate (keys)
19463 "Hook for activating single-letter speed commands.
19464 `org-speed-commands-default' specifies a minimal command set.
19465 Use `org-speed-commands-user' for further customization."
19466 (when (or (and (bolp) (looking-at org-outline-regexp))
19467 (and (functionp org-use-speed-commands)
19468 (funcall org-use-speed-commands)))
19469 (cdr (assoc keys (append org-speed-commands-user
19470 org-speed-commands-default)))))
19472 (define-obsolete-function-alias
19473 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19475 (defun org-babel-speed-command-activate (keys)
19476 "Hook for activating single-letter code block commands."
19477 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19478 (cdr (assoc keys org-babel-key-bindings))))
19480 (defcustom org-speed-command-hook
19481 '(org-speed-command-default-hook org-babel-speed-command-hook)
19482 "Hook for activating speed commands at strategic locations.
19483 Hook functions are called in sequence until a valid handler is
19484 found.
19486 Each hook takes a single argument, a user-pressed command key
19487 which is also a `self-insert-command' from the global map.
19489 Within the hook, examine the cursor position and the command key
19490 and return nil or a valid handler as appropriate. Handler could
19491 be one of an interactive command, a function, or a form.
19493 Set `org-use-speed-commands' to non-nil value to enable this
19494 hook. The default setting is `org-speed-command-activate'."
19495 :group 'org-structure
19496 :version "24.1"
19497 :type 'hook)
19499 (defun org-self-insert-command (N)
19500 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19501 If the cursor is in a table looking at whitespace, the whitespace is
19502 overwritten, and the table is not marked as requiring realignment."
19503 (interactive "p")
19504 (org-check-before-invisible-edit 'insert)
19505 (cond
19506 ((and org-use-speed-commands
19507 (setq org-speed-command
19508 (run-hook-with-args-until-success
19509 'org-speed-command-hook (this-command-keys))))
19510 (cond
19511 ((commandp org-speed-command)
19512 (setq this-command org-speed-command)
19513 (call-interactively org-speed-command))
19514 ((functionp org-speed-command)
19515 (funcall org-speed-command))
19516 ((and org-speed-command (listp org-speed-command))
19517 (eval org-speed-command))
19518 (t (let (org-use-speed-commands)
19519 (call-interactively 'org-self-insert-command)))))
19520 ((and
19521 (org-table-p)
19522 (progn
19523 ;; check if we blank the field, and if that triggers align
19524 (and (featurep 'org-table) org-table-auto-blank-field
19525 (member last-command
19526 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19527 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19528 ;; got extra space, this field does not determine column width
19529 (let (org-table-may-need-update) (org-table-blank-field))
19530 ;; no extra space, this field may determine column width
19531 (org-table-blank-field)))
19533 (eq N 1)
19534 (looking-at "[^|\n]* |"))
19535 (let (org-table-may-need-update)
19536 (goto-char (1- (match-end 0)))
19537 (backward-delete-char 1)
19538 (goto-char (match-beginning 0))
19539 (self-insert-command N)))
19541 (setq org-table-may-need-update t)
19542 (self-insert-command N)
19543 (org-fix-tags-on-the-fly)
19544 (if org-self-insert-cluster-for-undo
19545 (if (not (eq last-command 'org-self-insert-command))
19546 (setq org-self-insert-command-undo-counter 1)
19547 (if (>= org-self-insert-command-undo-counter 20)
19548 (setq org-self-insert-command-undo-counter 1)
19549 (and (> org-self-insert-command-undo-counter 0)
19550 buffer-undo-list (listp buffer-undo-list)
19551 (not (cadr buffer-undo-list)) ; remove nil entry
19552 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19553 (setq org-self-insert-command-undo-counter
19554 (1+ org-self-insert-command-undo-counter))))))))
19556 (defun org-check-before-invisible-edit (kind)
19557 "Check is editing if kind KIND would be dangerous with invisible text around.
19558 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19559 ;; First, try to get out of here as quickly as possible, to reduce overhead
19560 (if (and org-catch-invisible-edits
19561 (or (not (boundp 'visible-mode)) (not visible-mode))
19562 (or (get-char-property (point) 'invisible)
19563 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19564 ;; OK, we need to take a closer look
19565 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19566 (invisible-before-point (if (bobp) nil (get-char-property
19567 (1- (point)) 'invisible)))
19568 (border-and-ok-direction
19570 ;; Check if we are acting predictably before invisible text
19571 (and invisible-at-point (not invisible-before-point)
19572 (memq kind '(insert delete-backward)))
19573 ;; Check if we are acting predictably after invisible text
19574 ;; This works not well, and I have turned it off. It seems
19575 ;; better to always show and stop after invisible text.
19576 ;; (and (not invisible-at-point) invisible-before-point
19577 ;; (memq kind '(insert delete)))
19579 (when (or (memq invisible-at-point '(outline org-hide-block t))
19580 (memq invisible-before-point '(outline org-hide-block t)))
19581 (if (eq org-catch-invisible-edits 'error)
19582 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19583 (if (and org-custom-properties-overlays
19584 (y-or-n-p "Display invisible properties in this buffer? "))
19585 (org-toggle-custom-properties-visibility)
19586 ;; Make the area visible
19587 (save-excursion
19588 (if invisible-before-point
19589 (goto-char (previous-single-char-property-change
19590 (point) 'invisible)))
19591 (org-cycle))
19592 (cond
19593 ((eq org-catch-invisible-edits 'show)
19594 ;; That's it, we do the edit after showing
19595 (message
19596 "Unfolding invisible region around point before editing")
19597 (sit-for 1))
19598 ((and (eq org-catch-invisible-edits 'smart)
19599 border-and-ok-direction)
19600 (message "Unfolding invisible region around point before editing"))
19602 ;; Don't do the edit, make the user repeat it in full visibility
19603 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19605 (defun org-fix-tags-on-the-fly ()
19606 (when (and (equal (char-after (point-at-bol)) ?*)
19607 (org-at-heading-p))
19608 (org-align-tags-here org-tags-column)))
19610 (defun org-delete-backward-char (N)
19611 "Like `delete-backward-char', insert whitespace at field end in tables.
19612 When deleting backwards, in tables this function will insert whitespace in
19613 front of the next \"|\" separator, to keep the table aligned. The table will
19614 still be marked for re-alignment if the field did fill the entire column,
19615 because, in this case the deletion might narrow the column."
19616 (interactive "p")
19617 (save-match-data
19618 (org-check-before-invisible-edit 'delete-backward)
19619 (if (and (org-table-p)
19620 (eq N 1)
19621 (string-match "|" (buffer-substring (point-at-bol) (point)))
19622 (looking-at ".*?|"))
19623 (let ((pos (point))
19624 (noalign (looking-at "[^|\n\r]* |"))
19625 (c org-table-may-need-update))
19626 (backward-delete-char N)
19627 (if (not overwrite-mode)
19628 (progn
19629 (skip-chars-forward "^|")
19630 (insert " ")
19631 (goto-char (1- pos))))
19632 ;; noalign: if there were two spaces at the end, this field
19633 ;; does not determine the width of the column.
19634 (if noalign (setq org-table-may-need-update c)))
19635 (backward-delete-char N)
19636 (org-fix-tags-on-the-fly))))
19638 (defun org-delete-char (N)
19639 "Like `delete-char', but insert whitespace at field end in tables.
19640 When deleting characters, in tables this function will insert whitespace in
19641 front of the next \"|\" separator, to keep the table aligned. The table will
19642 still be marked for re-alignment if the field did fill the entire column,
19643 because, in this case the deletion might narrow the column."
19644 (interactive "p")
19645 (save-match-data
19646 (org-check-before-invisible-edit 'delete)
19647 (if (and (org-table-p)
19648 (not (bolp))
19649 (not (= (char-after) ?|))
19650 (eq N 1))
19651 (if (looking-at ".*?|")
19652 (let ((pos (point))
19653 (noalign (looking-at "[^|\n\r]* |"))
19654 (c org-table-may-need-update))
19655 (replace-match
19656 (concat (substring (match-string 0) 1 -1) " |") nil t)
19657 (goto-char pos)
19658 ;; noalign: if there were two spaces at the end, this field
19659 ;; does not determine the width of the column.
19660 (if noalign (setq org-table-may-need-update c)))
19661 (delete-char N))
19662 (delete-char N)
19663 (org-fix-tags-on-the-fly))))
19665 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19666 (put 'org-self-insert-command 'delete-selection
19667 (lambda ()
19668 (not (run-hook-with-args-until-success
19669 'self-insert-uses-region-functions))))
19670 (put 'orgtbl-self-insert-command 'delete-selection
19671 (lambda ()
19672 (not (run-hook-with-args-until-success
19673 'self-insert-uses-region-functions))))
19674 (put 'org-delete-char 'delete-selection 'supersede)
19675 (put 'org-delete-backward-char 'delete-selection 'supersede)
19676 (put 'org-yank 'delete-selection 'yank)
19678 ;; Make `flyspell-mode' delay after some commands
19679 (put 'org-self-insert-command 'flyspell-delayed t)
19680 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19681 (put 'org-delete-char 'flyspell-delayed t)
19682 (put 'org-delete-backward-char 'flyspell-delayed t)
19684 ;; Make pabbrev-mode expand after org-mode commands
19685 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19686 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19688 (defun org-remap (map &rest commands)
19689 "In MAP, remap the functions given in COMMANDS.
19690 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19691 (let (new old)
19692 (while commands
19693 (setq old (pop commands) new (pop commands))
19694 (if (fboundp 'command-remapping)
19695 (org-defkey map (vector 'remap old) new)
19696 (substitute-key-definition old new map global-map)))))
19698 (defun org-transpose-words ()
19699 "Transpose words for Org.
19700 This uses the `org-mode-transpose-word-syntax-table' syntax
19701 table, which interprets characters in `org-emphasis-alist' as
19702 word constituents."
19703 (interactive)
19704 (with-syntax-table org-mode-transpose-word-syntax-table
19705 (call-interactively 'transpose-words)))
19706 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19708 (when (eq org-enable-table-editor 'optimized)
19709 ;; If the user wants maximum table support, we need to hijack
19710 ;; some standard editing functions
19711 (org-remap org-mode-map
19712 'self-insert-command 'org-self-insert-command
19713 'delete-char 'org-delete-char
19714 'delete-backward-char 'org-delete-backward-char)
19715 (org-defkey org-mode-map "|" 'org-force-self-insert))
19717 (defvar org-ctrl-c-ctrl-c-hook nil
19718 "Hook for functions attaching themselves to `C-c C-c'.
19720 This can be used to add additional functionality to the C-c C-c
19721 key which executes context-dependent commands. This hook is run
19722 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19723 run after the last test.
19725 Each function will be called with no arguments. The function
19726 must check if the context is appropriate for it to act. If yes,
19727 it should do its thing and then return a non-nil value. If the
19728 context is wrong, just do nothing and return nil.")
19730 (defvar org-ctrl-c-ctrl-c-final-hook nil
19731 "Hook for functions attaching themselves to `C-c C-c'.
19733 This can be used to add additional functionality to the C-c C-c
19734 key which executes context-dependent commands. This hook is run
19735 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19736 before the first test.
19738 Each function will be called with no arguments. The function
19739 must check if the context is appropriate for it to act. If yes,
19740 it should do its thing and then return a non-nil value. If the
19741 context is wrong, just do nothing and return nil.")
19743 (defvar org-tab-first-hook nil
19744 "Hook for functions to attach themselves to TAB.
19745 See `org-ctrl-c-ctrl-c-hook' for more information.
19746 This hook runs as the first action when TAB is pressed, even before
19747 `org-cycle' messes around with the `outline-regexp' to cater for
19748 inline tasks and plain list item folding.
19749 If any function in this hook returns t, any other actions that
19750 would have been caused by TAB (such as table field motion or visibility
19751 cycling) will not occur.")
19753 (defvar org-tab-after-check-for-table-hook nil
19754 "Hook for functions to attach themselves to TAB.
19755 See `org-ctrl-c-ctrl-c-hook' for more information.
19756 This hook runs after it has been established that the cursor is not in a
19757 table, but before checking if the cursor is in a headline or if global cycling
19758 should be done.
19759 If any function in this hook returns t, not other actions like visibility
19760 cycling will be done.")
19762 (defvar org-tab-after-check-for-cycling-hook nil
19763 "Hook for functions to attach themselves to TAB.
19764 See `org-ctrl-c-ctrl-c-hook' for more information.
19765 This hook runs after it has been established that not table field motion and
19766 not visibility should be done because of current context. This is probably
19767 the place where a package like yasnippets can hook in.")
19769 (defvar org-tab-before-tab-emulation-hook nil
19770 "Hook for functions to attach themselves to TAB.
19771 See `org-ctrl-c-ctrl-c-hook' for more information.
19772 This hook runs after every other options for TAB have been exhausted, but
19773 before indentation and \t insertion takes place.")
19775 (defvar org-metaleft-hook nil
19776 "Hook for functions attaching themselves to `M-left'.
19777 See `org-ctrl-c-ctrl-c-hook' for more information.")
19778 (defvar org-metaright-hook nil
19779 "Hook for functions attaching themselves to `M-right'.
19780 See `org-ctrl-c-ctrl-c-hook' for more information.")
19781 (defvar org-metaup-hook nil
19782 "Hook for functions attaching themselves to `M-up'.
19783 See `org-ctrl-c-ctrl-c-hook' for more information.")
19784 (defvar org-metadown-hook nil
19785 "Hook for functions attaching themselves to `M-down'.
19786 See `org-ctrl-c-ctrl-c-hook' for more information.")
19787 (defvar org-shiftmetaleft-hook nil
19788 "Hook for functions attaching themselves to `M-S-left'.
19789 See `org-ctrl-c-ctrl-c-hook' for more information.")
19790 (defvar org-shiftmetaright-hook nil
19791 "Hook for functions attaching themselves to `M-S-right'.
19792 See `org-ctrl-c-ctrl-c-hook' for more information.")
19793 (defvar org-shiftmetaup-hook nil
19794 "Hook for functions attaching themselves to `M-S-up'.
19795 See `org-ctrl-c-ctrl-c-hook' for more information.")
19796 (defvar org-shiftmetadown-hook nil
19797 "Hook for functions attaching themselves to `M-S-down'.
19798 See `org-ctrl-c-ctrl-c-hook' for more information.")
19799 (defvar org-metareturn-hook nil
19800 "Hook for functions attaching themselves to `M-RET'.
19801 See `org-ctrl-c-ctrl-c-hook' for more information.")
19802 (defvar org-shiftup-hook nil
19803 "Hook for functions attaching themselves to `S-up'.
19804 See `org-ctrl-c-ctrl-c-hook' for more information.")
19805 (defvar org-shiftup-final-hook nil
19806 "Hook for functions attaching themselves to `S-up'.
19807 This one runs after all other options except shift-select have been excluded.
19808 See `org-ctrl-c-ctrl-c-hook' for more information.")
19809 (defvar org-shiftdown-hook nil
19810 "Hook for functions attaching themselves to `S-down'.
19811 See `org-ctrl-c-ctrl-c-hook' for more information.")
19812 (defvar org-shiftdown-final-hook nil
19813 "Hook for functions attaching themselves to `S-down'.
19814 This one runs after all other options except shift-select have been excluded.
19815 See `org-ctrl-c-ctrl-c-hook' for more information.")
19816 (defvar org-shiftleft-hook nil
19817 "Hook for functions attaching themselves to `S-left'.
19818 See `org-ctrl-c-ctrl-c-hook' for more information.")
19819 (defvar org-shiftleft-final-hook nil
19820 "Hook for functions attaching themselves to `S-left'.
19821 This one runs after all other options except shift-select have been excluded.
19822 See `org-ctrl-c-ctrl-c-hook' for more information.")
19823 (defvar org-shiftright-hook nil
19824 "Hook for functions attaching themselves to `S-right'.
19825 See `org-ctrl-c-ctrl-c-hook' for more information.")
19826 (defvar org-shiftright-final-hook nil
19827 "Hook for functions attaching themselves to `S-right'.
19828 This one runs after all other options except shift-select have been excluded.
19829 See `org-ctrl-c-ctrl-c-hook' for more information.")
19831 (defun org-modifier-cursor-error ()
19832 "Throw an error, a modified cursor command was applied in wrong context."
19833 (user-error "This command is active in special context like tables, headlines or items"))
19835 (defun org-shiftselect-error ()
19836 "Throw an error because Shift-Cursor command was applied in wrong context."
19837 (if (and (boundp 'shift-select-mode) shift-select-mode)
19838 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19839 (user-error "This command works only in special context like headlines or timestamps")))
19841 (defun org-call-for-shift-select (cmd)
19842 (let ((this-command-keys-shift-translated t))
19843 (call-interactively cmd)))
19845 (defun org-shifttab (&optional arg)
19846 "Global visibility cycling or move to previous table field.
19847 Call `org-table-previous-field' within a table.
19848 When ARG is nil, cycle globally through visibility states.
19849 When ARG is a numeric prefix, show contents of this level."
19850 (interactive "P")
19851 (cond
19852 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19853 ((integerp arg)
19854 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19855 (message "Content view to level: %d" arg)
19856 (org-content (prefix-numeric-value arg2))
19857 (org-cycle-show-empty-lines t)
19858 (setq org-cycle-global-status 'overview)))
19859 (t (call-interactively 'org-global-cycle))))
19861 (defun org-shiftmetaleft ()
19862 "Promote subtree or delete table column.
19863 Calls `org-promote-subtree', `org-outdent-item-tree', or
19864 `org-table-delete-column', depending on context. See the
19865 individual commands for more information."
19866 (interactive)
19867 (cond
19868 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19869 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19870 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19871 ((if (not (org-region-active-p)) (org-at-item-p)
19872 (save-excursion (goto-char (region-beginning))
19873 (org-at-item-p)))
19874 (call-interactively 'org-outdent-item-tree))
19875 (t (org-modifier-cursor-error))))
19877 (defun org-shiftmetaright ()
19878 "Demote subtree or insert table column.
19879 Calls `org-demote-subtree', `org-indent-item-tree', or
19880 `org-table-insert-column', depending on context. See the
19881 individual commands for more information."
19882 (interactive)
19883 (cond
19884 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19885 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19886 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19887 ((if (not (org-region-active-p)) (org-at-item-p)
19888 (save-excursion (goto-char (region-beginning))
19889 (org-at-item-p)))
19890 (call-interactively 'org-indent-item-tree))
19891 (t (org-modifier-cursor-error))))
19893 (defun org-shiftmetaup (&optional arg)
19894 "Move subtree up or kill table row.
19895 Calls `org-move-subtree-up' or `org-table-kill-row' or
19896 `org-move-item-up' or `org-timestamp-up', depending on context.
19897 See the individual commands for more information."
19898 (interactive "P")
19899 (cond
19900 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19901 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19902 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19903 ((org-at-item-p) (call-interactively 'org-move-item-up))
19904 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19905 (call-interactively 'org-timestamp-up)))
19906 (t (call-interactively 'org-drag-line-backward))))
19908 (defun org-shiftmetadown (&optional arg)
19909 "Move subtree down or insert table row.
19910 Calls `org-move-subtree-down' or `org-table-insert-row' or
19911 `org-move-item-down' or `org-timestamp-up', depending on context.
19912 See the individual commands for more information."
19913 (interactive "P")
19914 (cond
19915 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19916 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19917 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19918 ((org-at-item-p) (call-interactively 'org-move-item-down))
19919 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19920 (call-interactively 'org-timestamp-down)))
19921 (t (call-interactively 'org-drag-line-forward))))
19923 (defsubst org-hidden-tree-error ()
19924 (user-error
19925 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19927 (defun org-metaleft (&optional arg)
19928 "Promote heading or move table column to left.
19929 Calls `org-do-promote' or `org-table-move-column', depending on context.
19930 With no specific context, calls the Emacs default `backward-word'.
19931 See the individual commands for more information."
19932 (interactive "P")
19933 (cond
19934 ((run-hook-with-args-until-success 'org-metaleft-hook))
19935 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19936 ((org-with-limited-levels
19937 (or (org-at-heading-p)
19938 (and (org-region-active-p)
19939 (save-excursion
19940 (goto-char (region-beginning))
19941 (org-at-heading-p)))))
19942 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19943 (call-interactively 'org-do-promote))
19944 ;; At an inline task.
19945 ((org-at-heading-p)
19946 (call-interactively 'org-inlinetask-promote))
19947 ((or (org-at-item-p)
19948 (and (org-region-active-p)
19949 (save-excursion
19950 (goto-char (region-beginning))
19951 (org-at-item-p))))
19952 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19953 (call-interactively 'org-outdent-item))
19954 (t (call-interactively 'backward-word))))
19956 (defun org-metaright (&optional arg)
19957 "Demote a subtree, a list item or move table column to right.
19958 In front of a drawer or a block keyword, indent it correctly.
19959 With no specific context, calls the Emacs default `forward-word'.
19960 See the individual commands for more information."
19961 (interactive "P")
19962 (cond
19963 ((run-hook-with-args-until-success 'org-metaright-hook))
19964 ((org-at-table-p) (call-interactively 'org-table-move-column))
19965 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19966 ((org-at-block-p) (call-interactively 'org-indent-block))
19967 ((org-with-limited-levels
19968 (or (org-at-heading-p)
19969 (and (org-region-active-p)
19970 (save-excursion
19971 (goto-char (region-beginning))
19972 (org-at-heading-p)))))
19973 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19974 (call-interactively 'org-do-demote))
19975 ;; At an inline task.
19976 ((org-at-heading-p)
19977 (call-interactively 'org-inlinetask-demote))
19978 ((or (org-at-item-p)
19979 (and (org-region-active-p)
19980 (save-excursion
19981 (goto-char (region-beginning))
19982 (org-at-item-p))))
19983 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19984 (call-interactively 'org-indent-item))
19985 (t (call-interactively 'forward-word))))
19987 (defun org-check-for-hidden (what)
19988 "Check if there are hidden headlines/items in the current visual line.
19989 WHAT can be either `headlines' or `items'. If the current line is
19990 an outline or item heading and it has a folded subtree below it,
19991 this function returns t, nil otherwise."
19992 (let ((re (cond
19993 ((eq what 'headlines) org-outline-regexp-bol)
19994 ((eq what 'items) (org-item-beginning-re))
19995 (t (error "This should not happen"))))
19996 beg end)
19997 (save-excursion
19998 (catch 'exit
19999 (unless (org-region-active-p)
20000 (setq beg (point-at-bol))
20001 (beginning-of-line 2)
20002 (while (and (not (eobp)) ;; this is like `next-line'
20003 (get-char-property (1- (point)) 'invisible))
20004 (beginning-of-line 2))
20005 (setq end (point))
20006 (goto-char beg)
20007 (goto-char (point-at-eol))
20008 (setq end (max end (point)))
20009 (while (re-search-forward re end t)
20010 (if (get-char-property (match-beginning 0) 'invisible)
20011 (throw 'exit t))))
20012 nil))))
20014 (defun org-metaup (&optional arg)
20015 "Move subtree up or move table row up.
20016 Calls `org-move-subtree-up' or `org-table-move-row' or
20017 `org-move-item-up', depending on context. See the individual commands
20018 for more information."
20019 (interactive "P")
20020 (cond
20021 ((run-hook-with-args-until-success 'org-metaup-hook))
20022 ((org-region-active-p)
20023 (let* ((a (min (region-beginning) (region-end)))
20024 (b (1- (max (region-beginning) (region-end))))
20025 (c (save-excursion (goto-char a)
20026 (move-beginning-of-line 0)))
20027 (d (save-excursion (goto-char a)
20028 (move-end-of-line 0) (point))))
20029 (transpose-regions a b c d)
20030 (goto-char c)))
20031 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20032 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20033 ((org-at-item-p) (call-interactively 'org-move-item-up))
20034 (t (org-drag-element-backward))))
20036 (defun org-metadown (&optional arg)
20037 "Move subtree down or move table row down.
20038 Calls `org-move-subtree-down' or `org-table-move-row' or
20039 `org-move-item-down', depending on context. See the individual
20040 commands for more information."
20041 (interactive "P")
20042 (cond
20043 ((run-hook-with-args-until-success 'org-metadown-hook))
20044 ((org-region-active-p)
20045 (let* ((a (min (region-beginning) (region-end)))
20046 (b (max (region-beginning) (region-end)))
20047 (c (save-excursion (goto-char b)
20048 (move-beginning-of-line 1)))
20049 (d (save-excursion (goto-char b)
20050 (move-end-of-line 1) (1+ (point)))))
20051 (transpose-regions a b c d)
20052 (goto-char d)))
20053 ((org-at-table-p) (call-interactively 'org-table-move-row))
20054 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20055 ((org-at-item-p) (call-interactively 'org-move-item-down))
20056 (t (org-drag-element-forward))))
20058 (defun org-shiftup (&optional arg)
20059 "Increase item in timestamp or increase priority of current headline.
20060 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20061 depending on context. See the individual commands for more information."
20062 (interactive "P")
20063 (cond
20064 ((run-hook-with-args-until-success 'org-shiftup-hook))
20065 ((and org-support-shift-select (org-region-active-p))
20066 (org-call-for-shift-select 'previous-line))
20067 ((org-at-timestamp-p t)
20068 (call-interactively (if org-edit-timestamp-down-means-later
20069 'org-timestamp-down 'org-timestamp-up)))
20070 ((and (not (eq org-support-shift-select 'always))
20071 org-enable-priority-commands
20072 (org-at-heading-p))
20073 (call-interactively 'org-priority-up))
20074 ((and (not org-support-shift-select) (org-at-item-p))
20075 (call-interactively 'org-previous-item))
20076 ((org-clocktable-try-shift 'up arg))
20077 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20078 (org-support-shift-select
20079 (org-call-for-shift-select 'previous-line))
20080 (t (org-shiftselect-error))))
20082 (defun org-shiftdown (&optional arg)
20083 "Decrease item in timestamp or decrease priority of current headline.
20084 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20085 depending on context. See the individual commands for more information."
20086 (interactive "P")
20087 (cond
20088 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20089 ((and org-support-shift-select (org-region-active-p))
20090 (org-call-for-shift-select 'next-line))
20091 ((org-at-timestamp-p t)
20092 (call-interactively (if org-edit-timestamp-down-means-later
20093 'org-timestamp-up 'org-timestamp-down)))
20094 ((and (not (eq org-support-shift-select 'always))
20095 org-enable-priority-commands
20096 (org-at-heading-p))
20097 (call-interactively 'org-priority-down))
20098 ((and (not org-support-shift-select) (org-at-item-p))
20099 (call-interactively 'org-next-item))
20100 ((org-clocktable-try-shift 'down arg))
20101 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20102 (org-support-shift-select
20103 (org-call-for-shift-select 'next-line))
20104 (t (org-shiftselect-error))))
20106 (defun org-shiftright (&optional arg)
20107 "Cycle the thing at point or in the current line, depending on context.
20108 Depending on context, this does one of the following:
20110 - switch a timestamp at point one day into the future
20111 - on a headline, switch to the next TODO keyword.
20112 - on an item, switch entire list to the next bullet type
20113 - on a property line, switch to the next allowed value
20114 - on a clocktable definition line, move time block into the future"
20115 (interactive "P")
20116 (cond
20117 ((run-hook-with-args-until-success 'org-shiftright-hook))
20118 ((and org-support-shift-select (org-region-active-p))
20119 (org-call-for-shift-select 'forward-char))
20120 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20121 ((and (not (eq org-support-shift-select 'always))
20122 (org-at-heading-p))
20123 (let ((org-inhibit-logging
20124 (not org-treat-S-cursor-todo-selection-as-state-change))
20125 (org-inhibit-blocking
20126 (not org-treat-S-cursor-todo-selection-as-state-change)))
20127 (org-call-with-arg 'org-todo 'right)))
20128 ((or (and org-support-shift-select
20129 (not (eq org-support-shift-select 'always))
20130 (org-at-item-bullet-p))
20131 (and (not org-support-shift-select) (org-at-item-p)))
20132 (org-call-with-arg 'org-cycle-list-bullet nil))
20133 ((and (not (eq org-support-shift-select 'always))
20134 (org-at-property-p))
20135 (call-interactively 'org-property-next-allowed-value))
20136 ((org-clocktable-try-shift 'right arg))
20137 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20138 (org-support-shift-select
20139 (org-call-for-shift-select 'forward-char))
20140 (t (org-shiftselect-error))))
20142 (defun org-shiftleft (&optional arg)
20143 "Cycle the thing at point or in the current line, depending on context.
20144 Depending on context, this does one of the following:
20146 - switch a timestamp at point one day into the past
20147 - on a headline, switch to the previous TODO keyword.
20148 - on an item, switch entire list to the previous bullet type
20149 - on a property line, switch to the previous allowed value
20150 - on a clocktable definition line, move time block into the past"
20151 (interactive "P")
20152 (cond
20153 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20154 ((and org-support-shift-select (org-region-active-p))
20155 (org-call-for-shift-select 'backward-char))
20156 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20157 ((and (not (eq org-support-shift-select 'always))
20158 (org-at-heading-p))
20159 (let ((org-inhibit-logging
20160 (not org-treat-S-cursor-todo-selection-as-state-change))
20161 (org-inhibit-blocking
20162 (not org-treat-S-cursor-todo-selection-as-state-change)))
20163 (org-call-with-arg 'org-todo 'left)))
20164 ((or (and org-support-shift-select
20165 (not (eq org-support-shift-select 'always))
20166 (org-at-item-bullet-p))
20167 (and (not org-support-shift-select) (org-at-item-p)))
20168 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20169 ((and (not (eq org-support-shift-select 'always))
20170 (org-at-property-p))
20171 (call-interactively 'org-property-previous-allowed-value))
20172 ((org-clocktable-try-shift 'left arg))
20173 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20174 (org-support-shift-select
20175 (org-call-for-shift-select 'backward-char))
20176 (t (org-shiftselect-error))))
20178 (defun org-shiftcontrolright ()
20179 "Switch to next TODO set."
20180 (interactive)
20181 (cond
20182 ((and org-support-shift-select (org-region-active-p))
20183 (org-call-for-shift-select 'forward-word))
20184 ((and (not (eq org-support-shift-select 'always))
20185 (org-at-heading-p))
20186 (org-call-with-arg 'org-todo 'nextset))
20187 (org-support-shift-select
20188 (org-call-for-shift-select 'forward-word))
20189 (t (org-shiftselect-error))))
20191 (defun org-shiftcontrolleft ()
20192 "Switch to previous TODO set."
20193 (interactive)
20194 (cond
20195 ((and org-support-shift-select (org-region-active-p))
20196 (org-call-for-shift-select 'backward-word))
20197 ((and (not (eq org-support-shift-select 'always))
20198 (org-at-heading-p))
20199 (org-call-with-arg 'org-todo 'previousset))
20200 (org-support-shift-select
20201 (org-call-for-shift-select 'backward-word))
20202 (t (org-shiftselect-error))))
20204 (defun org-shiftcontrolup (&optional n)
20205 "Change timestamps synchronously up in CLOCK log lines.
20206 Optional argument N tells to change by that many units."
20207 (interactive "P")
20208 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20209 (let (org-support-shift-select)
20210 (org-clock-timestamps-up n))
20211 (user-error "Not at a clock log")))
20213 (defun org-shiftcontroldown (&optional n)
20214 "Change timestamps synchronously down in CLOCK log lines.
20215 Optional argument N tells to change by that many units."
20216 (interactive "P")
20217 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20218 (let (org-support-shift-select)
20219 (org-clock-timestamps-down n))
20220 (user-error "Not at a clock log")))
20222 (defun org-ctrl-c-ret ()
20223 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20224 (interactive)
20225 (cond
20226 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20227 (t (call-interactively 'org-insert-heading))))
20229 (defun org-find-visible ()
20230 (let ((s (point)))
20231 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20232 (get-char-property s 'invisible)))
20234 (defun org-find-invisible ()
20235 (let ((s (point)))
20236 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20237 (not (get-char-property s 'invisible))))
20240 (defun org-copy-visible (beg end)
20241 "Copy the visible parts of the region."
20242 (interactive "r")
20243 (let (snippets s)
20244 (save-excursion
20245 (save-restriction
20246 (narrow-to-region beg end)
20247 (setq s (goto-char (point-min)))
20248 (while (not (= (point) (point-max)))
20249 (goto-char (org-find-invisible))
20250 (push (buffer-substring s (point)) snippets)
20251 (setq s (goto-char (org-find-visible))))))
20252 (kill-new (apply 'concat (nreverse snippets)))))
20254 (defun org-copy-special ()
20255 "Copy region in table or copy current subtree.
20256 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20257 See the individual commands for more information."
20258 (interactive)
20259 (call-interactively
20260 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20262 (defun org-cut-special ()
20263 "Cut region in table or cut current subtree.
20264 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20265 See the individual commands for more information."
20266 (interactive)
20267 (call-interactively
20268 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20270 (defun org-paste-special (arg)
20271 "Paste rectangular region into table, or past subtree relative to level.
20272 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20273 See the individual commands for more information."
20274 (interactive "P")
20275 (if (org-at-table-p)
20276 (org-table-paste-rectangle)
20277 (org-paste-subtree arg)))
20279 (defsubst org-in-fixed-width-region-p ()
20280 "Is point in a fixed-width region?"
20281 (save-match-data
20282 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20284 (defun org-edit-special (&optional arg)
20285 "Call a special editor for the element at point.
20286 When at a table, call the formula editor with `org-table-edit-formulas'.
20287 When in a source code block, call `org-edit-src-code'.
20288 When in a fixed-width region, call `org-edit-fixed-width-region'.
20289 When at an #+INCLUDE keyword, visit the included file.
20290 On a link, call `ffap' to visit the link at point.
20291 Otherwise, return a user error."
20292 (interactive "P")
20293 (let ((element (org-element-at-point)))
20294 (assert (not buffer-read-only) nil
20295 "Buffer is read-only: %s" (buffer-name))
20296 (case (org-element-type element)
20297 (src-block
20298 (if (not arg) (org-edit-src-code)
20299 (let* ((info (org-babel-get-src-block-info))
20300 (lang (nth 0 info))
20301 (params (nth 2 info))
20302 (session (cdr (assq :session params))))
20303 (if (not session) (org-edit-src-code)
20304 ;; At a src-block with a session and function called with
20305 ;; an ARG: switch to the buffer related to the inferior
20306 ;; process.
20307 (switch-to-buffer
20308 (funcall (intern (concat "org-babel-prep-session:" lang))
20309 session params))))))
20310 (keyword
20311 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20312 (find-file-other-window
20313 (org-remove-double-quotes
20314 (car (org-split-string (org-element-property :value element)))))
20315 (user-error "No special environment to edit here")))
20316 (table
20317 (if (eq (org-element-property :type element) 'table.el)
20318 (org-edit-src-code)
20319 (call-interactively 'org-table-edit-formulas)))
20320 ;; Only Org tables contain `table-row' type elements.
20321 (table-row (call-interactively 'org-table-edit-formulas))
20322 ((example-block export-block) (org-edit-src-code))
20323 (fixed-width (org-edit-fixed-width-region))
20324 (otherwise
20325 ;; No notable element at point. Though, we may be at a link,
20326 ;; which is an object. Thus, scan deeper.
20327 (if (eq (org-element-type (org-element-context element)) 'link)
20328 (call-interactively 'ffap)
20329 (user-error "No special environment to edit here"))))))
20331 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20332 (defun org-ctrl-c-ctrl-c (&optional arg)
20333 "Set tags in headline, or update according to changed information at point.
20335 This command does many different things, depending on context:
20337 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20338 this is what we do.
20340 - If the cursor is on a statistics cookie, update it.
20342 - If the cursor is in a headline, prompt for tags and insert them
20343 into the current line, aligned to `org-tags-column'. When called
20344 with prefix arg, realign all tags in the current buffer.
20346 - If the cursor is in one of the special #+KEYWORD lines, this
20347 triggers scanning the buffer for these lines and updating the
20348 information.
20350 - If the cursor is inside a table, realign the table. This command
20351 works even if the automatic table editor has been turned off.
20353 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20354 the entire table.
20356 - If the cursor is at a footnote reference or definition, jump to
20357 the corresponding definition or references, respectively.
20359 - If the cursor is a the beginning of a dynamic block, update it.
20361 - If the current buffer is a capture buffer, close note and file it.
20363 - If the cursor is on a <<<target>>>, update radio targets and
20364 corresponding links in this buffer.
20366 - If the cursor is on a numbered item in a plain list, renumber the
20367 ordered list.
20369 - If the cursor is on a checkbox, toggle it.
20371 - If the cursor is on a code block, evaluate it. The variable
20372 `org-confirm-babel-evaluate' can be used to control prompting
20373 before code block evaluation, by default every code block
20374 evaluation requires confirmation. Code block evaluation can be
20375 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20376 (interactive "P")
20377 (cond
20378 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20379 org-occur-highlights
20380 org-latex-fragment-image-overlays)
20381 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20382 (org-remove-occur-highlights)
20383 (org-remove-latex-fragment-image-overlays)
20384 (message "Temporary highlights/overlays removed from current buffer"))
20385 ((and (local-variable-p 'org-finish-function (current-buffer))
20386 (fboundp org-finish-function))
20387 (funcall org-finish-function))
20388 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20390 (let* ((context (org-element-context)) (type (org-element-type context)))
20391 ;; Test if point is within a blank line.
20392 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20393 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20394 (user-error "C-c C-c can do nothing useful at this location"))
20395 (case type
20396 ;; When at a link, act according to the parent instead.
20397 (link (setq context (org-element-property :parent context))
20398 (setq type (org-element-type context)))
20399 ;; Unsupported object types: refer to the first supported
20400 ;; element or object containing it.
20401 ((bold code entity export-snippet inline-babel-call inline-src-block
20402 italic latex-fragment line-break macro strike-through subscript
20403 superscript underline verbatim)
20404 (while (and (setq context (org-element-property :parent context))
20405 (not (memq (setq type (org-element-type context))
20406 '(radio-target paragraph verse-block
20407 table-cell)))))))
20408 ;; For convenience: at the first line of a paragraph on the
20409 ;; same line as an item, apply function on that item instead.
20410 (when (eq type 'paragraph)
20411 (let ((parent (org-element-property :parent context)))
20412 (when (and (eq (org-element-type parent) 'item)
20413 (= (point-at-bol) (org-element-property :begin parent)))
20414 (setq context parent type 'item))))
20415 ;; Act according to type of element or object at point.
20416 (case type
20417 (clock (org-clock-update-time-maybe))
20418 (dynamic-block
20419 (save-excursion
20420 (goto-char (org-element-property :post-affiliated context))
20421 (org-update-dblock)))
20422 (footnote-definition
20423 (goto-char (org-element-property :post-affiliated context))
20424 (call-interactively 'org-footnote-action))
20425 (footnote-reference (call-interactively 'org-footnote-action))
20426 ((headline inlinetask)
20427 (save-excursion (goto-char (org-element-property :begin context))
20428 (call-interactively 'org-set-tags)))
20429 (item
20430 ;; At an item: a double C-u set checkbox to "[-]"
20431 ;; unconditionally, whereas a single one will toggle its
20432 ;; presence. Without an universal argument, if the item
20433 ;; has a checkbox, toggle it. Otherwise repair the list.
20434 (let* ((box (org-element-property :checkbox context))
20435 (struct (org-element-property :structure context))
20436 (old-struct (copy-tree struct))
20437 (parents (org-list-parents-alist struct))
20438 (prevs (org-list-prevs-alist struct))
20439 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20440 (org-list-set-checkbox
20441 (org-element-property :begin context) struct
20442 (cond ((equal arg '(16)) "[-]")
20443 ((and (not box) (equal arg '(4))) "[ ]")
20444 ((or (not box) (equal arg '(4))) nil)
20445 ((eq box 'on) "[ ]")
20446 (t "[X]")))
20447 ;; Mimic `org-list-write-struct' but with grabbing
20448 ;; a return value from `org-list-struct-fix-box'.
20449 (org-list-struct-fix-ind struct parents 2)
20450 (org-list-struct-fix-item-end struct)
20451 (org-list-struct-fix-bul struct prevs)
20452 (org-list-struct-fix-ind struct parents)
20453 (let ((block-item
20454 (org-list-struct-fix-box struct parents prevs orderedp)))
20455 (if (and box (equal struct old-struct))
20456 (if (equal arg '(16))
20457 (message "Checkboxes already reset")
20458 (user-error "Cannot toggle this checkbox: %s"
20459 (if (eq box 'on)
20460 "all subitems checked"
20461 "unchecked subitems")))
20462 (org-list-struct-apply-struct struct old-struct)
20463 (org-update-checkbox-count-maybe))
20464 (when block-item
20465 (message "Checkboxes were removed due to empty box at line %d"
20466 (org-current-line block-item))))))
20467 (keyword
20468 (let ((org-inhibit-startup-visibility-stuff t)
20469 (org-startup-align-all-tables nil))
20470 (when (boundp 'org-table-coordinate-overlays)
20471 (mapc 'delete-overlay org-table-coordinate-overlays)
20472 (setq org-table-coordinate-overlays nil))
20473 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20474 (message "Local setup has been refreshed"))
20475 (plain-list
20476 ;; At a plain list, with a double C-u argument, set
20477 ;; checkboxes of each item to "[-]", whereas a single one
20478 ;; will toggle their presence according to the state of the
20479 ;; first item in the list. Without an argument, repair the
20480 ;; list.
20481 (let* ((begin (org-element-property :contents-begin context))
20482 (beginm (move-marker (make-marker) begin))
20483 (struct (org-element-property :structure context))
20484 (old-struct (copy-tree struct))
20485 (first-box (save-excursion
20486 (goto-char begin)
20487 (looking-at org-list-full-item-re)
20488 (match-string-no-properties 3)))
20489 (new-box (cond ((equal arg '(16)) "[-]")
20490 ((equal arg '(4)) (unless first-box "[ ]"))
20491 ((equal first-box "[X]") "[ ]")
20492 (t "[X]"))))
20493 (cond
20494 (arg
20495 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20496 (org-list-get-all-items
20497 begin struct (org-list-prevs-alist struct))))
20498 ((and first-box (eq (point) begin))
20499 ;; For convenience, when point is at bol on the first
20500 ;; item of the list and no argument is provided, simply
20501 ;; toggle checkbox of that item, if any.
20502 (org-list-set-checkbox begin struct new-box)))
20503 (org-list-write-struct
20504 struct (org-list-parents-alist struct) old-struct)
20505 (org-update-checkbox-count-maybe)
20506 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20507 ((property-drawer node-property)
20508 (call-interactively 'org-property-action))
20509 ((radio-target target)
20510 (call-interactively 'org-update-radio-target-regexp))
20511 (statistics-cookie
20512 (call-interactively 'org-update-statistics-cookies))
20513 ((table table-cell table-row)
20514 ;; At a table, recalculate every field and align it. Also
20515 ;; send the table if necessary. If the table has
20516 ;; a `table.el' type, just give up. At a table row or
20517 ;; cell, maybe recalculate line but always align table.
20518 (if (eq (org-element-property :type context) 'table.el)
20519 (message "Use C-c ' to edit table.el tables")
20520 (let ((org-enable-table-editor t))
20521 (if (or (eq type 'table)
20522 ;; Check if point is at a TBLFM line.
20523 (and (eq type 'table-row)
20524 (= (point) (org-element-property :end context))))
20525 (save-excursion
20526 (if (org-at-TBLFM-p)
20527 (progn (require 'org-table)
20528 (org-table-calc-current-TBLFM))
20529 (goto-char (org-element-property :contents-begin context))
20530 (org-call-with-arg 'org-table-recalculate (or arg t))
20531 (orgtbl-send-table 'maybe)))
20532 (org-table-maybe-eval-formula)
20533 (cond (arg (call-interactively 'org-table-recalculate))
20534 ((org-table-maybe-recalculate-line))
20535 (t (org-table-align)))))))
20536 (timestamp (org-timestamp-change 0 'day))
20537 (otherwise
20538 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20539 (user-error
20540 "C-c C-c can do nothing useful at this location")))))))))
20542 (defun org-mode-restart ()
20543 (interactive)
20544 (let ((indent-status (org-bound-and-true-p org-indent-mode)))
20545 (funcall major-mode)
20546 (hack-local-variables)
20547 (when (and indent-status (not (org-bound-and-true-p org-indent-mode)))
20548 (org-indent-mode -1)))
20549 (message "%s restarted" major-mode))
20551 (defun org-kill-note-or-show-branches ()
20552 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20553 (interactive)
20554 (if (not org-finish-function)
20555 (progn
20556 (hide-subtree)
20557 (call-interactively 'show-branches))
20558 (let ((org-note-abort t))
20559 (funcall org-finish-function))))
20561 (defun org-open-line (n)
20562 "Insert a new row in tables, call `open-line' elsewhere.
20563 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
20564 (interactive "*p")
20565 (cond
20566 ((not org-special-ctrl-o)
20567 (open-line n))
20568 ((org-at-table-p)
20569 (org-table-insert-row))
20571 (open-line n))))
20573 (defun org-return (&optional indent)
20574 "Goto next table row or insert a newline.
20575 Calls `org-table-next-row' or `newline', depending on context.
20576 See the individual commands for more information."
20577 (interactive)
20578 (let (org-ts-what)
20579 (cond
20580 ((or (bobp) (org-in-src-block-p))
20581 (if indent (newline-and-indent) (newline)))
20582 ((org-at-table-p)
20583 (org-table-justify-field-maybe)
20584 (call-interactively 'org-table-next-row))
20585 ;; when `newline-and-indent' is called within a list, make sure
20586 ;; text moved stays inside the item.
20587 ((and (org-in-item-p) indent)
20588 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20589 (progn
20590 (save-match-data (newline))
20591 (org-indent-line-to (length (match-string 0))))
20592 (let ((ind (org-get-indentation)))
20593 (newline)
20594 (if (org-looking-back org-list-end-re)
20595 (org-indent-line)
20596 (org-indent-line-to ind)))))
20597 ((and org-return-follows-link
20598 (org-at-timestamp-p t)
20599 (not (eq org-ts-what 'after)))
20600 (org-follow-timestamp-link))
20601 ((and org-return-follows-link
20602 (let ((tprop (get-text-property (point) 'face)))
20603 (or (eq tprop 'org-link)
20604 (and (listp tprop) (memq 'org-link tprop)))))
20605 (call-interactively 'org-open-at-point))
20606 ((and (org-at-heading-p)
20607 (looking-at
20608 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20609 (org-show-entry)
20610 (end-of-line 1)
20611 (newline))
20612 (t (if indent (newline-and-indent) (newline))))))
20614 (defun org-return-indent ()
20615 "Goto next table row or insert a newline and indent.
20616 Calls `org-table-next-row' or `newline-and-indent', depending on
20617 context. See the individual commands for more information."
20618 (interactive)
20619 (org-return t))
20621 (defun org-ctrl-c-star ()
20622 "Compute table, or change heading status of lines.
20623 Calls `org-table-recalculate' or `org-toggle-heading',
20624 depending on context."
20625 (interactive)
20626 (cond
20627 ((org-at-table-p)
20628 (call-interactively 'org-table-recalculate))
20630 ;; Convert all lines in region to list items
20631 (call-interactively 'org-toggle-heading))))
20633 (defun org-ctrl-c-minus ()
20634 "Insert separator line in table or modify bullet status of line.
20635 Also turns a plain line or a region of lines into list items.
20636 Calls `org-table-insert-hline', `org-toggle-item', or
20637 `org-cycle-list-bullet', depending on context."
20638 (interactive)
20639 (cond
20640 ((org-at-table-p)
20641 (call-interactively 'org-table-insert-hline))
20642 ((org-region-active-p)
20643 (call-interactively 'org-toggle-item))
20644 ((org-in-item-p)
20645 (call-interactively 'org-cycle-list-bullet))
20647 (call-interactively 'org-toggle-item))))
20649 (defun org-toggle-item (arg)
20650 "Convert headings or normal lines to items, items to normal lines.
20651 If there is no active region, only the current line is considered.
20653 If the first non blank line in the region is a headline, convert
20654 all headlines to items, shifting text accordingly.
20656 If it is an item, convert all items to normal lines.
20658 If it is normal text, change region into a list of items.
20659 With a prefix argument ARG, change the region in a single item."
20660 (interactive "P")
20661 (let ((shift-text
20662 (function
20663 ;; Shift text in current section to IND, from point to END.
20664 ;; The function leaves point to END line.
20665 (lambda (ind end)
20666 (let ((min-i 1000) (end (copy-marker end)))
20667 ;; First determine the minimum indentation (MIN-I) of
20668 ;; the text.
20669 (save-excursion
20670 (catch 'exit
20671 (while (< (point) end)
20672 (let ((i (org-get-indentation)))
20673 (cond
20674 ;; Skip blank lines and inline tasks.
20675 ((looking-at "^[ \t]*$"))
20676 ((looking-at org-outline-regexp-bol))
20677 ;; We can't find less than 0 indentation.
20678 ((zerop i) (throw 'exit (setq min-i 0)))
20679 ((< i min-i) (setq min-i i))))
20680 (forward-line))))
20681 ;; Then indent each line so that a line indented to
20682 ;; MIN-I becomes indented to IND. Ignore blank lines
20683 ;; and inline tasks in the process.
20684 (let ((delta (- ind min-i)))
20685 (while (< (point) end)
20686 (unless (or (looking-at "^[ \t]*$")
20687 (looking-at org-outline-regexp-bol))
20688 (org-indent-line-to (+ (org-get-indentation) delta)))
20689 (forward-line)))))))
20690 (skip-blanks
20691 (function
20692 ;; Return beginning of first non-blank line, starting from
20693 ;; line at POS.
20694 (lambda (pos)
20695 (save-excursion
20696 (goto-char pos)
20697 (skip-chars-forward " \r\t\n")
20698 (point-at-bol)))))
20699 beg end)
20700 ;; Determine boundaries of changes.
20701 (if (org-region-active-p)
20702 (setq beg (funcall skip-blanks (region-beginning))
20703 end (copy-marker (region-end)))
20704 (setq beg (funcall skip-blanks (point-at-bol))
20705 end (copy-marker (point-at-eol))))
20706 ;; Depending on the starting line, choose an action on the text
20707 ;; between BEG and END.
20708 (org-with-limited-levels
20709 (save-excursion
20710 (goto-char beg)
20711 (cond
20712 ;; Case 1. Start at an item: de-itemize. Note that it only
20713 ;; happens when a region is active: `org-ctrl-c-minus'
20714 ;; would call `org-cycle-list-bullet' otherwise.
20715 ((org-at-item-p)
20716 (while (< (point) end)
20717 (when (org-at-item-p)
20718 (skip-chars-forward " \t")
20719 (delete-region (point) (match-end 0)))
20720 (forward-line)))
20721 ;; Case 2. Start at an heading: convert to items.
20722 ((org-at-heading-p)
20723 (let* ((bul (org-list-bullet-string "-"))
20724 (bul-len (length bul))
20725 (done (org-entry-is-done-p))
20726 (todo (org-entry-is-todo-p))
20727 ;; Indentation of the first heading. It should be
20728 ;; relative to the indentation of its parent, if any.
20729 (start-ind (save-excursion
20730 (cond
20731 ((not org-adapt-indentation) 0)
20732 ((not (outline-previous-heading)) 0)
20733 (t (length (match-string 0))))))
20734 ;; Level of first heading. Further headings will be
20735 ;; compared to it to determine hierarchy in the list.
20736 (ref-level (org-reduced-level (org-outline-level))))
20737 (when (or done todo) (org-todo ""))
20738 (while (< (point) end)
20739 (let* ((level (org-reduced-level (org-outline-level)))
20740 (delta (max 0 (- level ref-level))))
20741 ;; If current headline is less indented than the first
20742 ;; one, set it as reference, in order to preserve
20743 ;; subtrees.
20744 (when (< level ref-level) (setq ref-level level))
20745 (replace-match bul t t)
20746 (org-indent-line-to (+ start-ind (* delta bul-len)))
20747 (when (or done todo)
20748 (let* ((struct (org-list-struct))
20749 (old (copy-tree struct)))
20750 (org-list-set-checkbox (line-beginning-position)
20751 struct
20752 (if done "[X]" "[ ]"))
20753 (org-list-write-struct struct
20754 (org-list-parents-alist struct)
20755 old)))
20756 ;; Ensure all text down to END (or SECTION-END) belongs
20757 ;; to the newly created item.
20758 (let ((section-end (save-excursion
20759 (or (outline-next-heading) (point)))))
20760 (forward-line)
20761 (funcall shift-text
20762 (+ start-ind (* (1+ delta) bul-len))
20763 (min end section-end)))))))
20764 ;; Case 3. Normal line with ARG: make the first line of region
20765 ;; an item, and shift indentation of others lines to
20766 ;; set them as item's body.
20767 (arg (let* ((bul (org-list-bullet-string "-"))
20768 (bul-len (length bul))
20769 (ref-ind (org-get-indentation)))
20770 (skip-chars-forward " \t")
20771 (insert bul)
20772 (forward-line)
20773 (while (< (point) end)
20774 ;; Ensure that lines less indented than first one
20775 ;; still get included in item body.
20776 (funcall shift-text
20777 (+ ref-ind bul-len)
20778 (min end (save-excursion (or (outline-next-heading)
20779 (point)))))
20780 (forward-line))))
20781 ;; Case 4. Normal line without ARG: turn each non-item line
20782 ;; into an item.
20784 (while (< (point) end)
20785 (unless (or (org-at-heading-p) (org-at-item-p))
20786 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20787 (replace-match
20788 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20789 (forward-line))))))))
20791 (defun org-toggle-heading (&optional nstars)
20792 "Convert headings to normal text, or items or text to headings.
20793 If there is no active region, only convert the current line.
20795 With a \\[universal-argument] prefix, convert the whole list at
20796 point into heading.
20798 In a region:
20800 - If the first non blank line is a headline, remove the stars
20801 from all headlines in the region.
20803 - If it is a normal line, turn each and every normal line (i.e.,
20804 not an heading or an item) in the region into headings. If you
20805 want to convert only the first line of this region, use one
20806 universal prefix argument.
20808 - If it is a plain list item, turn all plain list items into headings.
20810 When converting a line into a heading, the number of stars is chosen
20811 such that the lines become children of the current entry. However,
20812 when a numeric prefix argument is given, its value determines the
20813 number of stars to add."
20814 (interactive "P")
20815 (let ((skip-blanks
20816 (function
20817 ;; Return beginning of first non-blank line, starting from
20818 ;; line at POS.
20819 (lambda (pos)
20820 (save-excursion
20821 (goto-char pos)
20822 (while (org-at-comment-p) (forward-line))
20823 (skip-chars-forward " \r\t\n")
20824 (point-at-bol)))))
20825 beg end toggled)
20826 ;; Determine boundaries of changes. If a universal prefix has
20827 ;; been given, put the list in a region. If region ends at a bol,
20828 ;; do not consider the last line to be in the region.
20830 (when (and current-prefix-arg (org-at-item-p))
20831 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20832 (org-mark-element))
20834 (if (org-region-active-p)
20835 (setq beg (funcall skip-blanks (region-beginning))
20836 end (copy-marker (save-excursion
20837 (goto-char (region-end))
20838 (if (bolp) (point) (point-at-eol)))))
20839 (setq beg (funcall skip-blanks (point-at-bol))
20840 end (copy-marker (point-at-eol))))
20841 ;; Ensure inline tasks don't count as headings.
20842 (org-with-limited-levels
20843 (save-excursion
20844 (goto-char beg)
20845 (cond
20846 ;; Case 1. Started at an heading: de-star headings.
20847 ((org-at-heading-p)
20848 (while (< (point) end)
20849 (when (org-at-heading-p t)
20850 (looking-at org-outline-regexp) (replace-match "")
20851 (setq toggled t))
20852 (forward-line)))
20853 ;; Case 2. Started at an item: change items into headlines.
20854 ;; One star will be added by `org-list-to-subtree'.
20855 ((org-at-item-p)
20856 (let* ((stars (make-string
20857 ;; subtract the star that will be added again by
20858 ;; `org-list-to-subtree'
20859 (if (numberp nstars) (1- nstars)
20860 (or (org-current-level) 0))
20861 ?*))
20862 (add-stars
20863 (cond (nstars "") ; stars from prefix only
20864 ((equal stars "") "") ; before first heading
20865 (org-odd-levels-only "*") ; inside heading, odd
20866 (t "")))) ; inside heading, oddeven
20867 (while (< (point) end)
20868 (when (org-at-item-p)
20869 ;; Pay attention to cases when region ends before list.
20870 (let* ((struct (org-list-struct))
20871 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20872 (save-restriction
20873 (narrow-to-region (point) list-end)
20874 (insert
20875 (org-list-to-subtree
20876 (org-list-parse-list t)
20877 '(:istart (concat stars add-stars (funcall get-stars depth))
20878 :icount (concat stars add-stars (funcall get-stars depth)))))))
20879 (setq toggled t))
20880 (forward-line))))
20881 ;; Case 3. Started at normal text: make every line an heading,
20882 ;; skipping headlines and items.
20883 (t (let* ((stars
20884 (make-string
20885 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20886 (add-stars
20887 (cond (nstars "") ; stars from prefix only
20888 ((equal stars "") "*") ; before first heading
20889 (org-odd-levels-only "**") ; inside heading, odd
20890 (t "*"))) ; inside heading, oddeven
20891 (rpl (concat stars add-stars " "))
20892 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20893 (while (< (point) (if (equal nstars '(4)) lend end))
20894 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20895 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20896 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20897 (forward-line)))))))
20898 (unless toggled (message "Cannot toggle heading from here"))))
20900 (defun org-meta-return (&optional arg)
20901 "Insert a new heading or wrap a region in a table.
20902 Calls `org-insert-heading' or `org-table-wrap-region', depending
20903 on context. See the individual commands for more information."
20904 (interactive "P")
20905 (org-check-before-invisible-edit 'insert)
20906 (or (run-hook-with-args-until-success 'org-metareturn-hook)
20907 (let* ((element (org-element-at-point))
20908 (type (org-element-type element)))
20909 (when (eq type 'table-row)
20910 (setq element (org-element-property :parent element))
20911 (setq type 'table))
20912 (if (and (eq type 'table)
20913 (eq (org-element-property :type element) 'org)
20914 (>= (point) (org-element-property :contents-begin element))
20915 (< (point) (org-element-property :contents-end element)))
20916 (call-interactively 'org-table-wrap-region)
20917 (call-interactively 'org-insert-heading)))))
20919 ;;; Menu entries
20921 (defsubst org-in-subtree-not-table-p ()
20922 "Are we in a subtree and not in a table?"
20923 (and (not (org-before-first-heading-p))
20924 (not (org-at-table-p))))
20926 ;; Define the Org-mode menus
20927 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20928 '("Tbl"
20929 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20930 ["Next Field" org-cycle (org-at-table-p)]
20931 ["Previous Field" org-shifttab (org-at-table-p)]
20932 ["Next Row" org-return (org-at-table-p)]
20933 "--"
20934 ["Blank Field" org-table-blank-field (org-at-table-p)]
20935 ["Edit Field" org-table-edit-field (org-at-table-p)]
20936 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20937 "--"
20938 ("Column"
20939 ["Move Column Left" org-metaleft (org-at-table-p)]
20940 ["Move Column Right" org-metaright (org-at-table-p)]
20941 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20942 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20943 ("Row"
20944 ["Move Row Up" org-metaup (org-at-table-p)]
20945 ["Move Row Down" org-metadown (org-at-table-p)]
20946 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20947 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20948 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20949 "--"
20950 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20951 ("Rectangle"
20952 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20953 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20954 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20955 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20956 "--"
20957 ("Calculate"
20958 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20959 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20960 ["Edit Formulas" org-edit-special (org-at-table-p)]
20961 "--"
20962 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20963 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20964 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20965 "--"
20966 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20967 "--"
20968 ["Sum Column/Rectangle" org-table-sum
20969 (or (org-at-table-p) (org-region-active-p))]
20970 ["Which Column?" org-table-current-column (org-at-table-p)])
20971 ["Debug Formulas"
20972 org-table-toggle-formula-debugger
20973 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20974 ["Show Col/Row Numbers"
20975 org-table-toggle-coordinate-overlays
20976 :style toggle
20977 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20978 "--"
20979 ["Create" org-table-create (and (not (org-at-table-p))
20980 org-enable-table-editor)]
20981 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20982 ["Import from File" org-table-import (not (org-at-table-p))]
20983 ["Export to File" org-table-export (org-at-table-p)]
20984 "--"
20985 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20987 (easy-menu-define org-org-menu org-mode-map "Org menu"
20988 '("Org"
20989 ("Show/Hide"
20990 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20991 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20992 ["Sparse Tree..." org-sparse-tree t]
20993 ["Reveal Context" org-reveal t]
20994 ["Show All" show-all t]
20995 "--"
20996 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20997 "--"
20998 ["New Heading" org-insert-heading t]
20999 ("Navigate Headings"
21000 ["Up" outline-up-heading t]
21001 ["Next" outline-next-visible-heading t]
21002 ["Previous" outline-previous-visible-heading t]
21003 ["Next Same Level" outline-forward-same-level t]
21004 ["Previous Same Level" outline-backward-same-level t]
21005 "--"
21006 ["Jump" org-goto t])
21007 ("Edit Structure"
21008 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21009 "--"
21010 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
21011 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
21012 "--"
21013 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21014 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21015 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21016 "--"
21017 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21018 "--"
21019 ["Copy visible text" org-copy-visible t]
21020 "--"
21021 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21022 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21023 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21024 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21025 "--"
21026 ["Sort Region/Children" org-sort t]
21027 "--"
21028 ["Convert to odd levels" org-convert-to-odd-levels t]
21029 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21030 ("Editing"
21031 ["Emphasis..." org-emphasize t]
21032 ["Edit Source Example" org-edit-special t]
21033 "--"
21034 ["Footnote new/jump" org-footnote-action t]
21035 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21036 ("Archive"
21037 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21038 "--"
21039 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
21040 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21041 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21043 "--"
21044 ("Hyperlinks"
21045 ["Store Link (Global)" org-store-link t]
21046 ["Find existing link to here" org-occur-link-in-agenda-files t]
21047 ["Insert Link" org-insert-link t]
21048 ["Follow Link" org-open-at-point t]
21049 "--"
21050 ["Next link" org-next-link t]
21051 ["Previous link" org-previous-link t]
21052 "--"
21053 ["Descriptive Links"
21054 org-toggle-link-display
21055 :style radio
21056 :selected org-descriptive-links
21058 ["Literal Links"
21059 org-toggle-link-display
21060 :style radio
21061 :selected (not org-descriptive-links)])
21062 "--"
21063 ("TODO Lists"
21064 ["TODO/DONE/-" org-todo t]
21065 ("Select keyword"
21066 ["Next keyword" org-shiftright (org-at-heading-p)]
21067 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21068 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21069 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21070 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21071 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21072 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21073 "--"
21074 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21075 :selected org-enforce-todo-dependencies :style toggle :active t]
21076 "Settings for tree at point"
21077 ["Do Children sequentially" org-toggle-ordered-property :style radio
21078 :selected (org-entry-get nil "ORDERED")
21079 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21080 ["Do Children parallel" org-toggle-ordered-property :style radio
21081 :selected (not (org-entry-get nil "ORDERED"))
21082 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21083 "--"
21084 ["Set Priority" org-priority t]
21085 ["Priority Up" org-shiftup t]
21086 ["Priority Down" org-shiftdown t]
21087 "--"
21088 ["Get news from all feeds" org-feed-update-all t]
21089 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21090 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21091 ("TAGS and Properties"
21092 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21093 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21094 "--"
21095 ["Set property" org-set-property (not (org-before-first-heading-p))]
21096 ["Column view of properties" org-columns t]
21097 ["Insert Column View DBlock" org-insert-columns-dblock t])
21098 ("Dates and Scheduling"
21099 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21100 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21101 ("Change Date"
21102 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21103 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21104 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21105 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21106 ["Compute Time Range" org-evaluate-time-range t]
21107 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21108 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21109 "--"
21110 ["Custom time format" org-toggle-time-stamp-overlays
21111 :style radio :selected org-display-custom-times]
21112 "--"
21113 ["Goto Calendar" org-goto-calendar t]
21114 ["Date from Calendar" org-date-from-calendar t]
21115 "--"
21116 ["Start/Restart Timer" org-timer-start t]
21117 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21118 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21119 ["Insert Timer String" org-timer t]
21120 ["Insert Timer Item" org-timer-item t])
21121 ("Logging work"
21122 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21123 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21124 ["Clock out" org-clock-out t]
21125 ["Clock cancel" org-clock-cancel t]
21126 "--"
21127 ["Mark as default task" org-clock-mark-default-task t]
21128 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21129 ["Goto running clock" org-clock-goto t]
21130 "--"
21131 ["Display times" org-clock-display t]
21132 ["Create clock table" org-clock-report t]
21133 "--"
21134 ["Record DONE time"
21135 (progn (setq org-log-done (not org-log-done))
21136 (message "Switching to %s will %s record a timestamp"
21137 (car org-done-keywords)
21138 (if org-log-done "automatically" "not")))
21139 :style toggle :selected org-log-done])
21140 "--"
21141 ["Agenda Command..." org-agenda t]
21142 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21143 ("File List for Agenda")
21144 ("Special views current file"
21145 ["TODO Tree" org-show-todo-tree t]
21146 ["Check Deadlines" org-check-deadlines t]
21147 ["Timeline" org-timeline t]
21148 ["Tags/Property tree" org-match-sparse-tree t])
21149 "--"
21150 ["Export/Publish..." org-export-dispatch t]
21151 ("LaTeX"
21152 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21153 :selected org-cdlatex-mode]
21154 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21155 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21156 ["Modify math symbol" org-cdlatex-math-modify
21157 (org-inside-LaTeX-fragment-p)]
21158 ["Insert citation" org-reftex-citation t]
21159 "--"
21160 ["Template for BEAMER" (org-beamer-insert-options-template) t])
21161 "--"
21162 ("MobileOrg"
21163 ["Push Files and Views" org-mobile-push t]
21164 ["Get Captured and Flagged" org-mobile-pull t]
21165 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21166 "--"
21167 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21168 "--"
21169 ("Documentation"
21170 ["Show Version" org-version t]
21171 ["Info Documentation" org-info t])
21172 ("Customize"
21173 ["Browse Org Group" org-customize t]
21174 "--"
21175 ["Expand This Menu" org-create-customize-menu
21176 (fboundp 'customize-menu-create)])
21177 ["Send bug report" org-submit-bug-report t]
21178 "--"
21179 ("Refresh/Reload"
21180 ["Refresh setup current buffer" org-mode-restart t]
21181 ["Reload Org (after update)" org-reload t]
21182 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21185 (defun org-info (&optional node)
21186 "Read documentation for Org-mode in the info system.
21187 With optional NODE, go directly to that node."
21188 (interactive)
21189 (info (format "(org)%s" (or node ""))))
21191 ;;;###autoload
21192 (defun org-submit-bug-report ()
21193 "Submit a bug report on Org-mode via mail.
21195 Don't hesitate to report any problems or inaccurate documentation.
21197 If you don't have setup sending mail from (X)Emacs, please copy the
21198 output buffer into your mail program, as it gives us important
21199 information about your Org-mode version and configuration."
21200 (interactive)
21201 (require 'reporter)
21202 (org-load-modules-maybe)
21203 (org-require-autoloaded-modules)
21204 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21205 (reporter-submit-bug-report
21206 "emacs-orgmode@gnu.org"
21207 (org-version nil 'full)
21208 (let (list)
21209 (save-window-excursion
21210 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21211 (delete-other-windows)
21212 (erase-buffer)
21213 (insert "You are about to submit a bug report to the Org-mode mailing list.
21215 We would like to add your full Org-mode and Outline configuration to the
21216 bug report. This greatly simplifies the work of the maintainer and
21217 other experts on the mailing list.
21219 HOWEVER, some variables you have customized may contain private
21220 information. The names of customers, colleagues, or friends, might
21221 appear in the form of file names, tags, todo states, or search strings.
21222 If you answer yes to the prompt, you might want to check and remove
21223 such private information before sending the email.")
21224 (add-text-properties (point-min) (point-max) '(face org-warning))
21225 (when (yes-or-no-p "Include your Org-mode configuration ")
21226 (mapatoms
21227 (lambda (v)
21228 (and (boundp v)
21229 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21230 (or (and (symbol-value v)
21231 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21232 (and
21233 (get v 'custom-type) (get v 'standard-value)
21234 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21235 (push v list)))))
21236 (kill-buffer (get-buffer "*Warn about privacy*"))
21237 list))
21238 nil nil
21239 "Remember to cover the basics, that is, what you expected to happen and
21240 what in fact did happen. You don't know how to make a good report? See
21242 http://orgmode.org/manual/Feedback.html#Feedback
21244 Your bug report will be posted to the Org-mode mailing list.
21245 ------------------------------------------------------------------------")
21246 (save-excursion
21247 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21248 (replace-match "\\1Bug: \\3 [\\2]")))))
21251 (defun org-install-agenda-files-menu ()
21252 (let ((bl (buffer-list)))
21253 (save-excursion
21254 (while bl
21255 (set-buffer (pop bl))
21256 (if (derived-mode-p 'org-mode) (setq bl nil)))
21257 (when (derived-mode-p 'org-mode)
21258 (easy-menu-change
21259 '("Org") "File List for Agenda"
21260 (append
21261 (list
21262 ["Edit File List" (org-edit-agenda-file-list) t]
21263 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21264 ["Remove Current File from List" org-remove-file t]
21265 ["Cycle through agenda files" org-cycle-agenda-files t]
21266 ["Occur in all agenda files" org-occur-in-agenda-files t]
21267 "--")
21268 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21270 ;;;; Documentation
21272 (defun org-require-autoloaded-modules ()
21273 (interactive)
21274 (mapc 'require
21275 '(org-agenda org-archive org-attach org-clock org-colview org-id
21276 org-table org-timer)))
21278 ;;;###autoload
21279 (defun org-reload (&optional uncompiled)
21280 "Reload all org lisp files.
21281 With prefix arg UNCOMPILED, load the uncompiled versions."
21282 (interactive "P")
21283 (require 'loadhist)
21284 (let* ((org-dir (org-find-library-dir "org"))
21285 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21286 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21287 (remove-re (mapconcat 'identity
21288 (mapcar (lambda (f) (concat "^" f "$"))
21289 (list (if (featurep 'xemacs)
21290 "org-colview"
21291 "org-colview-xemacs")
21292 "org" "org-loaddefs" "org-version"))
21293 "\\|"))
21294 (feats (delete-dups
21295 (mapcar 'file-name-sans-extension
21296 (mapcar 'file-name-nondirectory
21297 (delq nil
21298 (mapcar 'feature-file
21299 features))))))
21300 (lfeat (append
21301 (sort
21302 (setq feats
21303 (delq nil (mapcar
21304 (lambda (f)
21305 (if (and (string-match feature-re f)
21306 (not (string-match remove-re f)))
21307 f nil))
21308 feats)))
21309 'string-lessp)
21310 (list "org-version" "org")))
21311 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21312 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21313 load-uncore load-misses)
21314 (setq load-misses
21315 (delq 't
21316 (mapcar (lambda (f)
21317 (or (org-load-noerror-mustsuffix (concat org-dir f))
21318 (and (string= org-dir contrib-dir)
21319 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21320 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21321 (add-to-list 'load-uncore f 'append)
21324 lfeat)))
21325 (if load-uncore
21326 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21327 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21328 (if load-misses
21329 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21330 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21331 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21333 ;;;###autoload
21334 (defun org-customize ()
21335 "Call the customize function with org as argument."
21336 (interactive)
21337 (org-load-modules-maybe)
21338 (org-require-autoloaded-modules)
21339 (customize-browse 'org))
21341 (defun org-create-customize-menu ()
21342 "Create a full customization menu for Org-mode, insert it into the menu."
21343 (interactive)
21344 (org-load-modules-maybe)
21345 (org-require-autoloaded-modules)
21346 (if (fboundp 'customize-menu-create)
21347 (progn
21348 (easy-menu-change
21349 '("Org") "Customize"
21350 `(["Browse Org group" org-customize t]
21351 "--"
21352 ,(customize-menu-create 'org)
21353 ["Set" Custom-set t]
21354 ["Save" Custom-save t]
21355 ["Reset to Current" Custom-reset-current t]
21356 ["Reset to Saved" Custom-reset-saved t]
21357 ["Reset to Standard Settings" Custom-reset-standard t]))
21358 (message "\"Org\"-menu now contains full customization menu"))
21359 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21361 ;;;; Miscellaneous stuff
21363 ;;; Generally useful functions
21365 (defun org-get-at-bol (property)
21366 "Get text property PROPERTY at beginning of line."
21367 (get-text-property (point-at-bol) property))
21369 (defun org-find-text-property-in-string (prop s)
21370 "Return the first non-nil value of property PROP in string S."
21371 (or (get-text-property 0 prop s)
21372 (get-text-property (or (next-single-property-change 0 prop s) 0)
21373 prop s)))
21375 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21376 "Display the given MESSAGE as a warning."
21377 (if (fboundp 'display-warning)
21378 (display-warning 'org message
21379 (if (featurep 'xemacs) 'warning :warning))
21380 (let ((buf (get-buffer-create "*Org warnings*")))
21381 (with-current-buffer buf
21382 (goto-char (point-max))
21383 (insert "Warning (Org): " message)
21384 (unless (bolp)
21385 (newline)))
21386 (display-buffer buf)
21387 (sit-for 0))))
21389 (defun org-eval (form)
21390 "Eval FORM and return result."
21391 (condition-case error
21392 (eval form)
21393 (error (format "%%![Error: %s]" error))))
21395 (defun org-in-clocktable-p ()
21396 "Check if the cursor is in a clocktable."
21397 (let ((pos (point)) start)
21398 (save-excursion
21399 (end-of-line 1)
21400 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21401 (setq start (match-beginning 0))
21402 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21403 (>= (match-end 0) pos)
21404 start))))
21406 (defun org-in-commented-line ()
21407 "Is point in a line starting with `#'?"
21408 (equal (char-after (point-at-bol)) ?#))
21410 (defun org-in-indented-comment-line ()
21411 "Is point in a line starting with `#' after some white space?"
21412 (save-excursion
21413 (save-match-data
21414 (goto-char (point-at-bol))
21415 (looking-at "[ \t]*#"))))
21417 (defun org-in-verbatim-emphasis ()
21418 (save-match-data
21419 (and (org-in-regexp org-emph-re 2)
21420 (>= (point) (match-beginning 3))
21421 (<= (point) (match-end 4))
21422 (member (match-string 3) '("=" "~")))))
21424 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21425 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21426 (if (and marker (marker-buffer marker)
21427 (buffer-live-p (marker-buffer marker)))
21428 (progn
21429 (org-pop-to-buffer-same-window (marker-buffer marker))
21430 (if (or (> marker (point-max)) (< marker (point-min)))
21431 (widen))
21432 (goto-char marker)
21433 (org-show-context 'org-goto))
21434 (if bookmark
21435 (bookmark-jump bookmark)
21436 (error "Cannot find location"))))
21438 (defun org-quote-csv-field (s)
21439 "Quote field for inclusion in CSV material."
21440 (if (string-match "[\",]" s)
21441 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21444 (defun org-force-self-insert (N)
21445 "Needed to enforce self-insert under remapping."
21446 (interactive "p")
21447 (self-insert-command N))
21449 (defun org-string-width (s)
21450 "Compute width of string, ignoring invisible characters.
21451 This ignores character with invisibility property `org-link', and also
21452 characters with property `org-cwidth', because these will become invisible
21453 upon the next fontification round."
21454 (let (b l)
21455 (when (or (eq t buffer-invisibility-spec)
21456 (assq 'org-link buffer-invisibility-spec))
21457 (while (setq b (text-property-any 0 (length s)
21458 'invisible 'org-link s))
21459 (setq s (concat (substring s 0 b)
21460 (substring s (or (next-single-property-change
21461 b 'invisible s) (length s)))))))
21462 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21463 (setq s (concat (substring s 0 b)
21464 (substring s (or (next-single-property-change
21465 b 'org-cwidth s) (length s))))))
21466 (setq l (string-width s) b -1)
21467 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21468 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21471 (defun org-shorten-string (s maxlength)
21472 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21473 If the string is shorter or has length MAXLENGTH, just return the
21474 original string. If it is longer, the functions finds a space in the
21475 string, breaks this string off at that locations and adds three dots
21476 as ellipsis. Including the ellipsis, the string will not be longer
21477 than MAXLENGTH. If finding a good breaking point in the string does
21478 not work, the string is just chopped off in the middle of a word
21479 if necessary."
21480 (if (<= (length s) maxlength)
21482 (let* ((n (max (- maxlength 4) 1))
21483 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21484 (if (string-match re s)
21485 (concat (match-string 1 s) "...")
21486 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21488 (defun org-get-indentation (&optional line)
21489 "Get the indentation of the current line, interpreting tabs.
21490 When LINE is given, assume it represents a line and compute its indentation."
21491 (if line
21492 (if (string-match "^ *" (org-remove-tabs line))
21493 (match-end 0))
21494 (save-excursion
21495 (beginning-of-line 1)
21496 (skip-chars-forward " \t")
21497 (current-column))))
21499 (defun org-get-string-indentation (s)
21500 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21501 (let ((n -1) (i 0) (w tab-width) c)
21502 (catch 'exit
21503 (while (< (setq n (1+ n)) (length s))
21504 (setq c (aref s n))
21505 (cond ((= c ?\ ) (setq i (1+ i)))
21506 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21507 (t (throw 'exit t)))))
21510 (defun org-remove-tabs (s &optional width)
21511 "Replace tabulators in S with spaces.
21512 Assumes that s is a single line, starting in column 0."
21513 (setq width (or width tab-width))
21514 (while (string-match "\t" s)
21515 (setq s (replace-match
21516 (make-string
21517 (- (* width (/ (+ (match-beginning 0) width) width))
21518 (match-beginning 0)) ?\ )
21519 t t s)))
21522 (defun org-fix-indentation (line ind)
21523 "Fix indentation in LINE.
21524 IND is a cons cell with target and minimum indentation.
21525 If the current indentation in LINE is smaller than the minimum,
21526 leave it alone. If it is larger than ind, set it to the target."
21527 (let* ((l (org-remove-tabs line))
21528 (i (org-get-indentation l))
21529 (i1 (car ind)) (i2 (cdr ind)))
21530 (if (>= i i2) (setq l (substring line i2)))
21531 (if (> i1 0)
21532 (concat (make-string i1 ?\ ) l)
21533 l)))
21535 (defun org-remove-indentation (code &optional n)
21536 "Remove the maximum common indentation from the lines in CODE.
21537 N may optionally be the number of spaces to remove."
21538 (with-temp-buffer
21539 (insert code)
21540 (org-do-remove-indentation n)
21541 (buffer-string)))
21543 (defun org-do-remove-indentation (&optional n)
21544 "Remove the maximum common indentation from the buffer."
21545 (untabify (point-min) (point-max))
21546 (let ((min 10000) re)
21547 (if n
21548 (setq min n)
21549 (goto-char (point-min))
21550 (while (re-search-forward "^ *[^ \n]" nil t)
21551 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21552 (unless (or (= min 0) (= min 10000))
21553 (setq re (format "^ \\{%d\\}" min))
21554 (goto-char (point-min))
21555 (while (re-search-forward re nil t)
21556 (replace-match "")
21557 (end-of-line 1))
21558 min)))
21560 (defun org-fill-template (template alist)
21561 "Find each %key of ALIST in TEMPLATE and replace it."
21562 (let ((case-fold-search nil)
21563 entry key value)
21564 (setq alist (sort (copy-sequence alist)
21565 (lambda (a b) (< (length (car a)) (length (car b))))))
21566 (while (setq entry (pop alist))
21567 (setq template
21568 (replace-regexp-in-string
21569 (concat "%" (regexp-quote (car entry)))
21570 (or (cdr entry) "") template t t)))
21571 template))
21573 (defun org-base-buffer (buffer)
21574 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21575 (if (not buffer)
21576 buffer
21577 (or (buffer-base-buffer buffer)
21578 buffer)))
21580 (defun org-trim (s)
21581 "Remove whitespace at beginning and end of string."
21582 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
21583 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
21586 (defun org-wrap (string &optional width lines)
21587 "Wrap string to either a number of lines, or a width in characters.
21588 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21589 that costs. If there is a word longer than WIDTH, the text is actually
21590 wrapped to the length of that word.
21591 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21592 many lines, whatever width that takes.
21593 The return value is a list of lines, without newlines at the end."
21594 (let* ((words (org-split-string string "[ \t\n]+"))
21595 (maxword (apply 'max (mapcar 'org-string-width words)))
21596 w ll)
21597 (cond (width
21598 (org-do-wrap words (max maxword width)))
21599 (lines
21600 (setq w maxword)
21601 (setq ll (org-do-wrap words maxword))
21602 (if (<= (length ll) lines)
21604 (setq ll words)
21605 (while (> (length ll) lines)
21606 (setq w (1+ w))
21607 (setq ll (org-do-wrap words w)))
21608 ll))
21609 (t (error "Cannot wrap this")))))
21611 (defun org-do-wrap (words width)
21612 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21613 (let (lines line)
21614 (while words
21615 (setq line (pop words))
21616 (while (and words (< (+ (length line) (length (car words))) width))
21617 (setq line (concat line " " (pop words))))
21618 (setq lines (push line lines)))
21619 (nreverse lines)))
21621 (defun org-split-string (string &optional separators)
21622 "Splits STRING into substrings at SEPARATORS.
21623 No empty strings are returned if there are matches at the beginning
21624 and end of string."
21625 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21626 (start 0)
21627 notfirst
21628 (list nil))
21629 (while (and (string-match rexp string
21630 (if (and notfirst
21631 (= start (match-beginning 0))
21632 (< start (length string)))
21633 (1+ start) start))
21634 (< (match-beginning 0) (length string)))
21635 (setq notfirst t)
21636 (or (eq (match-beginning 0) 0)
21637 (and (eq (match-beginning 0) (match-end 0))
21638 (eq (match-beginning 0) start))
21639 (setq list
21640 (cons (substring string start (match-beginning 0))
21641 list)))
21642 (setq start (match-end 0)))
21643 (or (eq start (length string))
21644 (setq list
21645 (cons (substring string start)
21646 list)))
21647 (nreverse list)))
21649 (defun org-quote-vert (s)
21650 "Replace \"|\" with \"\\vert\"."
21651 (while (string-match "|" s)
21652 (setq s (replace-match "\\vert" t t s)))
21655 (defun org-uuidgen-p (s)
21656 "Is S an ID created by UUIDGEN?"
21657 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21659 (defun org-in-src-block-p (&optional inside)
21660 "Whether point is in a code source block.
21661 When INSIDE is non-nil, don't consider we are within a src block
21662 when point is at #+BEGIN_SRC or #+END_SRC."
21663 (let ((case-fold-search t) ov)
21664 (or (and (setq ov (overlays-at (point)))
21665 (memq 'org-block-background
21666 (overlay-properties (car ov))))
21667 (and (not inside)
21668 (save-match-data
21669 (save-excursion
21670 (beginning-of-line)
21671 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21673 (defun org-context ()
21674 "Return a list of contexts of the current cursor position.
21675 If several contexts apply, all are returned.
21676 Each context entry is a list with a symbol naming the context, and
21677 two positions indicating start and end of the context. Possible
21678 contexts are:
21680 :headline anywhere in a headline
21681 :headline-stars on the leading stars in a headline
21682 :todo-keyword on a TODO keyword (including DONE) in a headline
21683 :tags on the TAGS in a headline
21684 :priority on the priority cookie in a headline
21685 :item on the first line of a plain list item
21686 :item-bullet on the bullet/number of a plain list item
21687 :checkbox on the checkbox in a plain list item
21688 :table in an org-mode table
21689 :table-special on a special filed in a table
21690 :table-table in a table.el table
21691 :clocktable in a clocktable
21692 :src-block in a source block
21693 :link on a hyperlink
21694 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
21695 :target on a <<target>>
21696 :radio-target on a <<<radio-target>>>
21697 :latex-fragment on a LaTeX fragment
21698 :latex-preview on a LaTeX fragment with overlaid preview image
21700 This function expects the position to be visible because it uses font-lock
21701 faces as a help to recognize the following contexts: :table-special, :link,
21702 and :keyword."
21703 (let* ((f (get-text-property (point) 'face))
21704 (faces (if (listp f) f (list f)))
21705 (case-fold-search t)
21706 (p (point)) clist o)
21707 ;; First the large context
21708 (cond
21709 ((org-at-heading-p t)
21710 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21711 (when (progn
21712 (beginning-of-line 1)
21713 (looking-at org-todo-line-tags-regexp))
21714 (push (org-point-in-group p 1 :headline-stars) clist)
21715 (push (org-point-in-group p 2 :todo-keyword) clist)
21716 (push (org-point-in-group p 4 :tags) clist))
21717 (goto-char p)
21718 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21719 (if (looking-at "\\[#[A-Z0-9]\\]")
21720 (push (org-point-in-group p 0 :priority) clist)))
21722 ((org-at-item-p)
21723 (push (org-point-in-group p 2 :item-bullet) clist)
21724 (push (list :item (point-at-bol)
21725 (save-excursion (org-end-of-item) (point)))
21726 clist)
21727 (and (org-at-item-checkbox-p)
21728 (push (org-point-in-group p 0 :checkbox) clist)))
21730 ((org-at-table-p)
21731 (push (list :table (org-table-begin) (org-table-end)) clist)
21732 (if (memq 'org-formula faces)
21733 (push (list :table-special
21734 (previous-single-property-change p 'face)
21735 (next-single-property-change p 'face)) clist)))
21736 ((org-at-table-p 'any)
21737 (push (list :table-table) clist)))
21738 (goto-char p)
21740 (let ((case-fold-search t))
21741 ;; New the "medium" contexts: clocktables, source blocks
21742 (cond ((org-in-clocktable-p)
21743 (push (list :clocktable
21744 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
21745 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
21746 (match-beginning 1))
21747 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
21748 (match-end 0))) clist))
21749 ((org-in-src-block-p)
21750 (push (list :src-block
21751 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
21752 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
21753 (match-beginning 1))
21754 (and (search-forward "#+END_SRC" nil t)
21755 (match-beginning 0))) clist))))
21756 (goto-char p)
21758 ;; Now the small context
21759 (cond
21760 ((org-at-timestamp-p)
21761 (push (org-point-in-group p 0 :timestamp) clist))
21762 ((memq 'org-link faces)
21763 (push (list :link
21764 (previous-single-property-change p 'face)
21765 (next-single-property-change p 'face)) clist))
21766 ((memq 'org-special-keyword faces)
21767 (push (list :keyword
21768 (previous-single-property-change p 'face)
21769 (next-single-property-change p 'face)) clist))
21770 ((org-at-target-p)
21771 (push (org-point-in-group p 0 :target) clist)
21772 (goto-char (1- (match-beginning 0)))
21773 (if (looking-at org-radio-target-regexp)
21774 (push (org-point-in-group p 0 :radio-target) clist))
21775 (goto-char p))
21776 ((setq o (car (delq nil
21777 (mapcar
21778 (lambda (x)
21779 (if (memq x org-latex-fragment-image-overlays) x))
21780 (overlays-at (point))))))
21781 (push (list :latex-fragment
21782 (overlay-start o) (overlay-end o)) clist)
21783 (push (list :latex-preview
21784 (overlay-start o) (overlay-end o)) clist))
21785 ((org-inside-LaTeX-fragment-p)
21786 ;; FIXME: positions wrong.
21787 (push (list :latex-fragment (point) (point)) clist)))
21789 (setq clist (nreverse (delq nil clist)))
21790 clist))
21792 ;; FIXME: Compare with at-regexp-p Do we need both?
21793 (defun org-in-regexp (re &optional nlines visually)
21794 "Check if point is inside a match of regexp.
21795 Normally only the current line is checked, but you can include NLINES extra
21796 lines both before and after point into the search.
21797 If VISUALLY is set, require that the cursor is not after the match but
21798 really on, so that the block visually is on the match."
21799 (catch 'exit
21800 (let ((pos (point))
21801 (eol (point-at-eol (+ 1 (or nlines 0))))
21802 (inc (if visually 1 0)))
21803 (save-excursion
21804 (beginning-of-line (- 1 (or nlines 0)))
21805 (while (re-search-forward re eol t)
21806 (if (and (<= (match-beginning 0) pos)
21807 (>= (+ inc (match-end 0)) pos))
21808 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21810 (defun org-at-regexp-p (regexp)
21811 "Is point inside a match of REGEXP in the current line?"
21812 (catch 'exit
21813 (save-excursion
21814 (let ((pos (point)) (end (point-at-eol)))
21815 (beginning-of-line 1)
21816 (while (re-search-forward regexp end t)
21817 (if (and (<= (match-beginning 0) pos)
21818 (>= (match-end 0) pos))
21819 (throw 'exit t)))
21820 nil))))
21822 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21823 "Non-nil when point is between matches of START-RE and END-RE.
21825 Also return a non-nil value when point is on one of the matches.
21827 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21828 buffer positions. Default values are the positions of headlines
21829 surrounding the point.
21831 The functions returns a cons cell whose car (resp. cdr) is the
21832 position before START-RE (resp. after END-RE)."
21833 (save-match-data
21834 (let ((pos (point))
21835 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21836 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21837 beg end)
21838 (save-excursion
21839 ;; Point is on a block when on START-RE or if START-RE can be
21840 ;; found before it...
21841 (and (or (org-at-regexp-p start-re)
21842 (re-search-backward start-re limit-up t))
21843 (setq beg (match-beginning 0))
21844 ;; ... and END-RE after it...
21845 (goto-char (match-end 0))
21846 (re-search-forward end-re limit-down t)
21847 (> (setq end (match-end 0)) pos)
21848 ;; ... without another START-RE in-between.
21849 (goto-char (match-beginning 0))
21850 (not (re-search-backward start-re (1+ beg) t))
21851 ;; Return value.
21852 (cons beg end))))))
21854 (defun org-in-block-p (names)
21855 "Non-nil when point belongs to a block whose name belongs to NAMES.
21857 NAMES is a list of strings containing names of blocks.
21859 Return first block name matched, or nil. Beware that in case of
21860 nested blocks, the returned name may not belong to the closest
21861 block from point."
21862 (save-match-data
21863 (catch 'exit
21864 (let ((case-fold-search t)
21865 (lim-up (save-excursion (outline-previous-heading)))
21866 (lim-down (save-excursion (outline-next-heading))))
21867 (mapc (lambda (name)
21868 (let ((n (regexp-quote name)))
21869 (when (org-between-regexps-p
21870 (concat "^[ \t]*#\\+begin_" n)
21871 (concat "^[ \t]*#\\+end_" n)
21872 lim-up lim-down)
21873 (throw 'exit n))))
21874 names))
21875 nil)))
21877 (defun org-in-drawer-p ()
21878 "Non-nil if point is within a drawer.
21879 If point is within a drawer, return it, as parsed data."
21880 (let ((element (save-match-data (org-element-at-point))))
21881 (while (and element (not (memq (org-element-type element)
21882 '(drawer property-drawer))))
21883 (setq element (org-element-property :parent element)))
21884 element))
21886 (defun org-occur-in-agenda-files (regexp &optional nlines)
21887 "Call `multi-occur' with buffers for all agenda files."
21888 (interactive "sOrg-files matching: \np")
21889 (let* ((files (org-agenda-files))
21890 (tnames (mapcar 'file-truename files))
21891 (extra org-agenda-text-search-extra-files)
21893 (when (eq (car extra) 'agenda-archives)
21894 (setq extra (cdr extra))
21895 (setq files (org-add-archive-files files)))
21896 (while (setq f (pop extra))
21897 (unless (member (file-truename f) tnames)
21898 (add-to-list 'files f 'append)
21899 (add-to-list 'tnames (file-truename f) 'append)))
21900 (multi-occur
21901 (mapcar (lambda (x)
21902 (with-current-buffer
21903 (or (get-file-buffer x) (find-file-noselect x))
21904 (widen)
21905 (current-buffer)))
21906 files)
21907 regexp)))
21909 (if (boundp 'occur-mode-find-occurrence-hook)
21910 ;; Emacs 23
21911 (add-hook 'occur-mode-find-occurrence-hook
21912 (lambda ()
21913 (when (derived-mode-p 'org-mode)
21914 (org-reveal))))
21915 ;; Emacs 22
21916 (defadvice occur-mode-goto-occurrence
21917 (after org-occur-reveal activate)
21918 (and (derived-mode-p 'org-mode) (org-reveal)))
21919 (defadvice occur-mode-goto-occurrence-other-window
21920 (after org-occur-reveal activate)
21921 (and (derived-mode-p 'org-mode) (org-reveal)))
21922 (defadvice occur-mode-display-occurrence
21923 (after org-occur-reveal activate)
21924 (when (derived-mode-p 'org-mode)
21925 (let ((pos (occur-mode-find-occurrence)))
21926 (with-current-buffer (marker-buffer pos)
21927 (save-excursion
21928 (goto-char pos)
21929 (org-reveal)))))))
21931 (defun org-occur-link-in-agenda-files ()
21932 "Create a link and search for it in the agendas.
21933 The link is not stored in `org-stored-links', it is just created
21934 for the search purpose."
21935 (interactive)
21936 (let ((link (condition-case nil
21937 (org-store-link nil)
21938 (error "Unable to create a link to here"))))
21939 (org-occur-in-agenda-files (regexp-quote link))))
21941 (defun org-reverse-string (string)
21942 "Return the reverse of STRING."
21943 (apply 'string (reverse (string-to-list string))))
21945 (defun org-uniquify-alist (alist)
21946 "Merge elements of ALIST with the same key.
21948 For example, in this alist:
21950 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
21951 => '((a 1 3) (b 2))
21953 merge (a 1) and (a 3) into (a 1 3).
21955 The function returns the new ALIST."
21956 (let (rtn)
21957 (mapc
21958 (lambda (e)
21959 (let (n)
21960 (if (not (assoc (car e) rtn))
21961 (push e rtn)
21962 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
21963 (setq rtn (assq-delete-all (car e) rtn))
21964 (push n rtn))))
21965 alist)
21966 rtn))
21968 (defun org-delete-all (elts list)
21969 "Remove all elements in ELTS from LIST."
21970 (while elts
21971 (setq list (delete (pop elts) list)))
21972 list)
21974 (defun org-count (cl-item cl-seq)
21975 "Count the number of occurrences of ITEM in SEQ.
21976 Taken from `count' in cl-seq.el with all keyword arguments removed."
21977 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21978 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21979 (while (< cl-start cl-end)
21980 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21981 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21982 (setq cl-start (1+ cl-start)))
21983 cl-count))
21985 (defun org-remove-if (predicate seq)
21986 "Remove everything from SEQ that fulfills PREDICATE."
21987 (let (res e)
21988 (while seq
21989 (setq e (pop seq))
21990 (if (not (funcall predicate e)) (push e res)))
21991 (nreverse res)))
21993 (defun org-remove-if-not (predicate seq)
21994 "Remove everything from SEQ that does not fulfill PREDICATE."
21995 (let (res e)
21996 (while seq
21997 (setq e (pop seq))
21998 (if (funcall predicate e) (push e res)))
21999 (nreverse res)))
22001 (defun org-reduce (cl-func cl-seq &rest cl-keys)
22002 "Reduce two-argument FUNCTION across SEQ.
22003 Taken from `reduce' in cl-seq.el with all keyword arguments but
22004 \":initial-value\" removed."
22005 (let ((cl-accum (cond ((memq :initial-value cl-keys)
22006 (cadr (memq :initial-value cl-keys)))
22007 (cl-seq (pop cl-seq))
22008 (t (funcall cl-func)))))
22009 (while cl-seq
22010 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
22011 cl-accum))
22013 (defun org-every (pred seq)
22014 "Return true if PREDICATE is true of every element of SEQ.
22015 Adapted from `every' in cl.el."
22016 (catch 'org-every
22017 (mapc (lambda (e) (unless (funcall pred e) (throw 'org-every nil))) seq)
22020 (defun org-some (pred seq)
22021 "Return true if PREDICATE is true of any element of SEQ.
22022 Adapted from `some' in cl.el."
22023 (catch 'org-some
22024 (mapc (lambda (e) (when (funcall pred e) (throw 'org-some t))) seq)
22025 nil))
22027 (defun org-back-over-empty-lines ()
22028 "Move backwards over whitespace, to the beginning of the first empty line.
22029 Returns the number of empty lines passed."
22030 (let ((pos (point)))
22031 (if (cdr (assoc 'heading org-blank-before-new-entry))
22032 (skip-chars-backward " \t\n\r")
22033 (unless (eobp)
22034 (forward-line -1)))
22035 (beginning-of-line 2)
22036 (goto-char (min (point) pos))
22037 (count-lines (point) pos)))
22039 (defun org-skip-whitespace ()
22040 (skip-chars-forward " \t\n\r"))
22042 (defun org-point-in-group (point group &optional context)
22043 "Check if POINT is in match-group GROUP.
22044 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22045 match. If the match group does not exist or point is not inside it,
22046 return nil."
22047 (and (match-beginning group)
22048 (>= point (match-beginning group))
22049 (<= point (match-end group))
22050 (if context
22051 (list context (match-beginning group) (match-end group))
22052 t)))
22054 (defun org-switch-to-buffer-other-window (&rest args)
22055 "Switch to buffer in a second window on the current frame.
22056 In particular, do not allow pop-up frames.
22057 Returns the newly created buffer."
22058 (org-no-popups
22059 (apply 'switch-to-buffer-other-window args)))
22061 (defun org-combine-plists (&rest plists)
22062 "Create a single property list from all plists in PLISTS.
22063 The process starts by copying the first list, and then setting properties
22064 from the other lists. Settings in the last list are the most significant
22065 ones and overrule settings in the other lists."
22066 (let ((rtn (copy-sequence (pop plists)))
22067 p v ls)
22068 (while plists
22069 (setq ls (pop plists))
22070 (while ls
22071 (setq p (pop ls) v (pop ls))
22072 (setq rtn (plist-put rtn p v))))
22073 rtn))
22075 (defun org-replace-escapes (string table)
22076 "Replace %-escapes in STRING with values in TABLE.
22077 TABLE is an association list with keys like \"%a\" and string values.
22078 The sequences in STRING may contain normal field width and padding information,
22079 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22080 so values can contain further %-escapes if they are define later in TABLE."
22081 (let ((tbl (copy-alist table))
22082 (case-fold-search nil)
22083 (pchg 0)
22084 e re rpl)
22085 (while (setq e (pop tbl))
22086 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22087 (when (and (cdr e) (string-match re (cdr e)))
22088 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22089 (safe "SREF"))
22090 (add-text-properties 0 3 (list 'sref sref) safe)
22091 (setcdr e (replace-match safe t t (cdr e)))))
22092 (while (string-match re string)
22093 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22094 (cdr e)))
22095 (setq string (replace-match rpl t t string))))
22096 (while (setq pchg (next-property-change pchg string))
22097 (let ((sref (get-text-property pchg 'sref string)))
22098 (when (and sref (string-match "SREF" string pchg))
22099 (setq string (replace-match sref t t string)))))
22100 string))
22102 (defun org-sublist (list start end)
22103 "Return a section of LIST, from START to END.
22104 Counting starts at 1."
22105 (let (rtn (c start))
22106 (setq list (nthcdr (1- start) list))
22107 (while (and list (<= c end))
22108 (push (pop list) rtn)
22109 (setq c (1+ c)))
22110 (nreverse rtn)))
22112 (defun org-find-base-buffer-visiting (file)
22113 "Like `find-buffer-visiting' but always return the base buffer and
22114 not an indirect buffer."
22115 (let ((buf (or (get-file-buffer file)
22116 (find-buffer-visiting file))))
22117 (if buf
22118 (or (buffer-base-buffer buf) buf)
22119 nil)))
22121 (defun org-image-file-name-regexp (&optional extensions)
22122 "Return regexp matching the file names of images.
22123 If EXTENSIONS is given, only match these."
22124 (if (and (not extensions) (fboundp 'image-file-name-regexp))
22125 (image-file-name-regexp)
22126 (let ((image-file-name-extensions
22127 (or extensions
22128 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
22129 "xbm" "xpm" "pbm" "pgm" "ppm"))))
22130 (concat "\\."
22131 (regexp-opt (nconc (mapcar 'upcase
22132 image-file-name-extensions)
22133 image-file-name-extensions)
22135 "\\'"))))
22137 (defun org-file-image-p (file &optional extensions)
22138 "Return non-nil if FILE is an image."
22139 (save-match-data
22140 (string-match (org-image-file-name-regexp extensions) file)))
22142 (defun org-get-cursor-date (&optional with-time)
22143 "Return the date at cursor in as a time.
22144 This works in the calendar and in the agenda, anywhere else it just
22145 returns the current time.
22146 If WITH-TIME is non-nil, returns the time of the event at point (in
22147 the agenda) or the current time of the day."
22148 (let (date day defd tp tm hod mod)
22149 (when with-time
22150 (setq tp (get-text-property (point) 'time))
22151 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22152 (setq hod (string-to-number (match-string 1 tp))
22153 mod (string-to-number (match-string 2 tp))))
22154 (or tp (setq hod (nth 2 (decode-time (current-time)))
22155 mod (nth 1 (decode-time (current-time))))))
22156 (cond
22157 ((eq major-mode 'calendar-mode)
22158 (setq date (calendar-cursor-to-date)
22159 defd (encode-time 0 (or mod 0) (or hod 0)
22160 (nth 1 date) (nth 0 date) (nth 2 date))))
22161 ((eq major-mode 'org-agenda-mode)
22162 (setq day (get-text-property (point) 'day))
22163 (if day
22164 (setq date (calendar-gregorian-from-absolute day)
22165 defd (encode-time 0 (or mod 0) (or hod 0)
22166 (nth 1 date) (nth 0 date) (nth 2 date))))))
22167 (or defd (current-time))))
22169 (defun org-mark-subtree (&optional up)
22170 "Mark the current subtree.
22171 This puts point at the start of the current subtree, and mark at
22172 the end. If a numeric prefix UP is given, move up into the
22173 hierarchy of headlines by UP levels before marking the subtree."
22174 (interactive "P")
22175 (org-with-limited-levels
22176 (cond ((org-at-heading-p) (beginning-of-line))
22177 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22178 (t (outline-previous-visible-heading 1))))
22179 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
22180 (if (org-called-interactively-p 'any)
22181 (call-interactively 'org-mark-element)
22182 (org-mark-element)))
22185 ;;; Indentation
22187 (defun org-indent-line ()
22188 "Indent line depending on context."
22189 (interactive)
22190 (let* ((pos (point))
22191 (itemp (org-at-item-p))
22192 (case-fold-search t)
22193 (org-drawer-regexp (or org-drawer-regexp "\000"))
22194 (inline-task-p (and (featurep 'org-inlinetask)
22195 (org-inlinetask-in-task-p)))
22196 (inline-re (and inline-task-p
22197 (org-inlinetask-outline-regexp)))
22198 column)
22199 (if (and orgstruct-is-++ (eq pos (point)))
22200 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
22201 (indent-according-to-mode))
22202 (beginning-of-line 1)
22203 (cond
22204 ;; Headings
22205 ((looking-at org-outline-regexp) (setq column 0))
22206 ;; Footnote definition
22207 ((looking-at org-footnote-definition-re) (setq column 0))
22208 ;; Literal examples
22209 ((looking-at "[ \t]*:\\( \\|$\\)")
22210 (setq column (org-get-indentation))) ; do nothing
22211 ;; Lists
22212 ((ignore-errors (goto-char (org-in-item-p)))
22213 (setq column (if itemp
22214 (org-get-indentation)
22215 (org-list-item-body-column (point))))
22216 (goto-char pos))
22217 ;; Drawers
22218 ((and (looking-at "[ \t]*:END:")
22219 (save-excursion (re-search-backward org-drawer-regexp nil t)))
22220 (save-excursion
22221 (goto-char (1- (match-beginning 1)))
22222 (setq column (current-column))))
22223 ;; Special blocks
22224 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
22225 (save-excursion
22226 (re-search-backward
22227 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
22228 (setq column (org-get-indentation (match-string 0))))
22229 ((and (not (looking-at "[ \t]*#\\+begin_"))
22230 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
22231 (save-excursion
22232 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
22233 (setq column
22234 (cond ((equal (downcase (match-string 1)) "src")
22235 ;; src blocks: let `org-edit-src-exit' handle them
22236 (org-get-indentation))
22237 ((equal (downcase (match-string 1)) "example")
22238 (max (org-get-indentation)
22239 (org-get-indentation (match-string 0))))
22241 (org-get-indentation (match-string 0))))))
22242 ;; This line has nothing special, look at the previous relevant
22243 ;; line to compute indentation
22245 (beginning-of-line 0)
22246 (while (and (not (bobp))
22247 (not (looking-at org-table-line-regexp))
22248 (not (looking-at org-drawer-regexp))
22249 ;; When point started in an inline task, do not move
22250 ;; above task starting line.
22251 (not (and inline-task-p (looking-at inline-re)))
22252 ;; Skip drawers, blocks, empty lines, verbatim,
22253 ;; comments, tables, footnotes definitions, lists,
22254 ;; inline tasks.
22255 (or (and (looking-at "[ \t]*:END:")
22256 (re-search-backward org-drawer-regexp nil t))
22257 (and (looking-at "[ \t]*#\\+end_")
22258 (re-search-backward "[ \t]*#\\+begin_"nil t))
22259 (looking-at "[ \t]*[\n:#|]")
22260 (looking-at org-footnote-definition-re)
22261 (and (not inline-task-p)
22262 (featurep 'org-inlinetask)
22263 (org-inlinetask-in-task-p)
22264 (or (org-inlinetask-goto-beginning) t))))
22265 (beginning-of-line 0))
22266 (cond
22267 ;; There was a list item above.
22268 ((ignore-errors (goto-char (org-in-item-p)))
22269 (goto-char (org-list-get-top-point (org-list-struct)))
22270 (setq column (org-get-indentation)))
22271 ;; There was an heading above.
22272 ((looking-at "\\*+[ \t]+")
22273 (if (not org-adapt-indentation)
22274 (setq column 0)
22275 (goto-char (match-end 0))
22276 (setq column (current-column))))
22277 ;; A drawer had started and is unfinished
22278 ((looking-at org-drawer-regexp)
22279 (goto-char (1- (match-beginning 1)))
22280 (setq column (current-column)))
22281 ;; Else, nothing noticeable found: get indentation and go on.
22282 (t (setq column (org-get-indentation))))))
22283 ;; Now apply indentation and move cursor accordingly
22284 (goto-char pos)
22285 (if (<= (current-column) (current-indentation))
22286 (org-indent-line-to column)
22287 (save-excursion (org-indent-line-to column)))
22288 ;; Special polishing for properties, see `org-property-format'
22289 (setq column (current-column))
22290 (beginning-of-line 1)
22291 (if (looking-at org-property-re)
22292 (replace-match (concat (match-string 4)
22293 (format org-property-format
22294 (match-string 1) (match-string 3)))
22295 t t))
22296 (org-move-to-column column))))
22298 (defun org-indent-drawer ()
22299 "Indent the drawer at point."
22300 (interactive)
22301 (let ((p (point))
22302 (e (and (save-excursion (re-search-forward ":END:" nil t))
22303 (match-end 0)))
22304 (folded
22305 (save-excursion
22306 (end-of-line)
22307 (when (overlays-at (point))
22308 (member 'invisible (overlay-properties
22309 (car (overlays-at (point)))))))))
22310 (when folded (org-cycle))
22311 (indent-for-tab-command)
22312 (while (and (move-beginning-of-line 2) (< (point) e))
22313 (indent-for-tab-command))
22314 (goto-char p)
22315 (when folded (org-cycle)))
22316 (message "Drawer at point indented"))
22318 (defun org-indent-block ()
22319 "Indent the block at point."
22320 (interactive)
22321 (let ((p (point))
22322 (case-fold-search t)
22323 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
22324 (match-end 0)))
22325 (folded
22326 (save-excursion
22327 (end-of-line)
22328 (when (overlays-at (point))
22329 (member 'invisible (overlay-properties
22330 (car (overlays-at (point)))))))))
22331 (when folded (org-cycle))
22332 (indent-for-tab-command)
22333 (while (and (move-beginning-of-line 2) (< (point) e))
22334 (indent-for-tab-command))
22335 (goto-char p)
22336 (when folded (org-cycle)))
22337 (message "Block at point indented"))
22339 (defun org-indent-region (start end)
22340 "Indent region."
22341 (interactive "r")
22342 (save-excursion
22343 (let ((line-end (org-current-line end)))
22344 (goto-char start)
22345 (while (< (org-current-line) line-end)
22346 (cond ((org-in-src-block-p t) (org-src-native-tab-command-maybe))
22347 (t (call-interactively 'org-indent-line)))
22348 (move-beginning-of-line 2)))))
22351 ;;; Filling
22353 ;; We use our own fill-paragraph and auto-fill functions.
22355 ;; `org-fill-paragraph' relies on adaptive filling and context
22356 ;; checking. Appropriate `fill-prefix' is computed with
22357 ;; `org-adaptive-fill-function'.
22359 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22360 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22361 ;; `org-adaptive-fill-function' value. Internally,
22362 ;; `org-comment-line-break-function' breaks the line.
22364 ;; `org-setup-filling' installs filling and auto-filling related
22365 ;; variables during `org-mode' initialization.
22367 (defvar org-element-paragraph-separate) ; org-element.el
22368 (defun org-setup-filling ()
22369 (require 'org-element)
22370 ;; Prevent auto-fill from inserting unwanted new items.
22371 (when (boundp 'fill-nobreak-predicate)
22372 (org-set-local
22373 'fill-nobreak-predicate
22374 (org-uniquify
22375 (append fill-nobreak-predicate
22376 '(org-fill-line-break-nobreak-p
22377 org-fill-paragraph-with-timestamp-nobreak-p)))))
22378 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22379 (org-set-local 'paragraph-start paragraph-ending)
22380 (org-set-local 'paragraph-separate paragraph-ending))
22381 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22382 (org-set-local 'auto-fill-inhibit-regexp nil)
22383 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22384 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22385 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22387 (defun org-fill-line-break-nobreak-p ()
22388 "Non-nil when a new line at point would create an Org line break."
22389 (save-excursion
22390 (skip-chars-backward "[ \t]")
22391 (skip-chars-backward "\\\\")
22392 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22394 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22395 "Non-nil when a new line at point would split a timestamp."
22396 (and (org-at-timestamp-p t)
22397 (not (looking-at org-ts-regexp-both))))
22399 (declare-function message-in-body-p "message" ())
22400 (defvar orgtbl-line-start-regexp) ; From org-table.el
22401 (defun org-adaptive-fill-function ()
22402 "Compute a fill prefix for the current line.
22403 Return fill prefix, as a string, or nil if current line isn't
22404 meant to be filled. For convenience, if `adaptive-fill-regexp'
22405 matches in paragraphs or comments, use it."
22406 (catch 'exit
22407 (when (derived-mode-p 'message-mode)
22408 (save-excursion
22409 (beginning-of-line)
22410 (cond ((or (not (message-in-body-p))
22411 (looking-at orgtbl-line-start-regexp))
22412 (throw 'exit nil))
22413 ((looking-at message-cite-prefix-regexp)
22414 (throw 'exit (match-string-no-properties 0)))
22415 ((looking-at org-outline-regexp)
22416 (throw 'exit (make-string (length (match-string 0)) ? ))))))
22417 (org-with-wide-buffer
22418 (let* ((p (line-beginning-position))
22419 (element (save-excursion
22420 (beginning-of-line)
22421 (or (ignore-errors (org-element-at-point))
22422 (user-error "An element cannot be parsed line %d"
22423 (line-number-at-pos (point))))))
22424 (type (org-element-type element))
22425 (post-affiliated (org-element-property :post-affiliated element)))
22426 (unless (and post-affiliated (< p post-affiliated))
22427 (case type
22428 (comment
22429 (save-excursion
22430 (beginning-of-line)
22431 (looking-at "[ \t]*")
22432 (concat (match-string 0) "# ")))
22433 (footnote-definition "")
22434 ((item plain-list)
22435 (make-string (org-list-item-body-column
22436 (or post-affiliated
22437 (org-element-property :begin element)))
22438 ? ))
22439 (paragraph
22440 ;; Fill prefix is usually the same as the current line,
22441 ;; unless the paragraph is at the beginning of an item.
22442 (let ((parent (org-element-property :parent element)))
22443 (save-excursion
22444 (beginning-of-line)
22445 (cond ((eq (org-element-type parent) 'item)
22446 (make-string (org-list-item-body-column
22447 (org-element-property :begin parent))
22448 ? ))
22449 ((and adaptive-fill-regexp
22450 ;; Locally disable
22451 ;; `adaptive-fill-function' to let
22452 ;; `fill-context-prefix' handle
22453 ;; `adaptive-fill-regexp' variable.
22454 (let (adaptive-fill-function)
22455 (fill-context-prefix
22456 post-affiliated
22457 (org-element-property :end element)))))
22458 ((looking-at "[ \t]+") (match-string 0))
22459 (t "")))))
22460 (comment-block
22461 ;; Only fill contents if P is within block boundaries.
22462 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22463 (forward-line)
22464 (point)))
22465 (cend (save-excursion
22466 (goto-char (org-element-property :end element))
22467 (skip-chars-backward " \r\t\n")
22468 (line-beginning-position))))
22469 (when (and (>= p cbeg) (< p cend))
22470 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22471 (match-string 0)
22472 ""))))))))))
22474 (declare-function message-goto-body "message" ())
22475 (defvar message-cite-prefix-regexp) ; From message.el
22476 (defun org-fill-paragraph (&optional justify)
22477 "Fill element at point, when applicable.
22479 This function only applies to comment blocks, comments, example
22480 blocks and paragraphs. Also, as a special case, re-align table
22481 when point is at one.
22483 If JUSTIFY is non-nil (interactively, with prefix argument),
22484 justify as well. If `sentence-end-double-space' is non-nil, then
22485 period followed by one space does not end a sentence, so don't
22486 break a line there. The variable `fill-column' controls the
22487 width for filling.
22489 For convenience, when point is at a plain list, an item or
22490 a footnote definition, try to fill the first paragraph within."
22491 (interactive)
22492 (if (and (derived-mode-p 'message-mode)
22493 (or (not (message-in-body-p))
22494 (save-excursion (move-beginning-of-line 1)
22495 (looking-at message-cite-prefix-regexp))))
22496 ;; First ensure filling is correct in message-mode.
22497 (let ((fill-paragraph-function
22498 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22499 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22500 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22501 (paragraph-separate
22502 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22503 (fill-paragraph nil))
22504 (with-syntax-table org-mode-transpose-word-syntax-table
22505 ;; Move to end of line in order to get the first paragraph
22506 ;; within a plain list or a footnote definition.
22507 (let ((element (save-excursion
22508 (end-of-line)
22509 (or (ignore-errors (org-element-at-point))
22510 (user-error "An element cannot be parsed line %d"
22511 (line-number-at-pos (point)))))))
22512 ;; First check if point is in a blank line at the beginning of
22513 ;; the buffer. In that case, ignore filling.
22514 (case (org-element-type element)
22515 ;; Use major mode filling function is src blocks.
22516 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22517 ;; Align Org tables, leave table.el tables as-is.
22518 (table-row (org-table-align) t)
22519 (table
22520 (when (eq (org-element-property :type element) 'org)
22521 (save-excursion
22522 (goto-char (org-element-property :post-affiliated element))
22523 (org-table-align)))
22525 (paragraph
22526 ;; Paragraphs may contain `line-break' type objects.
22527 (let ((beg (max (point-min)
22528 (org-element-property :contents-begin element)))
22529 (end (min (point-max)
22530 (org-element-property :contents-end element))))
22531 ;; Do nothing if point is at an affiliated keyword.
22532 (if (< (line-end-position) beg) t
22533 (when (derived-mode-p 'message-mode)
22534 ;; In `message-mode', do not fill following citation
22535 ;; in current paragraph nor text before message body.
22536 (let ((body-start (save-excursion (message-goto-body))))
22537 (when body-start (setq beg (max body-start beg))))
22538 (when (save-excursion
22539 (re-search-forward
22540 (concat "^" message-cite-prefix-regexp) end t))
22541 (setq end (match-beginning 0))))
22542 ;; Fill paragraph, taking line breaks into account.
22543 ;; For that, slice the paragraph using line breaks as
22544 ;; separators, and fill the parts in reverse order to
22545 ;; avoid messing with markers.
22546 (save-excursion
22547 (goto-char end)
22548 (mapc
22549 (lambda (pos)
22550 (fill-region-as-paragraph pos (point) justify)
22551 (goto-char pos))
22552 ;; Find the list of ending positions for line breaks
22553 ;; in the current paragraph. Add paragraph
22554 ;; beginning to include first slice.
22555 (nreverse
22556 (cons beg
22557 (org-element-map
22558 (org-element--parse-objects
22559 beg end nil (org-element-restriction 'paragraph))
22560 'line-break
22561 (lambda (lb) (org-element-property :end lb)))))))
22562 t)))
22563 ;; Contents of `comment-block' type elements should be
22564 ;; filled as plain text, but only if point is within block
22565 ;; markers.
22566 (comment-block
22567 (let* ((case-fold-search t)
22568 (beg (save-excursion
22569 (goto-char (org-element-property :begin element))
22570 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22571 (forward-line)
22572 (point)))
22573 (end (save-excursion
22574 (goto-char (org-element-property :end element))
22575 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22576 (line-beginning-position))))
22577 (if (or (< (point) beg) (> (point) end)) t
22578 (fill-region-as-paragraph
22579 (save-excursion (end-of-line)
22580 (re-search-backward "^[ \t]*$" beg 'move)
22581 (line-beginning-position))
22582 (save-excursion (beginning-of-line)
22583 (re-search-forward "^[ \t]*$" end 'move)
22584 (line-beginning-position))
22585 justify))))
22586 ;; Fill comments.
22587 (comment
22588 (let ((begin (org-element-property :post-affiliated element))
22589 (end (org-element-property :end element)))
22590 (when (and (>= (point) begin) (<= (point) end))
22591 (let ((begin (save-excursion
22592 (end-of-line)
22593 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22594 (progn (forward-line) (point))
22595 begin)))
22596 (end (save-excursion
22597 (end-of-line)
22598 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22599 (1- (line-beginning-position))
22600 (skip-chars-backward " \r\t\n")
22601 (line-end-position)))))
22602 ;; Do not fill comments when at a blank line.
22603 (when (> end begin)
22604 (let ((fill-prefix
22605 (save-excursion
22606 (beginning-of-line)
22607 (looking-at "[ \t]*#")
22608 (let ((comment-prefix (match-string 0)))
22609 (goto-char (match-end 0))
22610 (if (looking-at adaptive-fill-regexp)
22611 (concat comment-prefix (match-string 0))
22612 (concat comment-prefix " "))))))
22613 (save-excursion
22614 (fill-region-as-paragraph begin end justify))))))
22616 ;; Ignore every other element.
22617 (otherwise t))))))
22619 (defun org-auto-fill-function ()
22620 "Auto-fill function."
22621 ;; Check if auto-filling is meaningful.
22622 (let ((fc (current-fill-column)))
22623 (when (and fc (> (current-column) fc))
22624 (let* ((fill-prefix (org-adaptive-fill-function))
22625 ;; Enforce empty fill prefix, if required. Otherwise, it
22626 ;; will be computed again.
22627 (adaptive-fill-mode (not (equal fill-prefix ""))))
22628 (when fill-prefix (do-auto-fill))))))
22630 (defun org-comment-line-break-function (&optional soft)
22631 "Break line at point and indent, continuing comment if within one.
22632 The inserted newline is marked hard if variable
22633 `use-hard-newlines' is true, unless optional argument SOFT is
22634 non-nil."
22635 (if soft (insert-and-inherit ?\n) (newline 1))
22636 (save-excursion (forward-char -1) (delete-horizontal-space))
22637 (delete-horizontal-space)
22638 (indent-to-left-margin)
22639 (insert-before-markers-and-inherit fill-prefix))
22642 ;;; Fixed Width Areas
22644 (defun org-toggle-fixed-width ()
22645 "Toggle fixed-width markup.
22647 Add or remove fixed-width markup on current line, whenever it
22648 makes sense. Return an error otherwise.
22650 If a region is active and if it contains only fixed-width areas
22651 or blank lines, remove all fixed-width markup in it. If the
22652 region contains anything else, convert all non-fixed-width lines
22653 to fixed-width ones.
22655 Blank lines at the end of the region are ignored unless the
22656 region only contains such lines."
22657 (interactive)
22658 (if (not (org-region-active-p))
22659 ;; No region:
22661 ;; Remove fixed width marker only in a fixed-with element.
22663 ;; Add fixed width maker in paragraphs, in blank lines after
22664 ;; elements or at the beginning of a headline or an inlinetask,
22665 ;; and before any one-line elements (e.g., a clock).
22666 (progn
22667 (beginning-of-line)
22668 (let* ((element (org-element-at-point))
22669 (type (org-element-type element)))
22670 (cond
22671 ((and (eq type 'fixed-width)
22672 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
22673 (replace-match
22674 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
22675 ((and (memq type '(babel-call clock comment diary-sexp headline
22676 horizontal-rule keyword paragraph
22677 planning))
22678 (or (not (org-element-property :post-affiliated element))
22679 (<= (org-element-property :post-affiliated element)
22680 (point))))
22681 (skip-chars-forward " \t")
22682 (insert ": "))
22683 ((and (org-looking-at-p "[ \t]*$")
22684 (or (eq type 'inlinetask)
22685 (save-excursion
22686 (skip-chars-forward " \r\t\n")
22687 (<= (org-element-property :end element) (point)))))
22688 (delete-region (point) (line-end-position))
22689 (org-indent-line)
22690 (insert ": "))
22691 (t (user-error "Cannot insert a fixed-width line here")))))
22692 ;; Region active.
22693 (let* ((begin (save-excursion
22694 (goto-char (region-beginning))
22695 (line-beginning-position)))
22696 (end (copy-marker
22697 (save-excursion
22698 (goto-char (region-end))
22699 (unless (eolp) (beginning-of-line))
22700 (if (save-excursion (re-search-backward "\\S-" begin t))
22701 (progn (skip-chars-backward " \r\t\n") (point))
22702 (point)))))
22703 (all-fixed-width-p
22704 (catch 'not-all-p
22705 (save-excursion
22706 (goto-char begin)
22707 (skip-chars-forward " \r\t\n")
22708 (when (eobp) (throw 'not-all-p nil))
22709 (while (< (point) end)
22710 (let ((element (org-element-at-point)))
22711 (if (eq (org-element-type element) 'fixed-width)
22712 (goto-char (org-element-property :end element))
22713 (throw 'not-all-p nil))))
22714 t))))
22715 (if all-fixed-width-p
22716 (save-excursion
22717 (goto-char begin)
22718 (while (< (point) end)
22719 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
22720 (replace-match
22721 "" nil nil nil
22722 (if (= (line-end-position) (match-end 0)) 0 1)))
22723 (forward-line)))
22724 (let ((min-ind (point-max)))
22725 ;; Find minimum indentation across all lines.
22726 (save-excursion
22727 (goto-char begin)
22728 (if (not (save-excursion (re-search-forward "\\S-" end t)))
22729 (setq min-ind 0)
22730 (catch 'zerop
22731 (while (< (point) end)
22732 (unless (org-looking-at-p "[ \t]*$")
22733 (let ((ind (org-get-indentation)))
22734 (setq min-ind (min min-ind ind))
22735 (when (zerop ind) (throw 'zerop t))))
22736 (forward-line)))))
22737 ;; Loop over all lines and add fixed-width markup everywhere
22738 ;; but in fixed-width lines.
22739 (save-excursion
22740 (goto-char begin)
22741 (while (< (point) end)
22742 (cond
22743 ((org-at-heading-p)
22744 (insert ": ")
22745 (forward-line)
22746 (while (and (< (point) end) (org-looking-at-p "[ \t]*$"))
22747 (insert ":")
22748 (forward-line)))
22749 ((org-looking-at-p "[ \t]*:\\( \\|$\\)")
22750 (let* ((element (org-element-at-point))
22751 (element-end (org-element-property :end element)))
22752 (if (eq (org-element-type element) 'fixed-width)
22753 (progn (goto-char element-end)
22754 (skip-chars-backward " \r\t\n")
22755 (forward-line))
22756 (let ((limit (min end element-end)))
22757 (while (< (point) limit)
22758 (org-move-to-column min-ind t)
22759 (insert ": ")
22760 (forward-line))))))
22762 (org-move-to-column min-ind t)
22763 (insert ": ")
22764 (forward-line)))))))
22765 (set-marker end nil))))
22768 ;;; Comments
22770 ;; Org comments syntax is quite complex. It requires the entire line
22771 ;; to be just a comment. Also, even with the right syntax at the
22772 ;; beginning of line, some some elements (i.e. verse-block or
22773 ;; example-block) don't accept comments. Usual Emacs comment commands
22774 ;; cannot cope with those requirements. Therefore, Org replaces them.
22776 ;; Org still relies on `comment-dwim', but cannot trust
22777 ;; `comment-only-p'. So, `comment-region-function' and
22778 ;; `uncomment-region-function' both point
22779 ;; to`org-comment-or-uncomment-region'. Eventually,
22780 ;; `org-insert-comment' takes care of insertion of comments at the
22781 ;; beginning of line.
22783 ;; `org-setup-comments-handling' install comments related variables
22784 ;; during `org-mode' initialization.
22786 (defun org-setup-comments-handling ()
22787 (interactive)
22788 (org-set-local 'comment-use-syntax nil)
22789 (org-set-local 'comment-start "# ")
22790 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22791 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22792 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22793 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22795 (defun org-insert-comment ()
22796 "Insert an empty comment above current line.
22797 If the line is empty, insert comment at its beginning. When
22798 point is within a source block, comment according to the related
22799 major mode."
22800 (if (let ((element (org-element-at-point)))
22801 (and (eq (org-element-type element) 'src-block)
22802 (< (save-excursion
22803 (goto-char (org-element-property :post-affiliated element))
22804 (line-end-position))
22805 (point))
22806 (> (save-excursion
22807 (goto-char (org-element-property :end element))
22808 (skip-chars-backward " \r\t\n")
22809 (line-beginning-position))
22810 (point))))
22811 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim))
22812 (beginning-of-line)
22813 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
22814 (open-line 1))
22815 (org-indent-line)
22816 (insert "# ")))
22818 (defvar comment-empty-lines) ; From newcomment.el.
22819 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22820 "Comment or uncomment each non-blank line in the region.
22821 Uncomment each non-blank line between BEG and END if it only
22822 contains commented lines. Otherwise, comment them. If region is
22823 strictly within a source block, use appropriate comment syntax."
22824 (if (let ((element (org-element-at-point)))
22825 (and (eq (org-element-type element) 'src-block)
22826 (< (save-excursion
22827 (goto-char (org-element-property :post-affiliated element))
22828 (line-end-position))
22829 beg)
22830 (>= (save-excursion
22831 (goto-char (org-element-property :end element))
22832 (skip-chars-backward " \r\t\n")
22833 (line-beginning-position))
22834 end)))
22835 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim))
22836 (save-restriction
22837 ;; Restrict region
22838 (narrow-to-region (save-excursion (goto-char beg)
22839 (skip-chars-forward " \r\t\n" end)
22840 (line-beginning-position))
22841 (save-excursion (goto-char end)
22842 (skip-chars-backward " \r\t\n" beg)
22843 (line-end-position)))
22844 (let ((uncommentp
22845 ;; UNCOMMENTP is non-nil when every non blank line between
22846 ;; BEG and END is a comment.
22847 (save-excursion
22848 (goto-char (point-min))
22849 (while (and (not (eobp))
22850 (let ((element (org-element-at-point)))
22851 (and (eq (org-element-type element) 'comment)
22852 (goto-char (min (point-max)
22853 (org-element-property
22854 :end element)))))))
22855 (eobp))))
22856 (if uncommentp
22857 ;; Only blank lines and comments in region: uncomment it.
22858 (save-excursion
22859 (goto-char (point-min))
22860 (while (not (eobp))
22861 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22862 (replace-match "" nil nil nil 1))
22863 (forward-line)))
22864 ;; Comment each line in region.
22865 (let ((min-indent (point-max)))
22866 ;; First find the minimum indentation across all lines.
22867 (save-excursion
22868 (goto-char (point-min))
22869 (while (and (not (eobp)) (not (zerop min-indent)))
22870 (unless (looking-at "[ \t]*$")
22871 (setq min-indent (min min-indent (current-indentation))))
22872 (forward-line)))
22873 ;; Then loop over all lines.
22874 (save-excursion
22875 (goto-char (point-min))
22876 (while (not (eobp))
22877 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22878 ;; Don't get fooled by invisible text (e.g. link path)
22879 ;; when moving to column MIN-INDENT.
22880 (let ((buffer-invisibility-spec nil))
22881 (org-move-to-column min-indent t))
22882 (insert comment-start))
22883 (forward-line)))))))))
22885 (defun org-comment-dwim (arg)
22886 (interactive "*P")
22887 "Call `comment-dwim' within a source edit buffer if needed."
22888 (if (org-in-src-block-p)
22889 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim))
22890 (call-interactively #'comment-dwim)))
22893 ;;; Planning
22895 ;; This section contains tools to operate on timestamp objects, as
22896 ;; returned by, e.g. `org-element-context'.
22898 (defun org-timestamp-has-time-p (timestamp)
22899 "Non-nil when TIMESTAMP has a time specified."
22900 (org-element-property :hour-start timestamp))
22902 (defun org-timestamp-format (timestamp format &optional end utc)
22903 "Format a TIMESTAMP element into a string.
22905 FORMAT is a format specifier to be passed to
22906 `format-time-string'.
22908 When optional argument END is non-nil, use end of date-range or
22909 time-range, if possible.
22911 When optional argument UTC is non-nil, time will be expressed as
22912 Universal Time."
22913 (format-time-string
22914 format
22915 (apply 'encode-time
22916 (cons 0
22917 (mapcar
22918 (lambda (prop) (or (org-element-property prop timestamp) 0))
22919 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22920 '(:minute-start :hour-start :day-start :month-start
22921 :year-start)))))
22922 utc))
22924 (defun org-timestamp-split-range (timestamp &optional end)
22925 "Extract a timestamp object from a date or time range.
22927 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22928 the end of the range. Otherwise, extract its start.
22930 Return a new timestamp object sharing the same parent as
22931 TIMESTAMP."
22932 (let ((type (org-element-property :type timestamp)))
22933 (if (memq type '(active inactive diary)) timestamp
22934 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22935 ;; Set new type.
22936 (org-element-put-property
22937 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22938 ;; Copy start properties over end properties if END is
22939 ;; non-nil. Otherwise, copy end properties over `start' ones.
22940 (let ((p-alist '((:minute-start . :minute-end)
22941 (:hour-start . :hour-end)
22942 (:day-start . :day-end)
22943 (:month-start . :month-end)
22944 (:year-start . :year-end))))
22945 (dolist (p-cell p-alist)
22946 (org-element-put-property
22947 split-ts
22948 (funcall (if end 'car 'cdr) p-cell)
22949 (org-element-property
22950 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22951 ;; Eventually refresh `:raw-value'.
22952 (org-element-put-property split-ts :raw-value nil)
22953 (org-element-put-property
22954 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22956 (defun org-timestamp-translate (timestamp &optional boundary)
22957 "Apply `org-translate-time' on a TIMESTAMP object.
22958 When optional argument BOUNDARY is non-nil, it is either the
22959 symbol `start' or `end'. In this case, only translate the
22960 starting or ending part of TIMESTAMP if it is a date or time
22961 range. Otherwise, translate both parts."
22962 (if (and (not boundary)
22963 (memq (org-element-property :type timestamp)
22964 '(active-range inactive-range)))
22965 (concat
22966 (org-translate-time
22967 (org-element-property :raw-value
22968 (org-timestamp-split-range timestamp)))
22969 "--"
22970 (org-translate-time
22971 (org-element-property :raw-value
22972 (org-timestamp-split-range timestamp t))))
22973 (org-translate-time
22974 (org-element-property
22975 :raw-value
22976 (if (not boundary) timestamp
22977 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22981 ;;; Other stuff.
22983 (defun org-reftex-citation ()
22984 "Use reftex-citation to insert a citation into the buffer.
22985 This looks for a line like
22987 #+BIBLIOGRAPHY: foo plain option:-d
22989 and derives from it that foo.bib is the bibliography file relevant
22990 for this document. It then installs the necessary environment for RefTeX
22991 to work in this buffer and calls `reftex-citation' to insert a citation
22992 into the buffer.
22994 Export of such citations to both LaTeX and HTML is handled by the contributed
22995 package ox-bibtex by Taru Karttunen."
22996 (interactive)
22997 (let ((reftex-docstruct-symbol 'rds)
22998 (reftex-cite-format "\\cite{%l}")
22999 rds bib)
23000 (save-excursion
23001 (save-restriction
23002 (widen)
23003 (let ((case-fold-search t)
23004 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23005 (if (not (save-excursion
23006 (or (re-search-forward re nil t)
23007 (re-search-backward re nil t))))
23008 (error "No bibliography defined in file")
23009 (setq bib (concat (match-string 1) ".bib")
23010 rds (list (list 'bib bib)))))))
23011 (call-interactively 'reftex-citation)))
23013 ;;;; Functions extending outline functionality
23015 (defun org-beginning-of-line (&optional arg)
23016 "Go to the beginning of the current line. If that is invisible, continue
23017 to a visible line beginning. This makes the function of C-a more intuitive.
23018 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
23019 first attempt, and only move to after the tags when the cursor is already
23020 beyond the end of the headline."
23021 (interactive "P")
23022 (let ((pos (point))
23023 (special (if (consp org-special-ctrl-a/e)
23024 (car org-special-ctrl-a/e)
23025 org-special-ctrl-a/e))
23026 deactivate-mark refpos)
23027 (if (org-bound-and-true-p visual-line-mode)
23028 (beginning-of-visual-line 1)
23029 (beginning-of-line 1))
23030 (if (and arg (fboundp 'move-beginning-of-line))
23031 (call-interactively 'move-beginning-of-line)
23032 (if (bobp)
23034 (backward-char 1)
23035 (if (org-truely-invisible-p)
23036 (while (and (not (bobp)) (org-truely-invisible-p))
23037 (backward-char 1)
23038 (beginning-of-line 1))
23039 (forward-char 1))))
23040 (when special
23041 (cond
23042 ((and (looking-at org-complex-heading-regexp)
23043 (= (char-after (match-end 1)) ?\ ))
23044 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23045 (point-at-eol)))
23046 (goto-char
23047 (if (eq special t)
23048 (cond ((> pos refpos) refpos)
23049 ((= pos (point)) refpos)
23050 (t (point)))
23051 (cond ((> pos (point)) (point))
23052 ((not (eq last-command this-command)) (point))
23053 (t refpos)))))
23054 ((org-at-item-p)
23055 ;; Being at an item and not looking at an the item means point
23056 ;; was previously moved to beginning of a visual line, which
23057 ;; doesn't contain the item. Therefore, do nothing special,
23058 ;; just stay here.
23059 (when (looking-at org-list-full-item-re)
23060 ;; Set special position at first white space character after
23061 ;; bullet, and check-box, if any.
23062 (let ((after-bullet
23063 (let ((box (match-end 3)))
23064 (if (not box) (match-end 1)
23065 (let ((after (char-after box)))
23066 (if (and after (= after ? )) (1+ box) box))))))
23067 ;; Special case: Move point to special position when
23068 ;; currently after it or at beginning of line.
23069 (if (eq special t)
23070 (when (or (> pos after-bullet) (= (point) pos))
23071 (goto-char after-bullet))
23072 ;; Reversed case: Move point to special position when
23073 ;; point was already at beginning of line and command is
23074 ;; repeated.
23075 (when (and (= (point) pos) (eq last-command this-command))
23076 (goto-char after-bullet))))))))
23077 (org-no-warnings
23078 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23079 (setq disable-point-adjustment
23080 (or (not (invisible-p (point)))
23081 (not (invisible-p (max (point-min) (1- (point))))))))
23083 (defun org-end-of-line (&optional arg)
23084 "Go to the end of the line.
23085 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23086 tags on the first attempt, and only move to after the tags when
23087 the cursor is already beyond the end of the headline."
23088 (interactive "P")
23089 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
23090 org-special-ctrl-a/e))
23091 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
23092 'end-of-visual-line)
23093 ((fboundp 'move-end-of-line) 'move-end-of-line)
23094 (t 'end-of-line)))
23095 deactivate-mark)
23096 (if (or (not special) arg) (call-interactively move-fun)
23097 (let* ((element (save-excursion (beginning-of-line)
23098 (org-element-at-point)))
23099 (type (org-element-type element)))
23100 (cond
23101 ((memq type '(headline inlinetask))
23102 (let ((pos (point)))
23103 (beginning-of-line 1)
23104 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
23105 (if (eq special t)
23106 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
23107 (goto-char (match-beginning 1))
23108 (goto-char (match-end 0)))
23109 (if (or (< pos (match-end 0))
23110 (not (eq this-command last-command)))
23111 (goto-char (match-end 0))
23112 (goto-char (match-beginning 1))))
23113 (call-interactively move-fun))))
23114 ((outline-invisible-p (line-end-position))
23115 ;; If element is hidden, `move-end-of-line' would put point
23116 ;; after it. Use `end-of-line' to stay on current line.
23117 (call-interactively 'end-of-line))
23118 (t (call-interactively move-fun)))))
23119 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23120 (setq disable-point-adjustment
23121 (or (not (invisible-p (point)))
23122 (not (invisible-p (max (point-min) (1- (point))))))))
23124 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23125 (define-key org-mode-map "\C-e" 'org-end-of-line)
23127 (defun org-backward-sentence (&optional arg)
23128 "Go to beginning of sentence, or beginning of table field.
23129 This will call `backward-sentence' or `org-table-beginning-of-field',
23130 depending on context."
23131 (interactive "P")
23132 (cond
23133 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
23134 (t (call-interactively 'backward-sentence))))
23136 (defun org-forward-sentence (&optional arg)
23137 "Go to end of sentence, or end of table field.
23138 This will call `forward-sentence' or `org-table-end-of-field',
23139 depending on context."
23140 (interactive "P")
23141 (cond
23142 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
23143 (t (call-interactively 'forward-sentence))))
23145 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23146 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23148 (defun org-kill-line (&optional arg)
23149 "Kill line, to tags or end of line."
23150 (interactive "P")
23151 (cond
23152 ((or (not org-special-ctrl-k)
23153 (bolp)
23154 (not (org-at-heading-p)))
23155 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23156 org-ctrl-k-protect-subtree)
23157 (if (or (eq org-ctrl-k-protect-subtree 'error)
23158 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
23159 (user-error "C-k aborted as it would kill a hidden subtree")))
23160 (call-interactively
23161 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23162 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
23163 (kill-region (point) (match-beginning 1))
23164 (org-set-tags nil t))
23165 (t (kill-region (point) (point-at-eol)))))
23167 (define-key org-mode-map "\C-k" 'org-kill-line)
23169 (defun org-yank (&optional arg)
23170 "Yank. If the kill is a subtree, treat it specially.
23171 This command will look at the current kill and check if is a single
23172 subtree, or a series of subtrees[1]. If it passes the test, and if the
23173 cursor is at the beginning of a line or after the stars of a currently
23174 empty headline, then the yank is handled specially. How exactly depends
23175 on the value of the following variables, both set by default.
23177 org-yank-folded-subtrees
23178 When set, the subtree(s) will be folded after insertion, but only
23179 if doing so would now swallow text after the yanked text.
23181 org-yank-adjusted-subtrees
23182 When set, the subtree will be promoted or demoted in order to
23183 fit into the local outline tree structure, which means that the level
23184 will be adjusted so that it becomes the smaller one of the two
23185 *visible* surrounding headings.
23187 Any prefix to this command will cause `yank' to be called directly with
23188 no special treatment. In particular, a simple \\[universal-argument] prefix \
23189 will just
23190 plainly yank the text as it is.
23192 \[1] The test checks if the first non-white line is a heading
23193 and if there are no other headings with fewer stars."
23194 (interactive "P")
23195 (org-yank-generic 'yank arg))
23197 (defun org-yank-generic (command arg)
23198 "Perform some yank-like command.
23200 This function implements the behavior described in the `org-yank'
23201 documentation. However, it has been generalized to work for any
23202 interactive command with similar behavior."
23204 ;; pretend to be command COMMAND
23205 (setq this-command command)
23207 (if arg
23208 (call-interactively command)
23210 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23211 (and (org-kill-is-subtree-p)
23212 (or (bolp)
23213 (and (looking-at "[ \t]*$")
23214 (string-match
23215 "\\`\\*+\\'"
23216 (buffer-substring (point-at-bol) (point)))))))
23217 swallowp)
23218 (cond
23219 ((and subtreep org-yank-folded-subtrees)
23220 (let ((beg (point))
23221 end)
23222 (if (and subtreep org-yank-adjusted-subtrees)
23223 (org-paste-subtree nil nil 'for-yank)
23224 (call-interactively command))
23226 (setq end (point))
23227 (goto-char beg)
23228 (when (and (bolp) subtreep
23229 (not (setq swallowp
23230 (org-yank-folding-would-swallow-text beg end))))
23231 (org-with-limited-levels
23232 (or (looking-at org-outline-regexp)
23233 (re-search-forward org-outline-regexp-bol end t))
23234 (while (and (< (point) end) (looking-at org-outline-regexp))
23235 (hide-subtree)
23236 (org-cycle-show-empty-lines 'folded)
23237 (condition-case nil
23238 (outline-forward-same-level 1)
23239 (error (goto-char end))))))
23240 (when swallowp
23241 (message
23242 "Inserted text not folded because that would swallow text"))
23244 (goto-char end)
23245 (skip-chars-forward " \t\n\r")
23246 (beginning-of-line 1)
23247 (push-mark beg 'nomsg)))
23248 ((and subtreep org-yank-adjusted-subtrees)
23249 (let ((beg (point-at-bol)))
23250 (org-paste-subtree nil nil 'for-yank)
23251 (push-mark beg 'nomsg)))
23253 (call-interactively command))))))
23255 (defun org-yank-folding-would-swallow-text (beg end)
23256 "Would hide-subtree at BEG swallow any text after END?"
23257 (let (level)
23258 (org-with-limited-levels
23259 (save-excursion
23260 (goto-char beg)
23261 (when (or (looking-at org-outline-regexp)
23262 (re-search-forward org-outline-regexp-bol end t))
23263 (setq level (org-outline-level)))
23264 (goto-char end)
23265 (skip-chars-forward " \t\r\n\v\f")
23266 (if (or (eobp)
23267 (and (bolp) (looking-at org-outline-regexp)
23268 (<= (org-outline-level) level)))
23269 nil ; Nothing would be swallowed
23270 t))))) ; something would swallow
23272 (define-key org-mode-map "\C-y" 'org-yank)
23274 (defun org-truely-invisible-p ()
23275 "Check if point is at a character currently not visible.
23276 This version does not only check the character property, but also
23277 `visible-mode'."
23278 ;; Early versions of noutline don't have `outline-invisible-p'.
23279 (if (org-bound-and-true-p visible-mode)
23281 (outline-invisible-p)))
23283 (defun org-invisible-p2 ()
23284 "Check if point is at a character currently not visible."
23285 (save-excursion
23286 (if (and (eolp) (not (bobp))) (backward-char 1))
23287 ;; Early versions of noutline don't have `outline-invisible-p'.
23288 (outline-invisible-p)))
23290 (defun org-back-to-heading (&optional invisible-ok)
23291 "Call `outline-back-to-heading', but provide a better error message."
23292 (condition-case nil
23293 (outline-back-to-heading invisible-ok)
23294 (error (error "Before first headline at position %d in buffer %s"
23295 (point) (current-buffer)))))
23297 (defun org-before-first-heading-p ()
23298 "Before first heading?"
23299 (save-excursion
23300 (end-of-line)
23301 (null (re-search-backward org-outline-regexp-bol nil t))))
23303 (defun org-at-heading-p (&optional ignored)
23304 (outline-on-heading-p t))
23305 ;; Compatibility alias with Org versions < 7.8.03
23306 (defalias 'org-on-heading-p 'org-at-heading-p)
23308 (defun org-in-commented-heading-p (&optional no-inheritance)
23309 "Non-nil if point is under a commented heading.
23310 This function also checks ancestors of the current headline,
23311 unless optional argument NO-INHERITANCE is non-nil."
23312 (cond
23313 ((org-before-first-heading-p) nil)
23314 ((let ((headline (nth 4 (org-heading-components))))
23315 (and headline
23316 (let ((case-fold-search nil))
23317 (org-string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
23318 headline)))))
23319 (no-inheritance nil)
23321 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
23323 (defun org-at-comment-p nil
23324 "Is cursor in a line starting with a # character?"
23325 (save-excursion
23326 (beginning-of-line)
23327 (looking-at "^#")))
23329 (defun org-at-drawer-p nil
23330 "Is cursor at a drawer keyword?"
23331 (save-excursion
23332 (move-beginning-of-line 1)
23333 (looking-at org-drawer-regexp)))
23335 (defun org-at-block-p nil
23336 "Is cursor at a block keyword?"
23337 (save-excursion
23338 (move-beginning-of-line 1)
23339 (looking-at org-block-regexp)))
23341 (defun org-point-at-end-of-empty-headline ()
23342 "If point is at the end of an empty headline, return t, else nil.
23343 If the heading only contains a TODO keyword, it is still still considered
23344 empty."
23345 (and (looking-at "[ \t]*$")
23346 (when org-todo-line-regexp
23347 (save-excursion
23348 (beginning-of-line 1)
23349 (let ((case-fold-search nil))
23350 (looking-at org-todo-line-regexp)
23351 (string= (match-string 3) ""))))))
23353 (defun org-at-heading-or-item-p ()
23354 (or (org-at-heading-p) (org-at-item-p)))
23356 (defun org-at-target-p ()
23357 (or (org-in-regexp org-radio-target-regexp)
23358 (org-in-regexp org-target-regexp)))
23359 ;; Compatibility alias with Org versions < 7.8.03
23360 (defalias 'org-on-target-p 'org-at-target-p)
23362 (defun org-up-heading-all (arg)
23363 "Move to the heading line of which the present line is a subheading.
23364 This function considers both visible and invisible heading lines.
23365 With argument, move up ARG levels."
23366 (if (fboundp 'outline-up-heading-all)
23367 (outline-up-heading-all arg) ; emacs 21 version of outline.el
23368 (outline-up-heading arg t))) ; emacs 22 version of outline.el
23370 (defun org-up-heading-safe ()
23371 "Move to the heading line of which the present line is a subheading.
23372 This version will not throw an error. It will return the level of the
23373 headline found, or nil if no higher level is found.
23375 Also, this function will be a lot faster than `outline-up-heading',
23376 because it relies on stars being the outline starters. This can really
23377 make a significant difference in outlines with very many siblings."
23378 (let (start-level re)
23379 (org-back-to-heading t)
23380 (setq start-level (funcall outline-level))
23381 (if (equal start-level 1)
23383 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
23384 (if (re-search-backward re nil t)
23385 (funcall outline-level)))))
23387 (defun org-first-sibling-p ()
23388 "Is this heading the first child of its parents?"
23389 (interactive)
23390 (let ((re org-outline-regexp-bol)
23391 level l)
23392 (unless (org-at-heading-p t)
23393 (user-error "Not at a heading"))
23394 (setq level (funcall outline-level))
23395 (save-excursion
23396 (if (not (re-search-backward re nil t))
23398 (setq l (funcall outline-level))
23399 (< l level)))))
23401 (defun org-goto-sibling (&optional previous)
23402 "Goto the next sibling, even if it is invisible.
23403 When PREVIOUS is set, go to the previous sibling instead. Returns t
23404 when a sibling was found. When none is found, return nil and don't
23405 move point."
23406 (let ((fun (if previous 're-search-backward 're-search-forward))
23407 (pos (point))
23408 (re org-outline-regexp-bol)
23409 level l)
23410 (when (condition-case nil (org-back-to-heading t) (error nil))
23411 (setq level (funcall outline-level))
23412 (catch 'exit
23413 (or previous (forward-char 1))
23414 (while (funcall fun re nil t)
23415 (setq l (funcall outline-level))
23416 (when (< l level) (goto-char pos) (throw 'exit nil))
23417 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23418 (goto-char pos)
23419 nil))))
23421 (defun org-show-siblings ()
23422 "Show all siblings of the current headline."
23423 (save-excursion
23424 (while (org-goto-sibling) (org-flag-heading nil)))
23425 (save-excursion
23426 (while (org-goto-sibling 'previous)
23427 (org-flag-heading nil))))
23429 (defun org-goto-first-child ()
23430 "Goto the first child, even if it is invisible.
23431 Return t when a child was found. Otherwise don't move point and
23432 return nil."
23433 (let (level (pos (point)) (re org-outline-regexp-bol))
23434 (when (condition-case nil (org-back-to-heading t) (error nil))
23435 (setq level (outline-level))
23436 (forward-char 1)
23437 (if (and (re-search-forward re nil t) (> (outline-level) level))
23438 (progn (goto-char (match-beginning 0)) t)
23439 (goto-char pos) nil))))
23441 (defun org-show-hidden-entry ()
23442 "Show an entry where even the heading is hidden."
23443 (save-excursion
23444 (org-show-entry)))
23446 (defun org-flag-heading (flag &optional entry)
23447 "Flag the current heading. FLAG non-nil means make invisible.
23448 When ENTRY is non-nil, show the entire entry."
23449 (save-excursion
23450 (org-back-to-heading t)
23451 ;; Check if we should show the entire entry
23452 (if entry
23453 (progn
23454 (org-show-entry)
23455 (save-excursion
23456 (and (outline-next-heading)
23457 (org-flag-heading nil))))
23458 (outline-flag-region (max (point-min) (1- (point)))
23459 (save-excursion (outline-end-of-heading) (point))
23460 flag))))
23462 (defun org-get-next-sibling ()
23463 "Move to next heading of the same level, and return point.
23464 If there is no such heading, return nil.
23465 This is like outline-next-sibling, but invisible headings are ok."
23466 (let ((level (funcall outline-level)))
23467 (outline-next-heading)
23468 (while (and (not (eobp)) (> (funcall outline-level) level))
23469 (outline-next-heading))
23470 (if (or (eobp) (< (funcall outline-level) level))
23472 (point))))
23474 (defun org-get-last-sibling ()
23475 "Move to previous heading of the same level, and return point.
23476 If there is no such heading, return nil."
23477 (let ((opoint (point))
23478 (level (funcall outline-level)))
23479 (outline-previous-heading)
23480 (when (and (/= (point) opoint) (outline-on-heading-p t))
23481 (while (and (> (funcall outline-level) level)
23482 (not (bobp)))
23483 (outline-previous-heading))
23484 (if (< (funcall outline-level) level)
23486 (point)))))
23488 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23489 "Goto to the end of a subtree."
23490 ;; This contains an exact copy of the original function, but it uses
23491 ;; `org-back-to-heading', to make it work also in invisible
23492 ;; trees. And is uses an invisible-ok argument.
23493 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23494 ;; Furthermore, when used inside Org, finding the end of a large subtree
23495 ;; with many children and grandchildren etc, this can be much faster
23496 ;; than the outline version.
23497 (org-back-to-heading invisible-ok)
23498 (let ((first t)
23499 (level (funcall outline-level)))
23500 (if (and (derived-mode-p 'org-mode) (< level 1000))
23501 ;; A true heading (not a plain list item), in Org-mode
23502 ;; This means we can easily find the end by looking
23503 ;; only for the right number of stars. Using a regexp to do
23504 ;; this is so much faster than using a Lisp loop.
23505 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23506 (forward-char 1)
23507 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23508 ;; something else, do it the slow way
23509 (while (and (not (eobp))
23510 (or first (> (funcall outline-level) level)))
23511 (setq first nil)
23512 (outline-next-heading)))
23513 (unless to-heading
23514 (if (memq (preceding-char) '(?\n ?\^M))
23515 (progn
23516 ;; Go to end of line before heading
23517 (forward-char -1)
23518 (if (memq (preceding-char) '(?\n ?\^M))
23519 ;; leave blank line before heading
23520 (forward-char -1))))))
23521 (point))
23523 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
23524 "Use Org version in org-mode, for dramatic speed-up."
23525 (if (derived-mode-p 'org-mode)
23526 (progn
23527 (org-end-of-subtree nil t)
23528 (unless (eobp) (backward-char 1)))
23529 ad-do-it))
23531 (defun org-end-of-meta-data-and-drawers ()
23532 "Jump to the first text after meta data and drawers in the current entry.
23533 This will move over empty lines, lines with planning time stamps,
23534 clocking lines, and drawers."
23535 (org-back-to-heading t)
23536 (let ((end (save-excursion (outline-next-heading) (point)))
23537 (re (concat "\\(" org-drawer-regexp "\\)"
23538 "\\|" "[ \t]*" org-keyword-time-regexp)))
23539 (forward-line 1)
23540 (while (re-search-forward re end t)
23541 (if (not (match-end 1))
23542 ;; empty or planning line
23543 (forward-line 1)
23544 ;; a drawer, find the end
23545 (re-search-forward "^[ \t]*:END:" end 'move)
23546 (forward-line 1)))
23547 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23548 (point)))
23550 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23551 "Move forward to the ARG'th subheading at same level as this one.
23552 Stop at the first and last subheadings of a superior heading.
23553 Normally this only looks at visible headings, but when INVISIBLE-OK is
23554 non-nil it will also look at invisible ones."
23555 (interactive "p")
23556 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23557 (if (and arg (< arg 0))
23558 (goto-char (point-min))
23559 (outline-next-heading))
23560 (org-at-heading-p)
23561 (let ((level (- (match-end 0) (match-beginning 0) 1))
23562 (f (if (and arg (< arg 0))
23563 're-search-backward
23564 're-search-forward))
23565 (count (if arg (abs arg) 1))
23566 (result (point)))
23567 (while (and (prog1 (> count 0)
23568 (forward-char (if (and arg (< arg 0)) -1 1)))
23569 (funcall f org-outline-regexp-bol nil 'move))
23570 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23571 (cond ((< l level) (setq count 0))
23572 ((and (= l level)
23573 (or invisible-ok
23574 (progn
23575 (goto-char (line-beginning-position))
23576 (not (outline-invisible-p)))))
23577 (setq count (1- count))
23578 (when (eq l level)
23579 (setq result (point)))))))
23580 (goto-char result))
23581 (beginning-of-line 1)))
23583 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23584 "Move backward to the ARG'th subheading at same level as this one.
23585 Stop at the first and last subheadings of a superior heading."
23586 (interactive "p")
23587 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23589 (defun org-next-block (arg &optional backward block-regexp)
23590 "Jump to the next block.
23591 With a prefix argument ARG, jump forward ARG many source blocks.
23592 When BACKWARD is non-nil, jump to the previous block.
23593 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23594 (interactive "p")
23595 (let ((re (or block-regexp org-block-regexp))
23596 (re-search-fn (or (and backward 're-search-backward)
23597 're-search-forward)))
23598 (if (looking-at re) (forward-char 1))
23599 (condition-case nil
23600 (funcall re-search-fn re nil nil arg)
23601 (error (error "No %s code blocks" (if backward "previous" "further" ))))
23602 (goto-char (match-beginning 0)) (org-show-context)))
23604 (defun org-previous-block (arg &optional block-regexp)
23605 "Jump to the previous block.
23606 With a prefix argument ARG, jump backward ARG many source blocks.
23607 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23608 (interactive "p")
23609 (org-next-block arg t block-regexp))
23611 (defun org-forward-paragraph ()
23612 "Move forward to beginning of next paragraph or equivalent.
23614 The function moves point to the beginning of the next visible
23615 structural element, which can be a paragraph, a table, a list
23616 item, etc. It also provides some special moves for convenience:
23618 - On an affiliated keyword, jump to the beginning of the
23619 relative element.
23620 - On an item or a footnote definition, move to the second
23621 element inside, if any.
23622 - On a table or a property drawer, jump after it.
23623 - On a verse or source block, stop after blank lines."
23624 (interactive)
23625 (when (eobp) (user-error "Cannot move further down"))
23626 (let* ((deactivate-mark nil)
23627 (element (org-element-at-point))
23628 (type (org-element-type element))
23629 (post-affiliated (org-element-property :post-affiliated element))
23630 (contents-begin (org-element-property :contents-begin element))
23631 (contents-end (org-element-property :contents-end element))
23632 (end (let ((end (org-element-property :end element)) (parent element))
23633 (while (and (setq parent (org-element-property :parent parent))
23634 (= (org-element-property :contents-end parent) end))
23635 (setq end (org-element-property :end parent)))
23636 end)))
23637 (cond ((not element)
23638 (skip-chars-forward " \r\t\n")
23639 (or (eobp) (beginning-of-line)))
23640 ;; On affiliated keywords, move to element's beginning.
23641 ((and post-affiliated (< (point) post-affiliated))
23642 (goto-char post-affiliated))
23643 ;; At a table row, move to the end of the table. Similarly,
23644 ;; at a node property, move to the end of the property
23645 ;; drawer.
23646 ((memq type '(node-property table-row))
23647 (goto-char (org-element-property
23648 :end (org-element-property :parent element))))
23649 ((memq type '(property-drawer table)) (goto-char end))
23650 ;; Consider blank lines as separators in verse and source
23651 ;; blocks to ease editing.
23652 ((memq type '(src-block verse-block))
23653 (when (eq type 'src-block)
23654 (setq contents-end
23655 (save-excursion (goto-char end)
23656 (skip-chars-backward " \r\t\n")
23657 (line-beginning-position))))
23658 (beginning-of-line)
23659 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23660 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23661 (goto-char end)
23662 (skip-chars-forward " \r\t\n")
23663 (if (= (point) contents-end) (goto-char end)
23664 (beginning-of-line))))
23665 ;; With no contents, just skip element.
23666 ((not contents-begin) (goto-char end))
23667 ;; If contents are invisible, skip the element altogether.
23668 ((outline-invisible-p (line-end-position))
23669 (case type
23670 (headline
23671 (org-with-limited-levels (outline-next-visible-heading 1)))
23672 ;; At a plain list, make sure we move to the next item
23673 ;; instead of skipping the whole list.
23674 (plain-list (forward-char)
23675 (org-forward-paragraph))
23676 (otherwise (goto-char end))))
23677 ((>= (point) contents-end) (goto-char end))
23678 ((>= (point) contents-begin)
23679 ;; This can only happen on paragraphs and plain lists.
23680 (case type
23681 (paragraph (goto-char end))
23682 ;; At a plain list, try to move to second element in
23683 ;; first item, if possible.
23684 (plain-list (end-of-line)
23685 (org-forward-paragraph))))
23686 ;; When contents start on the middle of a line (e.g. in
23687 ;; items and footnote definitions), try to reach first
23688 ;; element starting after current line.
23689 ((> (line-end-position) contents-begin)
23690 (end-of-line)
23691 (org-forward-paragraph))
23692 (t (goto-char contents-begin)))))
23694 (defun org-backward-paragraph ()
23695 "Move backward to start of previous paragraph or equivalent.
23697 The function moves point to the beginning of the current
23698 structural element, which can be a paragraph, a table, a list
23699 item, etc., or to the beginning of the previous visible one if
23700 point is already there. It also provides some special moves for
23701 convenience:
23703 - On an affiliated keyword, jump to the first one.
23704 - On a table or a property drawer, move to its beginning.
23705 - On a verse or source block, stop before blank lines."
23706 (interactive)
23707 (when (bobp) (user-error "Cannot move further up"))
23708 (let* ((deactivate-mark nil)
23709 (element (org-element-at-point))
23710 (type (org-element-type element))
23711 (contents-begin (org-element-property :contents-begin element))
23712 (contents-end (org-element-property :contents-end element))
23713 (post-affiliated (org-element-property :post-affiliated element))
23714 (begin (org-element-property :begin element)))
23715 (cond
23716 ((not element) (goto-char (point-min)))
23717 ((= (point) begin)
23718 (backward-char)
23719 (org-backward-paragraph))
23720 ((and post-affiliated (<= (point) post-affiliated)) (goto-char begin))
23721 ((memq type '(node-property table-row))
23722 (goto-char (org-element-property
23723 :post-affiliated (org-element-property :parent element))))
23724 ((memq type '(property-drawer table)) (goto-char begin))
23725 ((memq type '(src-block verse-block))
23726 (when (eq type 'src-block)
23727 (setq contents-begin
23728 (save-excursion (goto-char begin) (forward-line) (point))))
23729 (if (= (point) contents-begin) (goto-char post-affiliated)
23730 ;; Inside a verse block, see blank lines as paragraph
23731 ;; separators.
23732 (let ((origin (point)))
23733 (skip-chars-backward " \r\t\n" contents-begin)
23734 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
23735 (skip-chars-forward " \r\t\n" origin)
23736 (if (= (point) origin) (goto-char contents-begin)
23737 (beginning-of-line))))))
23738 ((not contents-begin) (goto-char (or post-affiliated begin)))
23739 ((eq type 'paragraph)
23740 (goto-char contents-begin)
23741 ;; When at first paragraph in an item or a footnote definition,
23742 ;; move directly to beginning of line.
23743 (let ((parent-contents
23744 (org-element-property
23745 :contents-begin (org-element-property :parent element))))
23746 (when (and parent-contents (= parent-contents contents-begin))
23747 (beginning-of-line))))
23748 ;; At the end of a greater element, move to the beginning of the
23749 ;; last element within.
23750 ((>= (point) contents-end)
23751 (goto-char (1- contents-end))
23752 (org-backward-paragraph))
23753 (t (goto-char (or post-affiliated begin))))
23754 ;; Ensure we never leave point invisible.
23755 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
23757 (defun org-forward-element ()
23758 "Move forward by one element.
23759 Move to the next element at the same level, when possible."
23760 (interactive)
23761 (cond ((eobp) (user-error "Cannot move further down"))
23762 ((org-with-limited-levels (org-at-heading-p))
23763 (let ((origin (point)))
23764 (goto-char (org-end-of-subtree nil t))
23765 (unless (org-with-limited-levels (org-at-heading-p))
23766 (goto-char origin)
23767 (user-error "Cannot move further down"))))
23769 (let* ((elem (org-element-at-point))
23770 (end (org-element-property :end elem))
23771 (parent (org-element-property :parent elem)))
23772 (cond ((and parent (= (org-element-property :contents-end parent) end))
23773 (goto-char (org-element-property :end parent)))
23774 ((integer-or-marker-p end) (goto-char end))
23775 (t (message "No element at point")))))))
23777 (defun org-backward-element ()
23778 "Move backward by one element.
23779 Move to the previous element at the same level, when possible."
23780 (interactive)
23781 (cond ((bobp) (user-error "Cannot move further up"))
23782 ((org-with-limited-levels (org-at-heading-p))
23783 ;; At a headline, move to the previous one, if any, or stay
23784 ;; here.
23785 (let ((origin (point)))
23786 (org-with-limited-levels (org-backward-heading-same-level 1))
23787 ;; When current headline has no sibling above, move to its
23788 ;; parent.
23789 (when (= (point) origin)
23790 (or (org-with-limited-levels (org-up-heading-safe))
23791 (progn (goto-char origin)
23792 (user-error "Cannot move further up"))))))
23794 (let* ((elem (org-element-at-point))
23795 (beg (org-element-property :begin elem)))
23796 (cond
23797 ;; Move to beginning of current element if point isn't
23798 ;; there already.
23799 ((null beg) (message "No element at point"))
23800 ((/= (point) beg) (goto-char beg))
23801 (t (goto-char beg)
23802 (skip-chars-backward " \r\t\n")
23803 (unless (bobp)
23804 (let ((prev (org-element-at-point)))
23805 (goto-char (org-element-property :begin prev))
23806 (while (and (setq prev (org-element-property :parent prev))
23807 (<= (org-element-property :end prev) beg))
23808 (goto-char (org-element-property :begin prev)))))))))))
23810 (defun org-up-element ()
23811 "Move to upper element."
23812 (interactive)
23813 (if (org-with-limited-levels (org-at-heading-p))
23814 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23815 (let* ((elem (org-element-at-point))
23816 (parent (org-element-property :parent elem)))
23817 (if parent (goto-char (org-element-property :begin parent))
23818 (if (org-with-limited-levels (org-before-first-heading-p))
23819 (user-error "No surrounding element")
23820 (org-with-limited-levels (org-back-to-heading)))))))
23822 (defvar org-element-greater-elements)
23823 (defun org-down-element ()
23824 "Move to inner element."
23825 (interactive)
23826 (let ((element (org-element-at-point)))
23827 (cond
23828 ((memq (org-element-type element) '(plain-list table))
23829 (goto-char (org-element-property :contents-begin element))
23830 (forward-char))
23831 ((memq (org-element-type element) org-element-greater-elements)
23832 ;; If contents are hidden, first disclose them.
23833 (when (outline-invisible-p (line-end-position)) (org-cycle))
23834 (goto-char (or (org-element-property :contents-begin element)
23835 (user-error "No content for this element"))))
23836 (t (user-error "No inner element")))))
23838 (defun org-drag-element-backward ()
23839 "Move backward element at point."
23840 (interactive)
23841 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
23842 (let* ((elem (org-element-at-point))
23843 (prev-elem
23844 (save-excursion
23845 (goto-char (org-element-property :begin elem))
23846 (skip-chars-backward " \r\t\n")
23847 (unless (bobp)
23848 (let* ((beg (org-element-property :begin elem))
23849 (prev (org-element-at-point))
23850 (up prev))
23851 (while (and (setq up (org-element-property :parent up))
23852 (<= (org-element-property :end prev) beg))
23853 (setq prev up))
23854 prev)))))
23855 ;; Error out if no previous element or previous element is
23856 ;; a parent of the current one.
23857 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23858 (user-error "Cannot drag element backward")
23859 (let ((pos (point)))
23860 (org-element-swap-A-B prev-elem elem)
23861 (goto-char (+ (org-element-property :begin prev-elem)
23862 (- pos (org-element-property :begin elem)))))))))
23864 (defun org-drag-element-forward ()
23865 "Move forward element at point."
23866 (interactive)
23867 (let* ((pos (point))
23868 (elem (org-element-at-point)))
23869 (when (= (point-max) (org-element-property :end elem))
23870 (user-error "Cannot drag element forward"))
23871 (goto-char (org-element-property :end elem))
23872 (let ((next-elem (org-element-at-point)))
23873 (when (or (org-element-nested-p elem next-elem)
23874 (and (eq (org-element-type next-elem) 'headline)
23875 (not (eq (org-element-type elem) 'headline))))
23876 (goto-char pos)
23877 (user-error "Cannot drag element forward"))
23878 ;; Compute new position of point: it's shifted by NEXT-ELEM
23879 ;; body's length (without final blanks) and by the length of
23880 ;; blanks between ELEM and NEXT-ELEM.
23881 (let ((size-next (- (save-excursion
23882 (goto-char (org-element-property :end next-elem))
23883 (skip-chars-backward " \r\t\n")
23884 (forward-line)
23885 ;; Small correction if buffer doesn't end
23886 ;; with a newline character.
23887 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23888 (org-element-property :begin next-elem)))
23889 (size-blank (- (org-element-property :end elem)
23890 (save-excursion
23891 (goto-char (org-element-property :end elem))
23892 (skip-chars-backward " \r\t\n")
23893 (forward-line)
23894 (point)))))
23895 (org-element-swap-A-B elem next-elem)
23896 (goto-char (+ pos size-next size-blank))))))
23898 (defun org-drag-line-forward (arg)
23899 "Drag the line at point ARG lines forward."
23900 (interactive "p")
23901 (dotimes (n (abs arg))
23902 (let ((c (current-column)))
23903 (if (< 0 arg)
23904 (progn
23905 (beginning-of-line 2)
23906 (transpose-lines 1)
23907 (beginning-of-line 0))
23908 (transpose-lines 1)
23909 (beginning-of-line -1))
23910 (org-move-to-column c))))
23912 (defun org-drag-line-backward (arg)
23913 "Drag the line at point ARG lines backward."
23914 (interactive "p")
23915 (org-drag-line-forward (- arg)))
23917 (defun org-mark-element ()
23918 "Put point at beginning of this element, mark at end.
23920 Interactively, if this command is repeated or (in Transient Mark
23921 mode) if the mark is active, it marks the next element after the
23922 ones already marked."
23923 (interactive)
23924 (let (deactivate-mark)
23925 (if (and (org-called-interactively-p 'any)
23926 (or (and (eq last-command this-command) (mark t))
23927 (and transient-mark-mode mark-active)))
23928 (set-mark
23929 (save-excursion
23930 (goto-char (mark))
23931 (goto-char (org-element-property :end (org-element-at-point)))))
23932 (let ((element (org-element-at-point)))
23933 (end-of-line)
23934 (push-mark (org-element-property :end element) t t)
23935 (goto-char (org-element-property :begin element))))))
23937 (defun org-narrow-to-element ()
23938 "Narrow buffer to current element."
23939 (interactive)
23940 (let ((elem (org-element-at-point)))
23941 (cond
23942 ((eq (car elem) 'headline)
23943 (narrow-to-region
23944 (org-element-property :begin elem)
23945 (org-element-property :end elem)))
23946 ((memq (car elem) org-element-greater-elements)
23947 (narrow-to-region
23948 (org-element-property :contents-begin elem)
23949 (org-element-property :contents-end elem)))
23951 (narrow-to-region
23952 (org-element-property :begin elem)
23953 (org-element-property :end elem))))))
23955 (defun org-transpose-element ()
23956 "Transpose current and previous elements, keeping blank lines between.
23957 Point is moved after both elements."
23958 (interactive)
23959 (org-skip-whitespace)
23960 (let ((end (org-element-property :end (org-element-at-point))))
23961 (org-drag-element-backward)
23962 (goto-char end)))
23964 (defun org-unindent-buffer ()
23965 "Un-indent the visible part of the buffer.
23966 Relative indentation (between items, inside blocks, etc.) isn't
23967 modified."
23968 (interactive)
23969 (unless (eq major-mode 'org-mode)
23970 (user-error "Cannot un-indent a buffer not in Org mode"))
23971 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23972 unindent-tree ; For byte-compiler.
23973 (unindent-tree
23974 (function
23975 (lambda (contents)
23976 (mapc
23977 (lambda (element)
23978 (if (memq (org-element-type element) '(headline section))
23979 (funcall unindent-tree (org-element-contents element))
23980 (save-excursion
23981 (save-restriction
23982 (narrow-to-region
23983 (org-element-property :begin element)
23984 (org-element-property :end element))
23985 (org-do-remove-indentation)))))
23986 (reverse contents))))))
23987 (funcall unindent-tree (org-element-contents parse-tree))))
23989 (defun org-show-subtree ()
23990 "Show everything after this heading at deeper levels."
23991 (interactive)
23992 (outline-flag-region
23993 (point)
23994 (save-excursion
23995 (org-end-of-subtree t t))
23996 nil))
23998 (defun org-show-entry ()
23999 "Show the body directly following this heading.
24000 Show the heading too, if it is currently invisible."
24001 (interactive)
24002 (save-excursion
24003 (condition-case nil
24004 (progn
24005 (org-back-to-heading t)
24006 (outline-flag-region
24007 (max (point-min) (1- (point)))
24008 (save-excursion
24009 (if (re-search-forward
24010 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24011 (match-beginning 1)
24012 (point-max)))
24013 nil)
24014 (org-cycle-hide-drawers 'children))
24015 (error nil))))
24017 (defun org-make-options-regexp (kwds &optional extra)
24018 "Make a regular expression for keyword lines."
24019 (concat
24020 "^[ \t]*#\\+\\("
24021 (mapconcat 'regexp-quote kwds "\\|")
24022 (if extra (concat "\\|" extra))
24023 "\\):[ \t]*\\(.*\\)"))
24025 ;; Make isearch reveal the necessary context
24026 (defun org-isearch-end ()
24027 "Reveal context after isearch exits."
24028 (when isearch-success ; only if search was successful
24029 (if (featurep 'xemacs)
24030 ;; Under XEmacs, the hook is run in the correct place,
24031 ;; we directly show the context.
24032 (org-show-context 'isearch)
24033 ;; In Emacs the hook runs *before* restoring the overlays.
24034 ;; So we have to use a one-time post-command-hook to do this.
24035 ;; (Emacs 22 has a special variable, see function `org-mode')
24036 (unless (and (boundp 'isearch-mode-end-hook-quit)
24037 isearch-mode-end-hook-quit)
24038 ;; Only when the isearch was not quitted.
24039 (org-add-hook 'post-command-hook 'org-isearch-post-command
24040 'append 'local)))
24041 (org-fix-ellipsis-at-bol)))
24043 (defun org-isearch-post-command ()
24044 "Remove self from hook, and show context."
24045 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
24046 (org-show-context 'isearch))
24049 ;;;; Integration with and fixes for other packages
24051 ;;; Imenu support
24053 (defvar org-imenu-markers nil
24054 "All markers currently used by Imenu.")
24055 (make-variable-buffer-local 'org-imenu-markers)
24057 (defun org-imenu-new-marker (&optional pos)
24058 "Return a new marker for use by Imenu, and remember the marker."
24059 (let ((m (make-marker)))
24060 (move-marker m (or pos (point)))
24061 (push m org-imenu-markers)
24064 (defun org-imenu-get-tree ()
24065 "Produce the index for Imenu."
24066 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
24067 (setq org-imenu-markers nil)
24068 (let* ((n org-imenu-depth)
24069 (re (concat "^" (org-get-limited-outline-regexp)))
24070 (subs (make-vector (1+ n) nil))
24071 (last-level 0)
24072 m level head0 head)
24073 (save-excursion
24074 (save-restriction
24075 (widen)
24076 (goto-char (point-max))
24077 (while (re-search-backward re nil t)
24078 (setq level (org-reduced-level (funcall outline-level)))
24079 (when (and (<= level n)
24080 (looking-at org-complex-heading-regexp)
24081 (setq head0 (org-match-string-no-properties 4)))
24082 (setq head (org-link-display-format head0)
24083 m (org-imenu-new-marker))
24084 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24085 (if (>= level last-level)
24086 (push (cons head m) (aref subs level))
24087 (push (cons head (aref subs (1+ level))) (aref subs level))
24088 (loop for i from (1+ level) to n do (aset subs i nil)))
24089 (setq last-level level)))))
24090 (aref subs 1)))
24092 (eval-after-load "imenu"
24093 '(progn
24094 (add-hook 'imenu-after-jump-hook
24095 (lambda ()
24096 (if (derived-mode-p 'org-mode)
24097 (org-show-context 'org-goto))))))
24099 (defun org-link-display-format (link)
24100 "Replace a link with its the description.
24101 If there is no description, use the link target."
24102 (save-match-data
24103 (if (string-match org-bracket-link-analytic-regexp link)
24104 (replace-match (if (match-end 5)
24105 (match-string 5 link)
24106 (concat (match-string 1 link)
24107 (match-string 3 link)))
24108 nil t link)
24109 link)))
24111 (defun org-toggle-link-display ()
24112 "Toggle the literal or descriptive display of links."
24113 (interactive)
24114 (if org-descriptive-links
24115 (progn (org-remove-from-invisibility-spec '(org-link))
24116 (org-restart-font-lock)
24117 (setq org-descriptive-links nil))
24118 (progn (add-to-invisibility-spec '(org-link))
24119 (org-restart-font-lock)
24120 (setq org-descriptive-links t))))
24122 ;; Speedbar support
24124 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24125 "Overlay marking the agenda restriction line in speedbar.")
24126 (overlay-put org-speedbar-restriction-lock-overlay
24127 'face 'org-agenda-restriction-lock)
24128 (overlay-put org-speedbar-restriction-lock-overlay
24129 'help-echo "Agendas are currently limited to this item.")
24130 (org-detach-overlay org-speedbar-restriction-lock-overlay)
24132 (defun org-speedbar-set-agenda-restriction ()
24133 "Restrict future agenda commands to the location at point in speedbar.
24134 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
24135 (interactive)
24136 (require 'org-agenda)
24137 (let (p m tp np dir txt)
24138 (cond
24139 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24140 'org-imenu t))
24141 (setq m (get-text-property p 'org-imenu-marker))
24142 (with-current-buffer (marker-buffer m)
24143 (goto-char m)
24144 (org-agenda-set-restriction-lock 'subtree)))
24145 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24146 'speedbar-function 'speedbar-find-file))
24147 (setq tp (previous-single-property-change
24148 (1+ p) 'speedbar-function)
24149 np (next-single-property-change
24150 tp 'speedbar-function)
24151 dir (speedbar-line-directory)
24152 txt (buffer-substring-no-properties (or tp (point-min))
24153 (or np (point-max))))
24154 (with-current-buffer (find-file-noselect
24155 (let ((default-directory dir))
24156 (expand-file-name txt)))
24157 (unless (derived-mode-p 'org-mode)
24158 (user-error "Cannot restrict to non-Org-mode file"))
24159 (org-agenda-set-restriction-lock 'file)))
24160 (t (user-error "Don't know how to restrict Org-mode's agenda")))
24161 (move-overlay org-speedbar-restriction-lock-overlay
24162 (point-at-bol) (point-at-eol))
24163 (setq current-prefix-arg nil)
24164 (org-agenda-maybe-redo)))
24166 (defvar speedbar-file-key-map)
24167 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24168 (eval-after-load "speedbar"
24169 '(progn
24170 (speedbar-add-supported-extension ".org")
24171 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24172 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24173 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24174 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24175 (add-hook 'speedbar-visiting-tag-hook
24176 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24178 ;;; Fixes and Hacks for problems with other packages
24180 (defun org-mode-flyspell-verify ()
24181 "Function used for `flyspell-generic-check-word-predicate'."
24182 (if (org-at-heading-p)
24183 ;; At a headline or an inlinetask, check title only. This is
24184 ;; faster than relying on `org-element-at-point'.
24185 (and (save-excursion (beginning-of-line)
24186 (and (let ((case-fold-search t))
24187 (not (looking-at "\\*+ END[ \t]*$")))
24188 (looking-at org-complex-heading-regexp)))
24189 (match-beginning 4)
24190 (>= (point) (match-beginning 4))
24191 (or (not (match-beginning 5))
24192 (< (point) (match-beginning 5))))
24193 (let* ((element (org-element-at-point))
24194 (post-affiliated (org-element-property :post-affiliated element))
24195 (object-check
24196 (function
24197 ;; Non-nil if checks can be done for object at point.
24198 (lambda ()
24199 (let ((object (save-excursion
24200 (when (org-looking-at-p "\\>") (backward-char))
24201 (org-element-context element))))
24202 (case (org-element-type object)
24203 ;; Prevent checks in links due to keybinding conflict
24204 ;; with Flyspell.
24205 ((code entity export-snippet inline-babel-call
24206 inline-src-block line-break latex-fragment link macro
24207 statistics-cookie target timestamp verbatim)
24208 nil)
24209 (footnote-reference
24210 ;; Only in inline footnotes, within the definition.
24211 (and (eq (org-element-property :type object) 'inline)
24212 (< (save-excursion
24213 (goto-char (org-element-property :begin object))
24214 (search-forward ":" nil t 2))
24215 (point))))
24216 (otherwise t)))))))
24217 (cond
24218 ;; Ignore checks in all affiliated keywords but captions.
24219 ((and post-affiliated (< (point) post-affiliated))
24220 (and (save-excursion
24221 (beginning-of-line)
24222 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
24223 (> (point) (match-end 0))
24224 (funcall object-check)))
24225 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
24226 ((and org-log-into-drawer
24227 (let ((log (or (org-string-nw-p org-log-into-drawer) "LOGBOOK"))
24228 (parent element))
24229 (while (and parent (not (eq (org-element-type parent) 'drawer)))
24230 (setq parent (org-element-property :parent parent)))
24231 (and parent
24232 (eq (compare-strings
24233 log nil nil
24234 (org-element-property :drawer-name parent) nil nil t)
24235 t))))
24236 nil)
24238 (case (org-element-type element)
24239 ((comment quote-section) t)
24240 (comment-block
24241 ;; Allow checks between block markers, not on them.
24242 (and (> (line-beginning-position)
24243 (org-element-property :post-affiliated element))
24244 (save-excursion
24245 (end-of-line)
24246 (skip-chars-forward " \r\t\n")
24247 (< (point) (org-element-property :end element)))))
24248 ;; Arbitrary list of keywords where checks are meaningful.
24249 ;; Make sure point is on the value part of the element.
24250 (keyword
24251 (and (member (org-element-property :key element)
24252 '("DESCRIPTION" "TITLE"))
24253 (< (save-excursion
24254 (beginning-of-line) (search-forward ":") (point))
24255 (point))))
24256 ;; Check is globally allowed in paragraphs verse blocks and
24257 ;; table rows (after affiliated keywords) but some objects
24258 ;; must not be affected.
24259 ((paragraph table-row verse-block)
24260 (and (>= (point) (org-element-property :contents-begin element))
24261 (< (point) (org-element-property :contents-end element))
24262 (funcall object-check)))))))))
24263 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
24265 (defun org-remove-flyspell-overlays-in (beg end)
24266 "Remove flyspell overlays in region."
24267 (and (org-bound-and-true-p flyspell-mode)
24268 (fboundp 'flyspell-delete-region-overlays)
24269 (flyspell-delete-region-overlays beg end)))
24271 (defvar flyspell-delayed-commands)
24272 (eval-after-load "flyspell"
24273 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
24275 ;; Make `bookmark-jump' shows the jump location if it was hidden.
24276 (eval-after-load "bookmark"
24277 '(if (boundp 'bookmark-after-jump-hook)
24278 ;; We can use the hook
24279 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
24280 ;; Hook not available, use advice
24281 (defadvice bookmark-jump (after org-make-visible activate)
24282 "Make the position visible."
24283 (org-bookmark-jump-unhide))))
24285 ;; Make sure saveplace shows the location if it was hidden
24286 (eval-after-load "saveplace"
24287 '(defadvice save-place-find-file-hook (after org-make-visible activate)
24288 "Make the position visible."
24289 (org-bookmark-jump-unhide)))
24291 ;; Make sure ecb shows the location if it was hidden
24292 (eval-after-load "ecb"
24293 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
24294 "Make hierarchy visible when jumping into location from ECB tree buffer."
24295 (if (derived-mode-p 'org-mode)
24296 (org-show-context))))
24298 (defun org-bookmark-jump-unhide ()
24299 "Unhide the current position, to show the bookmark location."
24300 (and (derived-mode-p 'org-mode)
24301 (or (outline-invisible-p)
24302 (save-excursion (goto-char (max (point-min) (1- (point))))
24303 (outline-invisible-p)))
24304 (org-show-context 'bookmark-jump)))
24306 ;; Make session.el ignore our circular variable
24307 (defvar session-globals-exclude)
24308 (eval-after-load "session"
24309 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24311 ;;;; Finish up
24313 (provide 'org)
24315 (run-hooks 'org-load-hook)
24317 ;;; org.el ends here